context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
using System;
using sys=System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using WindowsInstaller;
#pragma warning disable 1591
namespace WixSharp.UI
{
/// <summary>
/// Generic class that represents runtime properties of the MSI setup session as well as some <c>runtime</c>
/// properties of the product being installed (e.g. CodePage, Caption). It also Simplifies MSI execution
/// and provides automatic responses on the MSI Messages.
/// <para>
/// Normally <c>MsiSession</c> should be extended top meet the needs of the product (MSI) specific setup.</para>
/// </summary>
public class MsiSession : INotifyPropertyChanged
{
/// <summary>
/// Occurs when setup progress changed.
/// </summary>
public event EventHandler ProgressChanged;
/// <summary>
/// Occurs when setup completes.
/// </summary>
public event sys.Action SetupComplete;
/// <summary>
/// Occurs when setup starts.
/// </summary>
public event sys.Action SetupStarted;
/// <summary>
/// Occurs when new setup action started.
/// </summary>
public event EventHandler ActionStarted;
/// <summary>
/// The UI thread marshalling delegate. It should be set for the environments where cross-thread calls
/// must be marshalled (e.g. WPF, WinForms). Not needed otherwise (e.g. Console application).
/// </summary>
public sys.Action<sys.Action> InUiThread = (action) => action();
void NotifyHostOnProgress()
{
InUiThread(() =>
{
if (ProgressChanged != null)
ProgressChanged(this, EventArgs.Empty);
});
}
void NotifyHostOnActionStarted()
{
InUiThread(() =>
{
if (ActionStarted != null)
ActionStarted(this, EventArgs.Empty);
});
}
int progressTotal = 100;
/// <summary>
/// Gets or sets the progress total.
/// </summary>
/// <value>The progress total.</value>
public int ProgressTotal
{
get { return progressTotal; }
protected set
{
progressTotal = value;
OnPropertyChanged("ProgressTotal");
NotifyHostOnProgress();
}
}
int progressCurrentPosition = 0;
/// <summary>
/// Gets or sets the progress current position.
/// </summary>
/// <value>The progress current position.</value>
public int ProgressCurrentPosition
{
get { return progressCurrentPosition; }
protected set
{
Thread.Sleep(ProgressStepDelay);
progressCurrentPosition = value;
OnPropertyChanged("ProgressCurrentPosition");
NotifyHostOnProgress();
}
}
/// <summary>
/// The progress step delay. It is a "for-testing" feature. Set it to positive value (number of milliseconds)
/// to artificially slow down the installation process. The default value is 0.
/// </summary>
public static int ProgressStepDelay = 0;
string currentActionName = null;
/// <summary>
/// Gets or sets the name of the current action.
/// </summary>
/// <value>
/// The name of the current action.
/// </value>
public string CurrentActionName
{
get { return currentActionName; }
protected set
{
var newValue = (value ?? "").Trim();
currentActionName = newValue;
OnPropertyChanged("CurrentActionName");
//MSI Runtime can periodically fire null-CurrentAction
if (!string.IsNullOrWhiteSpace(CurrentActionName))
NotifyHostOnActionStarted();
}
}
int language;
/// <summary>
/// Gets or sets the product language.
/// </summary>
/// <value>The language.</value>
public int Language
{
get { return language; }
protected set
{
language = value;
OnPropertyChanged("Language");
}
}
int codePage;
/// <summary>
/// Gets or sets the product CodePage.
/// </summary>
/// <value>The product CodePage.</value>
public int CodePage
{
get { return codePage; }
protected set
{
codePage = value;
OnPropertyChanged("CodePage");
}
}
bool canCancel;
/// <summary>
/// Gets or sets the flag indication the the user can cancel the setup in progress.
/// </summary>
/// <value>The can cancel.</value>
public bool CanCancel
{
get { return canCancel; }
protected set
{
canCancel = value;
OnPropertyChanged("CanCancel");
}
}
string caption;
/// <summary>
/// Gets or sets the setup window caption.
/// </summary>
/// <value>The caption.</value>
public string Caption
{
get { return caption; }
protected set
{
caption = value;
OnPropertyChanged("Caption");
}
}
int ticksPerActionDataMessage;
protected int TicksPerActionDataMessage
{
get { return ticksPerActionDataMessage; }
set
{
ticksPerActionDataMessage = value;
OnPropertyChanged("TicksPerActionDataMessage");
}
}
bool isProgressForwardDirection;
/// <summary>
/// Gets or sets a value indicating whether the progress steps are changing in the forward direction.
/// </summary>
/// <value>
/// <c>true</c> if the progress changes are in forward direction; otherwise, <c>false</c>.
/// </value>
public bool IsProgressForwardDirection
{
get { return isProgressForwardDirection; }
protected set
{
isProgressForwardDirection = value;
OnPropertyChanged("IsProgressForwardDirection");
}
}
bool isProgressTimeEstimationAccurate;
protected bool IsProgressTimeEstimationAccurate
{
get { return isProgressTimeEstimationAccurate; }
set
{
isProgressTimeEstimationAccurate = value;
OnPropertyChanged("IsProgressTimeEstimationAccurate");
}
}
bool cancelRequested;
/// <summary>
/// Gets or sets the CancelRequested flag. It should beset to <c>true</c> if user wants to cancel the setup in progress.
/// </summary>
/// <value>The CancelRequested value.</value>
public bool CancelRequested
{
get { return cancelRequested; }
set
{
cancelRequested = value;
OnPropertyChanged("CancelRequested");
}
}
/// <summary>
/// Called when ActionData MSI message is received.
/// </summary>
/// <param name="data">The message data.</param>
public virtual void OnActionData(string data)
{
//if (!string.IsNullOrWhiteSpace(data))
// Debug.WriteLine("ActionData>\t\t" + data);
}
/// <summary>
/// Called when Error event occurs (MSI Error message is received or an internal error condition triggered).
/// </summary>
/// <param name="data">The message data.</param>
/// <param name="fatal">if set to <c>true</c> the error is fatal.</param>
/// <param name="relatedMessageType">Type of the related message. Note the error may be associated with the internal
/// error condition (e.g. exception is raised). </param>
public virtual void OnError(string data, bool fatal, MsiInstallMessage? relatedMessageType = null)
{
//Debug.WriteLine("Error>\t\t" + data);
}
/// <summary>
/// Called when Warning MSI message is received.
/// </summary>
/// <param name="data">The message data.</param>
public virtual void OnWarning(string data)
{
//Debug.WriteLine("Warning>\t\t" + data);
}
/// <summary>
/// Called when User MSI message is received.
/// </summary>
/// <param name="data">The message data.</param>
public virtual void OnUser(string data)
{
//Debug.WriteLine("User>\t\t" + data);
}
/// <summary>
/// Called when Info MSI message is received.
/// </summary>
/// <param name="data">The message data.</param>
public virtual void OnInfo(string data)
{
//Debug.WriteLine("Info>\t\t" + data);
}
/// <summary>
/// Enables the MSI runtime logging to the specified log file.
/// </summary>
/// <param name="logFile">The log file.</param>
/// <param name="mode">The logging mode.</param>
public void EnableLog(string logFile, MsiInstallLogMode mode = MsiInstallLogMode.Info | MsiInstallLogMode.Progress | MsiInstallLogMode.PropertyDump |
MsiInstallLogMode.Error | MsiInstallLogMode.User | MsiInstallLogMode.ActionData)
{
MsiInterop.MsiEnableLog(mode, logFile, MsiLogAttribute.FlushEachLine);
}
/// <summary>
/// Executes the install sequence from the specified MSI file.
/// </summary>
/// <param name="msiFile">The MSI file.</param>
/// <param name="msiParams">The MSI params.</param>
public void ExecuteInstall(string msiFile, string msiParams = null)
{
Execute(msiFile, msiParams ?? "");
}
/// <summary>
/// Executes the uninstall sequence from the specified MSI file.
/// </summary>
/// <param name="msiFile">The MSI file.</param>
/// <param name="msiParams">The MSI params.</param>
public void ExecuteUninstall(string msiFile, string msiParams = null)
{
Execute(msiFile, "REMOVE=ALL " + (msiParams ?? ""));
}
/// <summary>
/// Executes the MSI file with the specified MSI parameters.
/// </summary>
/// <param name="msiFile">The MSI file.</param>
/// <param name="msiParams">The MSI parameters.</param>
/// <exception cref="System.ApplicationException"></exception>
public void Execute(string msiFile, string msiParams)
{
MsiInstallUIHandler uiHandler = null;
IntPtr parent = IntPtr.Zero;
MsiInstallUILevel oldLevel = MsiInterop.MsiSetInternalUI(MsiInstallUILevel.None | MsiInstallUILevel.SourceResOnly, ref parent);
MsiInstallUIHandler oldHandler = null;
try
{
uiHandler = new MsiInstallUIHandler(OnExternalUI); //must be kept alive until the end of the MsiInstallProduct call
if (SetupStarted != null)
InUiThread(SetupStarted);
oldHandler = MsiInterop.MsiSetExternalUI(uiHandler, MsiInstallLogMode.ExternalUI, IntPtr.Zero);
MsiError ret = MsiInterop.MsiInstallProduct(msiFile, msiParams);
CurrentActionName = "";
if (ret != MsiError.Success)
{
Console.WriteLine(string.Format("Failed to install -- {0}", ret));
//(ret==ProductVersion) Another version of this product is already installed
throw new ApplicationException(string.Format("Failed to install -- {0}", ret));
}
}
catch (Exception e)
{
OnError("Application initialization error: " + e.ToString(), false);
CurrentActionName = "";
throw;
// do something meaningful
}
finally
{
if (oldHandler != null)
{
MsiInterop.MsiSetExternalUI(oldHandler, MsiInstallLogMode.None, IntPtr.Zero);
oldHandler = null;
}
//It is important to reference uiHandler here to keep it alive till the end.
//The debug build is more forgiving and referencing uiHandler is not essential as the code is not optimized
if (uiHandler != null)
uiHandler = null;
MsiInterop.MsiSetInternalUI(oldLevel, ref parent);
if (SetupComplete != null)
InUiThread(SetupComplete);
}
}
int OnExternalUI(IntPtr context, uint messageType, string message)
{
MsiInstallMessage msgType = (MsiInstallMessage)(MsiInterop.MessageTypeMask & messageType);
return OnMessage(message, msgType);
}
/// <summary>
/// Called when MSI message is received. It is actual the MSI <c>Message Loop</c>.
/// </summary>
/// <param name="message">The message data.</param>
/// <param name="messageType">Type of the message.</param>
/// <returns>The integer as per MSI documentation.</returns>
protected virtual int OnMessage(string message, MsiInstallMessage messageType)
{
try
{
switch (messageType)
{
case MsiInstallMessage.ActionData:
this.OnActionData(message);
return (int)DialogResult.OK;
case MsiInstallMessage.ActionStart:
this.CurrentActionName = message.Substring(message.LastIndexOf(".") + 1);
return (int)DialogResult.OK;
case MsiInstallMessage.CommonData:
string[] data = MsiParser.ParseCommonData(message);
if (data != null && data[0] != null)
{
switch (data.MSI<int>(1))
{
case 0: // language
{
Language = data.MSI<int>(2);
CodePage = data.MSI<int>(3);
}
break;
case 1: // caption
{
Caption = data.MSI<string>(2);
}
break;
case 2: // CancelShow
{
CanCancel = data.MSI<int>(2) == 1;
}
break;
default: break;
}
}
return (int)DialogResult.OK;
case MsiInstallMessage.Error:
OnError(message, false, MsiInstallMessage.Error);
return 1;
case MsiInstallMessage.FatalExit:
OnError(message, true, MsiInstallMessage.FatalExit);
return 1;
case MsiInstallMessage.FilesInUse:
// display in use files in a dialog, informing the user
// that they should close whatever applications are using
// them. You must return the DialogResult to the service
// if displayed.
{
//If locked files need to be reported to the user then MsiSetExternalUIRecord should be used
OnError("Files in use", true, MsiInstallMessage.FilesInUse);
return 0; // we didn't handle it in this case!
}
case MsiInstallMessage.Info:
this.OnInfo(message);
return 1;
case MsiInstallMessage.Initialize:
return 1;
case MsiInstallMessage.OutOfDiskSpace:
{
OnError("Out Of Disk Space", true, MsiInstallMessage.OutOfDiskSpace);
break;
}
case MsiInstallMessage.Progress:
{
string[] fields = MsiParser.ParseProgressString(message);
if (null == fields || null == fields[0])
{
return (int)DialogResult.OK;
}
switch (fields.MSI<int>(1))
{
case 0: // reset progress bar
{
ProgressTotal = fields.MSI<int>(2);
IsProgressForwardDirection = fields.MSI<int>(3) == 0;
IsProgressTimeEstimationAccurate = fields.MSI<int>(4) == 0;
ProgressCurrentPosition = IsProgressForwardDirection ? 0 : ProgressTotal;
}
break;
case 1: // action info
{
if (this.ProgressTotal == 0)
return (int)DialogResult.OK; //The external handler should not act upon any of these messages until the first a Reset progress message is received.
if (fields.MSI<int>(3) == 1)
TicksPerActionDataMessage = fields.MSI<int>(2);
}
break;
case 2: // progress
{
if (this.ProgressTotal == 0)
return (int)DialogResult.OK; //The external handler should not act upon any of these messages until the first a Reset progress message is received.
if (this.ProgressTotal != 0) //initialized
{
if (IsProgressForwardDirection)
ProgressCurrentPosition = ProgressCurrentPosition + fields.MSI<int>(2);
else
ProgressCurrentPosition = ProgressCurrentPosition - fields.MSI<int>(2);
}
}
break;
default: break;
}
if (this.CancelRequested)
return (int)DialogResult.Cancel;
else
return (int)DialogResult.OK;
}
case MsiInstallMessage.ResolveSource:
return 0;
case MsiInstallMessage.ShowDialog:
return (int)DialogResult.OK;
case MsiInstallMessage.Terminate:
return (int)DialogResult.OK;
case MsiInstallMessage.User:
OnUser(message);
return 1;
case MsiInstallMessage.Warning:
OnWarning(message);
return 1;
default: break;
}
}
catch (Exception e)
{
// do something meaningful, but don't re-throw here.
OnError("Application error: " + e.ToString(), false);
}
return 0;
}
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
InUiThread(() =>
PropertyChanged(this, new PropertyChangedEventArgs(propertyName)));
}
}
/// <summary>
/// Occurs when some of the current instance property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
namespace Amazon.Redshift.Model
{
/// <summary>
/// <para>Describes the result of a cluster resize operation.</para>
/// </summary>
public class DescribeResizeResult
{
private string targetNodeType;
private int? targetNumberOfNodes;
private string targetClusterType;
private string status;
private List<string> importTablesCompleted = new List<string>();
private List<string> importTablesInProgress = new List<string>();
private List<string> importTablesNotStarted = new List<string>();
/// <summary>
/// The node type that the cluster will have after the resize is complete.
///
/// </summary>
public string TargetNodeType
{
get { return this.targetNodeType; }
set { this.targetNodeType = value; }
}
/// <summary>
/// Sets the TargetNodeType property
/// </summary>
/// <param name="targetNodeType">The value to set for the TargetNodeType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithTargetNodeType(string targetNodeType)
{
this.targetNodeType = targetNodeType;
return this;
}
// Check to see if TargetNodeType property is set
internal bool IsSetTargetNodeType()
{
return this.targetNodeType != null;
}
/// <summary>
/// The number of nodes that the cluster will have after the resize is complete.
///
/// </summary>
public int TargetNumberOfNodes
{
get { return this.targetNumberOfNodes ?? default(int); }
set { this.targetNumberOfNodes = value; }
}
/// <summary>
/// Sets the TargetNumberOfNodes property
/// </summary>
/// <param name="targetNumberOfNodes">The value to set for the TargetNumberOfNodes property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithTargetNumberOfNodes(int targetNumberOfNodes)
{
this.targetNumberOfNodes = targetNumberOfNodes;
return this;
}
// Check to see if TargetNumberOfNodes property is set
internal bool IsSetTargetNumberOfNodes()
{
return this.targetNumberOfNodes.HasValue;
}
/// <summary>
/// The cluster type after the resize is complete. Valid Values: <c>multi-node</c> | <c>single-node</c>
///
/// </summary>
public string TargetClusterType
{
get { return this.targetClusterType; }
set { this.targetClusterType = value; }
}
/// <summary>
/// Sets the TargetClusterType property
/// </summary>
/// <param name="targetClusterType">The value to set for the TargetClusterType property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithTargetClusterType(string targetClusterType)
{
this.targetClusterType = targetClusterType;
return this;
}
// Check to see if TargetClusterType property is set
internal bool IsSetTargetClusterType()
{
return this.targetClusterType != null;
}
/// <summary>
/// The status of the resize operation. Valid Values: <c>NONE</c> | <c>IN_PROGRESS</c> | <c>FAILED</c> | <c>SUCCEEDED</c>
///
/// </summary>
public string Status
{
get { return this.status; }
set { this.status = value; }
}
/// <summary>
/// Sets the Status property
/// </summary>
/// <param name="status">The value to set for the Status property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithStatus(string status)
{
this.status = status;
return this;
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this.status != null;
}
/// <summary>
/// The names of tables that have been completely imported . Valid Values: List of table names.
///
/// </summary>
public List<string> ImportTablesCompleted
{
get { return this.importTablesCompleted; }
set { this.importTablesCompleted = value; }
}
/// <summary>
/// Adds elements to the ImportTablesCompleted collection
/// </summary>
/// <param name="importTablesCompleted">The values to add to the ImportTablesCompleted collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesCompleted(params string[] importTablesCompleted)
{
foreach (string element in importTablesCompleted)
{
this.importTablesCompleted.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ImportTablesCompleted collection
/// </summary>
/// <param name="importTablesCompleted">The values to add to the ImportTablesCompleted collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesCompleted(IEnumerable<string> importTablesCompleted)
{
foreach (string element in importTablesCompleted)
{
this.importTablesCompleted.Add(element);
}
return this;
}
// Check to see if ImportTablesCompleted property is set
internal bool IsSetImportTablesCompleted()
{
return this.importTablesCompleted.Count > 0;
}
/// <summary>
/// The names of tables that are being currently imported. Valid Values: List of table names.
///
/// </summary>
public List<string> ImportTablesInProgress
{
get { return this.importTablesInProgress; }
set { this.importTablesInProgress = value; }
}
/// <summary>
/// Adds elements to the ImportTablesInProgress collection
/// </summary>
/// <param name="importTablesInProgress">The values to add to the ImportTablesInProgress collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesInProgress(params string[] importTablesInProgress)
{
foreach (string element in importTablesInProgress)
{
this.importTablesInProgress.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ImportTablesInProgress collection
/// </summary>
/// <param name="importTablesInProgress">The values to add to the ImportTablesInProgress collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesInProgress(IEnumerable<string> importTablesInProgress)
{
foreach (string element in importTablesInProgress)
{
this.importTablesInProgress.Add(element);
}
return this;
}
// Check to see if ImportTablesInProgress property is set
internal bool IsSetImportTablesInProgress()
{
return this.importTablesInProgress.Count > 0;
}
/// <summary>
/// The names of tables that have not been yet imported. Valid Values: List of table names
///
/// </summary>
public List<string> ImportTablesNotStarted
{
get { return this.importTablesNotStarted; }
set { this.importTablesNotStarted = value; }
}
/// <summary>
/// Adds elements to the ImportTablesNotStarted collection
/// </summary>
/// <param name="importTablesNotStarted">The values to add to the ImportTablesNotStarted collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesNotStarted(params string[] importTablesNotStarted)
{
foreach (string element in importTablesNotStarted)
{
this.importTablesNotStarted.Add(element);
}
return this;
}
/// <summary>
/// Adds elements to the ImportTablesNotStarted collection
/// </summary>
/// <param name="importTablesNotStarted">The values to add to the ImportTablesNotStarted collection </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public DescribeResizeResult WithImportTablesNotStarted(IEnumerable<string> importTablesNotStarted)
{
foreach (string element in importTablesNotStarted)
{
this.importTablesNotStarted.Add(element);
}
return this;
}
// Check to see if ImportTablesNotStarted property is set
internal bool IsSetImportTablesNotStarted()
{
return this.importTablesNotStarted.Count > 0;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using Microsoft.Web.Services3;
using WebsitePanel.Providers.Common;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.RemoteDesktopServices;
using WebsitePanel.EnterpriseServer.Base.RDS;
namespace WebsitePanel.EnterpriseServer
{
/// <summary>
/// Summary description for esApplicationsInstaller
/// </summary>
[WebService(Namespace = "http://smbsaas/websitepanel/enterpriseserver")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
[ToolboxItem(false)]
public class esRemoteDesktopServices : System.Web.Services.WebService
{
[WebMethod]
public RdsCollection GetRdsCollection(int collectionId)
{
return RemoteDesktopServicesController.GetRdsCollection(collectionId);
}
[WebMethod]
public RdsCollectionSettings GetRdsCollectionSettings(int collectionId)
{
return RemoteDesktopServicesController.GetRdsCollectionSettings(collectionId);
}
[WebMethod]
public List<RdsCollection> GetOrganizationRdsCollections(int itemId)
{
return RemoteDesktopServicesController.GetOrganizationRdsCollections(itemId);
}
[WebMethod]
public int AddRdsCollection(int itemId, RdsCollection collection)
{
return RemoteDesktopServicesController.AddRdsCollection(itemId, collection);
}
[WebMethod]
public ResultObject EditRdsCollection(int itemId, RdsCollection collection)
{
return RemoteDesktopServicesController.EditRdsCollection(itemId, collection);
}
[WebMethod]
public ResultObject EditRdsCollectionSettings(int itemId, RdsCollection collection)
{
return RemoteDesktopServicesController.EditRdsCollectionSettings(itemId, collection);
}
[WebMethod]
public RdsCollectionPaged GetRdsCollectionsPaged(int itemId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return RemoteDesktopServicesController.GetRdsCollectionsPaged(itemId, filterColumn, filterValue, sortColumn,
startRow, maximumRows);
}
[WebMethod]
public ResultObject RemoveRdsCollection(int itemId, RdsCollection collection)
{
return RemoteDesktopServicesController.RemoveRdsCollection(itemId, collection);
}
[WebMethod]
public RdsServersPaged GetRdsServersPaged(string filterColumn, string filterValue, string sortColumn,
int startRow, int maximumRows)
{
return RemoteDesktopServicesController.GetRdsServersPaged(filterColumn, filterValue, sortColumn, startRow,
maximumRows);
}
[WebMethod]
public RdsServersPaged GetFreeRdsServersPaged(int packageId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return RemoteDesktopServicesController.GetFreeRdsServersPaged(packageId, filterColumn, filterValue,
sortColumn, startRow, maximumRows);
}
[WebMethod]
public RdsServersPaged GetOrganizationRdsServersPaged(int itemId, int? collectionId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return RemoteDesktopServicesController.GetOrganizationRdsServersPaged(itemId, collectionId, filterColumn, filterValue,
sortColumn, startRow, maximumRows);
}
[WebMethod]
public RdsServersPaged GetOrganizationFreeRdsServersPaged(int itemId, string filterColumn, string filterValue,
string sortColumn, int startRow, int maximumRows)
{
return RemoteDesktopServicesController.GetOrganizationFreeRdsServersPaged(itemId, filterColumn, filterValue,
sortColumn, startRow, maximumRows);
}
[WebMethod]
public RdsServer GetRdsServer(int rdsSeverId)
{
return RemoteDesktopServicesController.GetRdsServer(rdsSeverId);
}
[WebMethod]
public ResultObject SetRDServerNewConnectionAllowed(int itemId, bool newConnectionAllowed, int rdsSeverId)
{
return RemoteDesktopServicesController.SetRDServerNewConnectionAllowed(itemId, newConnectionAllowed, rdsSeverId);
}
[WebMethod]
public List<RdsServer> GetCollectionRdsServers(int collectionId)
{
return RemoteDesktopServicesController.GetCollectionRdsServers(collectionId);
}
[WebMethod]
public List<RdsServer> GetOrganizationRdsServers(int itemId)
{
return RemoteDesktopServicesController.GetOrganizationRdsServers(itemId);
}
[WebMethod]
public ResultObject AddRdsServer(RdsServer rdsServer)
{
return RemoteDesktopServicesController.AddRdsServer(rdsServer);
}
[WebMethod]
public ResultObject AddRdsServerToCollection(int itemId, RdsServer rdsServer, RdsCollection rdsCollection)
{
return RemoteDesktopServicesController.AddRdsServerToCollection(itemId, rdsServer, rdsCollection);
}
[WebMethod]
public ResultObject AddRdsServerToOrganization(int itemId, int serverId)
{
return RemoteDesktopServicesController.AddRdsServerToOrganization(itemId, serverId);
}
[WebMethod]
public ResultObject RemoveRdsServer(int rdsServerId)
{
return RemoteDesktopServicesController.RemoveRdsServer(rdsServerId);
}
[WebMethod]
public ResultObject RemoveRdsServerFromCollection(int itemId, RdsServer rdsServer, RdsCollection rdsCollection)
{
return RemoteDesktopServicesController.RemoveRdsServerFromCollection(itemId, rdsServer, rdsCollection);
}
[WebMethod]
public ResultObject RemoveRdsServerFromOrganization(int itemId, int rdsServerId)
{
return RemoteDesktopServicesController.RemoveRdsServerFromOrganization(itemId, rdsServerId);
}
[WebMethod]
public ResultObject UpdateRdsServer(RdsServer rdsServer)
{
return RemoteDesktopServicesController.UpdateRdsServer(rdsServer);
}
[WebMethod]
public List<OrganizationUser> GetRdsCollectionUsers(int collectionId)
{
return RemoteDesktopServicesController.GetRdsCollectionUsers(collectionId);
}
[WebMethod]
public ResultObject SetUsersToRdsCollection(int itemId, int collectionId, List<OrganizationUser> users)
{
return RemoteDesktopServicesController.SetUsersToRdsCollection(itemId, collectionId, users);
}
[WebMethod]
public List<RemoteApplication> GetCollectionRemoteApplications(int itemId, string collectionName)
{
return RemoteDesktopServicesController.GetCollectionRemoteApplications(itemId, collectionName);
}
[WebMethod]
public List<StartMenuApp> GetAvailableRemoteApplications(int itemId, string collectionName)
{
return RemoteDesktopServicesController.GetAvailableRemoteApplications(itemId, collectionName);
}
[WebMethod]
public ResultObject AddRemoteApplicationToCollection(int itemId, RdsCollection collection, RemoteApplication application)
{
return RemoteDesktopServicesController.AddRemoteApplicationToCollection(itemId, collection, application);
}
[WebMethod]
public ResultObject RemoveRemoteApplicationFromCollection(int itemId, RdsCollection collection, RemoteApplication application)
{
return RemoteDesktopServicesController.RemoveRemoteApplicationFromCollection(itemId, collection, application);
}
[WebMethod]
public ResultObject SetRemoteApplicationsToRdsCollection(int itemId, int collectionId, List<RemoteApplication> remoteApps)
{
return RemoteDesktopServicesController.SetRemoteApplicationsToRdsCollection(itemId, collectionId, remoteApps);
}
[WebMethod]
public int GetOrganizationRdsUsersCount(int itemId)
{
return RemoteDesktopServicesController.GetOrganizationRdsUsersCount(itemId);
}
[WebMethod]
public int GetOrganizationRdsServersCount(int itemId)
{
return RemoteDesktopServicesController.GetOrganizationRdsServersCount(itemId);
}
[WebMethod]
public int GetOrganizationRdsCollectionsCount(int itemId)
{
return RemoteDesktopServicesController.GetOrganizationRdsCollectionsCount(itemId);
}
[WebMethod]
public List<string> GetApplicationUsers(int itemId, int collectionId, RemoteApplication remoteApp)
{
return RemoteDesktopServicesController.GetApplicationUsers(itemId, collectionId, remoteApp);
}
[WebMethod]
public ResultObject SetApplicationUsers(int itemId, int collectionId, RemoteApplication remoteApp, List<string> users)
{
return RemoteDesktopServicesController.SetApplicationUsers(itemId, collectionId, remoteApp, users);
}
[WebMethod]
public List<RdsUserSession> GetRdsUserSessions(int collectionId)
{
return RemoteDesktopServicesController.GetRdsUserSessions(collectionId);
}
[WebMethod]
public ResultObject LogOffRdsUser(int itemId, string unifiedSessionId, string hostServer)
{
return RemoteDesktopServicesController.LogOffRdsUser(itemId, unifiedSessionId, hostServer);
}
[WebMethod]
public List<string> GetRdsCollectionSessionHosts(int collectionId)
{
return RemoteDesktopServicesController.GetRdsCollectionSessionHosts(collectionId);
}
[WebMethod]
public RdsServerInfo GetRdsServerInfo(int? itemId, string fqdnName)
{
return RemoteDesktopServicesController.GetRdsServerInfo(itemId, fqdnName);
}
[WebMethod]
public string GetRdsServerStatus(int? itemId, string fqdnName)
{
return RemoteDesktopServicesController.GetRdsServerStatus(itemId, fqdnName);
}
[WebMethod]
public ResultObject ShutDownRdsServer(int? itemId, string fqdnName)
{
return RemoteDesktopServicesController.ShutDownRdsServer(itemId, fqdnName);
}
[WebMethod]
public ResultObject RestartRdsServer(int? itemId, string fqdnName)
{
return RemoteDesktopServicesController.RestartRdsServer(itemId, fqdnName);
}
[WebMethod]
public List<OrganizationUser> GetRdsCollectionLocalAdmins(int collectionId)
{
return RemoteDesktopServicesController.GetRdsCollectionLocalAdmins(collectionId);
}
[WebMethod]
public ResultObject SaveRdsCollectionLocalAdmins(OrganizationUser[] users, int collectionId)
{
return RemoteDesktopServicesController.SaveRdsCollectionLocalAdmins(users, collectionId);
}
[WebMethod]
public ResultObject InstallSessionHostsCertificate(RdsServer rdsServer)
{
return RemoteDesktopServicesController.InstallSessionHostsCertificate(rdsServer);
}
[WebMethod]
public RdsCertificate GetRdsCertificateByServiceId(int serviceId)
{
return RemoteDesktopServicesController.GetRdsCertificateByServiceId(serviceId);
}
[WebMethod]
public RdsCertificate GetRdsCertificateByItemId(int? itemId)
{
return RemoteDesktopServicesController.GetRdsCertificateByItemId(itemId);
}
[WebMethod]
public ResultObject AddRdsCertificate(RdsCertificate certificate)
{
return RemoteDesktopServicesController.AddRdsCertificate(certificate);
}
[WebMethod]
public List<ServiceInfo> GetRdsServices()
{
return RemoteDesktopServicesController.GetRdsServices();
}
[WebMethod]
public string GetRdsSetupLetter(int itemId, int? accountId)
{
return RemoteDesktopServicesController.GetRdsSetupLetter(itemId, accountId);
}
[WebMethod]
public int SendRdsSetupLetter(int itemId, int? accountId, string to, string cc)
{
return RemoteDesktopServicesController.SendRdsSetupLetter(itemId, accountId, to, cc);
}
[WebMethod]
public RdsServerSettings GetRdsServerSettings(int serverId, string settingsName)
{
return RemoteDesktopServicesController.GetRdsServerSettings(serverId, settingsName);
}
[WebMethod]
public int UpdateRdsServerSettings(int serverId, string settingsName, RdsServerSettings settings)
{
return RemoteDesktopServicesController.UpdateRdsServerSettings(serverId, settingsName, settings);
}
[WebMethod]
public ResultObject ShadowSession(int itemId, string sessionId, bool control, string fqdName)
{
return RemoteDesktopServicesController.ShadowSession(itemId, sessionId, control, fqdName);
}
[WebMethod]
public ResultObject ImportCollection(int itemId, string collectionName)
{
return RemoteDesktopServicesController.ImportCollection(itemId, collectionName);
}
[WebMethod]
public int GetRemoteDesktopServiceId(int itemId)
{
return RemoteDesktopServicesController.GetRemoteDesktopServiceId(itemId);
}
[WebMethod]
public ResultObject SendMessage(RdsMessageRecipient[] recipients, string text, int itemId, int rdsCollectionId, string userName)
{
return RemoteDesktopServicesController.SendMessage(recipients, text, itemId, rdsCollectionId, userName);
}
[WebMethod]
public List<RdsMessage> GetRdsMessagesByCollectionId(int rdsCollectionId)
{
return RemoteDesktopServicesController.GetRdsMessagesByCollectionId(rdsCollectionId);
}
}
}
| |
//
// MainLoop.cs
//
// Authors:
// Alan McGovern [email protected]
//
// Copyright (C) 2008 Alan McGovern
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Mono.Ssdp.Internal;
using MonoTorrent.Common;
namespace MonoTorrent.Client
{
public delegate void MainLoopResult (object result);
public delegate object MainLoopJob();
public delegate void MainLoopTask();
public delegate bool TimeoutTask();
public class MainLoop
{
private class DelegateTask : ICacheable
{
private ManualResetEvent handle;
private bool isBlocking;
private MainLoopJob job;
private object jobResult;
private Exception storedException;
private MainLoopTask task;
private TimeoutTask timeout;
private bool timeoutResult;
public bool IsBlocking
{
get { return isBlocking; }
set { isBlocking = value; }
}
public MainLoopJob Job
{
get { return job; }
set { job = value; }
}
public Exception StoredException
{
get { return storedException; }
set { storedException = value; }
}
public MainLoopTask Task
{
get { return task; }
set { task = value; }
}
public TimeoutTask Timeout
{
get { return timeout; }
set { timeout = value; }
}
public object JobResult
{
get { return jobResult; }
}
public bool TimeoutResult
{
get { return timeoutResult; }
}
public ManualResetEvent WaitHandle
{
get { return handle; }
}
public DelegateTask()
{
handle = new ManualResetEvent(false);
}
public void Execute()
{
try
{
if (job != null)
jobResult = job();
else if (task != null)
task();
else if (timeout != null)
timeoutResult = timeout();
}
catch (Exception ex)
{
storedException = ex;
// FIXME: I assume this case can't happen. The only user interaction
// with the mainloop is with blocking tasks. Internally it's a big bug
// if i allow an exception to propagate to the mainloop.
if (!IsBlocking)
throw;
}
finally
{
handle.Set();
}
}
public void Initialise()
{
isBlocking = false;
job = null;
jobResult = null;
storedException = null;
task = null;
timeout = null;
timeoutResult = false;
}
}
TimeoutDispatcher dispatcher = new TimeoutDispatcher();
AutoResetEvent handle = new AutoResetEvent(false);
ICache<DelegateTask> cache = new Cache<DelegateTask>(true).Synchronize();
Queue<DelegateTask> tasks = new Queue<DelegateTask>();
internal Thread thread;
public MainLoop(string name)
{
thread = new Thread(Loop);
thread.IsBackground = true;
thread.Start();
}
void Loop()
{
while (true)
{
DelegateTask task = null;
lock (tasks)
{
if (tasks.Count > 0)
task = tasks.Dequeue();
}
if (task == null)
{
handle.WaitOne();
}
else
{
bool reuse = !task.IsBlocking;
task.Execute();
if (reuse)
cache.Enqueue(task);
}
}
}
private void Queue(DelegateTask task)
{
Queue(task, Priority.Normal);
}
private void Queue(DelegateTask task, Priority priority)
{
lock (tasks)
{
tasks.Enqueue(task);
handle.Set();
}
}
public void Queue(MainLoopTask task)
{
DelegateTask dTask = cache.Dequeue();
dTask.Task = task;
Queue(dTask);
}
public void QueueWait(MainLoopTask task)
{
DelegateTask dTask = cache.Dequeue();
dTask.Task = task;
try
{
QueueWait(dTask);
}
finally
{
cache.Enqueue(dTask);
}
}
public object QueueWait(MainLoopJob task)
{
DelegateTask dTask = cache.Dequeue();
dTask.Job = task;
try
{
QueueWait(dTask);
return dTask.JobResult;
}
finally
{
cache.Enqueue(dTask);
}
}
private void QueueWait(DelegateTask t)
{
t.WaitHandle.Reset();
t.IsBlocking = true;
if (Thread.CurrentThread == thread)
t.Execute();
else
Queue(t, Priority.Highest);
t.WaitHandle.WaitOne();
//if (t.StoredException != null)
//throw new TorrentException("Exception in mainloop", t.StoredException);
}
public uint QueueTimeout(TimeSpan span, TimeoutTask task)
{
DelegateTask dTask = cache.Dequeue();
dTask.Timeout = task;
return dispatcher.Add(span, delegate {
QueueWait(dTask);
return dTask.TimeoutResult;
});
}
public AsyncCallback Wrap(AsyncCallback callback)
{
return delegate(IAsyncResult result) {
Queue(delegate {
callback(result);
});
};
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Xml;
using log4net;
using Nini.Config;
using OpenSim.Framework;
namespace OpenSim
{
public class ConfigurationLoader
{
protected ConfigSettings m_configSettings;
protected OpenSimConfigSource m_config;
protected NetworkServersInfo m_networkServersInfo;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public ConfigurationLoader()
{
}
public OpenSimConfigSource LoadConfigSettings(IConfigSource configSource, out ConfigSettings configSettings,
out NetworkServersInfo networkInfo)
{
m_configSettings = configSettings = new ConfigSettings();
m_networkServersInfo = networkInfo = new NetworkServersInfo();
bool iniFileExists = false;
IConfig startupConfig = configSource.Configs["Startup"];
//old style or new style settings?
string iniFileName = startupConfig.GetString("inifile", "Halcyon.ini");
ApplicationBase.iniFilePath = Path.Combine(Util.configDir(), iniFileName);
string masterFileName = startupConfig.GetString("inimaster", String.Empty);
string masterfilePath = Path.Combine(Util.configDir(), masterFileName);
string iniDirName = startupConfig.GetString("inidirectory", "config");
//string iniDirPath = Path.Combine(Util.configDir(), iniDirName);
m_config = new OpenSimConfigSource();
m_config.Source = new IniConfigSource();
m_config.Source.Merge(DefaultConfig());
m_log.Info("[CONFIG] Reading configuration settings");
Uri configUri;
String xmlPath = Path.Combine(Util.configDir(), "Halcyon.xml");
//check for master .INI file (name passed in command line, no default), or XML over http
if (!String.IsNullOrEmpty(masterFileName)) // If a master file name is given ...
{
m_log.InfoFormat("[CONFIG] Reading config master file {0}", masterfilePath);
bool isMasterUri = Uri.TryCreate(masterFileName, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp;
if (!ReadConfig(masterFileName, masterfilePath, m_config, isMasterUri))
{
m_log.FatalFormat("[CONFIG] Could not open master config file {0}", masterfilePath);
}
}
if (Directory.Exists(iniDirName))
{
m_log.InfoFormat("Searching folder: {0} , for config ini files", iniDirName);
string[] fileEntries = Directory.GetFiles(iniDirName);
foreach (string filePath in fileEntries)
{
if (Path.GetExtension(filePath).ToLower() == ".ini")
{
// m_log.InfoFormat("reading ini file < {0} > from config dir", filePath);
ReadConfig(Path.GetFileName(filePath), filePath, m_config, false);
}
}
}
// Check for .INI file (either default or name passed on command
// line) or XML config source over http
bool isIniUri = Uri.TryCreate(iniFileName, UriKind.Absolute, out configUri) &&
configUri.Scheme == Uri.UriSchemeHttp;
iniFileExists = ReadConfig(iniFileName, ApplicationBase.iniFilePath, m_config, isIniUri);
if (!iniFileExists)
{
// check for a xml config file
if (File.Exists(xmlPath))
{
ApplicationBase.iniFilePath = xmlPath;
m_log.InfoFormat("Reading XML configuration from {0}", Path.GetFullPath(xmlPath));
iniFileExists = true;
m_config.Source = new XmlConfigSource();
m_config.Source.Merge(new XmlConfigSource(ApplicationBase.iniFilePath));
}
}
m_config.Source.Merge(configSource);
if (!iniFileExists)
{
m_log.FatalFormat("[CONFIG] Could not load any configuration");
if (!isIniUri)
m_log.FatalFormat("[CONFIG] Tried to load {0}, ", Path.GetFullPath(ApplicationBase.iniFilePath));
else
m_log.FatalFormat("[CONFIG] Tried to load from URI {0}, ", iniFileName);
m_log.FatalFormat("[CONFIG] and XML source {0}", Path.GetFullPath(xmlPath));
string sampleName = Path.GetFileNameWithoutExtension(ApplicationBase.iniFilePath) + ".sample.ini";
m_log.FatalFormat("[CONFIG] Did you copy the {0} file to {1}?", sampleName, ApplicationBase.iniFilePath);
Environment.Exit(1);
}
ReadConfigSettings();
return m_config;
}
/// <summary>
/// Provide same ini loader functionality for standard ini and master ini - file system or XML over http
/// </summary>
/// <param name="iniName">The name of the ini to load</param>
/// <param name="iniPath">Full path to the ini</param>
/// <param name="m_config">The current configuration source</param>
/// <param name="isUri">Boolean representing whether the ini source is a URI path over http or a file on the system</param>
/// <returns></returns>
private bool ReadConfig(string iniName, string iniPath, OpenSimConfigSource m_config, bool isUri)
{
bool success = false;
if (!isUri && File.Exists(iniPath))
{
m_log.InfoFormat("[CONFIG] Reading configuration file {0}", Path.GetFullPath(iniPath));
// From reading Nini's code, it seems that later merged keys replace earlier ones.
m_config.Source.Merge(new IniConfigSource(iniPath));
success = true;
}
else
{
if (isUri)
{
m_log.InfoFormat("[CONFIG] {0} is a http:// URI, fetching ...", iniName);
// The ini file path is a http URI
// Try to read it
try
{
XmlReader r = XmlReader.Create(iniName);
XmlConfigSource cs = new XmlConfigSource(r);
m_config.Source.Merge(cs);
success = true;
m_log.InfoFormat("[CONFIG] Loaded config from {0}", iniName);
}
catch (Exception e)
{
m_log.FatalFormat("[CONFIG] Exception reading config from URI {0}\n" + e.ToString(), iniName);
Environment.Exit(1);
}
}
}
return success;
}
/// <summary>
/// Setup a default config values in case they aren't present in the ini file
/// </summary>
/// <returns></returns>
public static IConfigSource DefaultConfig()
{
IConfigSource defaultConfig = new IniConfigSource();
{
IConfig config = defaultConfig.Configs["Startup"];
if (null == config)
config = defaultConfig.AddConfig("Startup");
config.Set("region_info_source", "filesystem");
config.Set("gridmode", false);
config.Set("physics", "basicphysics");
config.Set("meshing", "Meshmerizer");
config.Set("physical_prim", true);
config.Set("see_into_this_sim_from_neighbor", true);
config.Set("serverside_object_permissions", false);
config.Set("storage_plugin", "OpenSim.Data.SQLite.dll");
config.Set("storage_connection_string", "URI=file:OpenSim.db,version=3");
config.Set("storage_prim_inventories", true);
config.Set("startup_console_commands_file", String.Empty);
config.Set("shutdown_console_commands_file", String.Empty);
config.Set("DefaultScriptEngine", "XEngine");
config.Set("asset_database", "default");
config.Set("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
// life doesn't really work without this
config.Set("EventQueue", true);
}
{
IConfig config = defaultConfig.Configs["StandAlone"];
if (null == config)
config = defaultConfig.AddConfig("StandAlone");
config.Set("accounts_authenticate", true);
config.Set("welcome_message", "Welcome to Halcyon");
config.Set("inventory_plugin", "OpenSim.Data.SQLite.dll");
config.Set("inventory_source", String.Empty);
config.Set("userDatabase_plugin", "OpenSim.Data.SQLite.dll");
config.Set("user_source", String.Empty);
config.Set("asset_plugin", "OpenSim.Data.SQLite.dll");
config.Set("asset_source", "URI=file:Asset.db,version=3");
config.Set("LibraryName", "InWorldz Library");
config.Set("LibrariesXMLFile", string.Format(".{0}inventory{0}Libraries.xml", Path.DirectorySeparatorChar));
config.Set("AssetSetsXMLFile", string.Format(".{0}assets{0}AssetSets.xml", Path.DirectorySeparatorChar));
config.Set("dump_assets_to_file", false);
}
{
IConfig config = defaultConfig.Configs["Network"];
if (null == config)
config = defaultConfig.AddConfig("Network");
config.Set("default_location_x", 1000);
config.Set("default_location_y", 1000);
config.Set("http_listener_port", ConfigSettings.DefaultRegionHttpPort);
config.Set("remoting_listener_port", ConfigSettings.DefaultRegionRemotingPort);
config.Set("grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString());
config.Set("grid_send_key", "null");
config.Set("grid_recv_key", "null");
config.Set("user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString());
config.Set("user_send_key", "null");
config.Set("user_recv_key", "null");
config.Set("asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString());
config.Set("inventory_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultInventoryServerHttpPort.ToString());
config.Set("secure_inventory_server", "true");
}
return defaultConfig;
}
protected virtual void ReadConfigSettings()
{
IConfig startupConfig = m_config.Source.Configs["Startup"];
IConfig inventoryConfig = m_config.Source.Configs["Inventory"];
if (startupConfig != null)
{
m_configSettings.Standalone = !startupConfig.GetBoolean("gridmode", false);
m_configSettings.PhysicsEngine = startupConfig.GetString("physics");
m_configSettings.MeshEngineName = startupConfig.GetString("meshing");
m_configSettings.PhysicalPrim = startupConfig.GetBoolean("physical_prim", true);
m_configSettings.See_into_region_from_neighbor = startupConfig.GetBoolean("see_into_this_sim_from_neighbor", true);
m_configSettings.StorageDll = startupConfig.GetString("storage_plugin");
if (m_configSettings.StorageDll == "OpenSim.DataStore.MonoSqlite.dll")
{
m_configSettings.StorageDll = "OpenSim.Data.SQLite.dll";
m_log.Warn("WARNING: OpenSim.DataStore.MonoSqlite.dll is deprecated. Set storage_plugin to OpenSim.Data.SQLite.dll.");
Thread.Sleep(3000);
}
m_configSettings.StorageConnectionString
= startupConfig.GetString("storage_connection_string");
m_configSettings.EstateConnectionString
= startupConfig.GetString("estate_connection_string", m_configSettings.StorageConnectionString);
m_configSettings.AssetStorage
= startupConfig.GetString("asset_database");
m_configSettings.AssetCache
= startupConfig.GetString("AssetCache", "OpenSim.Framework.Communications.Cache.AssetCache");
m_configSettings.ClientstackDll
= startupConfig.GetString("clientstack_plugin", "OpenSim.Region.ClientStack.LindenUDP.dll");
}
IConfig standaloneConfig = m_config.Source.Configs["StandAlone"];
if (standaloneConfig != null)
{
m_configSettings.StandaloneAuthenticate = standaloneConfig.GetBoolean("accounts_authenticate", true);
m_configSettings.StandaloneWelcomeMessage = standaloneConfig.GetString("welcome_message");
m_configSettings.StandaloneInventoryPlugin = standaloneConfig.GetString("inventory_plugin");
m_configSettings.StandaloneInventorySource = standaloneConfig.GetString("inventory_source");
m_configSettings.StandaloneUserPlugin = standaloneConfig.GetString("userDatabase_plugin");
m_configSettings.StandaloneUserSource = standaloneConfig.GetString("user_source");
m_configSettings.StandaloneAssetSource = standaloneConfig.GetString("asset_source");
m_configSettings.LibraryName = standaloneConfig.GetString("LibraryName");
m_configSettings.LibrariesXMLFile = standaloneConfig.GetString("LibrariesXMLFile");
m_configSettings.AssetSetsXMLFile = standaloneConfig.GetString("AssetSetsXMLFile");
}
m_networkServersInfo.loadFromConfiguration(m_config.Source);
if (inventoryConfig != null)
{
m_configSettings.InventoryPlugin = inventoryConfig.GetString("inventory_plugin");
m_configSettings.InventoryCluster = inventoryConfig.GetString("inventory_cluster");
m_configSettings.LegacyInventorySource = inventoryConfig.GetString("legacy_inventory_source");
m_configSettings.InventoryMigrationActive = inventoryConfig.GetBoolean("migration_active");
}
else
{
m_log.Warn("[INVENTORY] New style inventory configuration information not found");
}
m_configSettings.CoreConnectionString = startupConfig.GetString("core_connection_string");
m_configSettings.SettingsFile = m_config.Source.Configs;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
namespace System.IO
{
/// <summary>Contains internal path helpers that are shared between many projects.</summary>
internal static partial class PathInternal
{
// All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through
// DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical
// path "Foo" passed as a filename to any Win32 API:
//
// 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example)
// 2. "C:\Foo" is prepended with the DosDevice namespace "\??\"
// 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo"
// 4. The Object Manager recognizes the DosDevices prefix and looks
// a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here)
// b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\")
// 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6")
// 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off
// to the registered parsing method for Files
// 7. The registered open method for File objects is invoked to create the file handle which is then returned
//
// There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified
// as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization
// (essentially GetFullPathName()) and path length checks.
// Windows Kernel-Mode Object Manager
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx
// https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager
//
// Introduction to MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx
//
// Local and Global MS-DOS Device Names
// https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx
internal const string ExtendedPathPrefix = @"\\?\";
internal const string UncPathPrefix = @"\\";
internal const string UncExtendedPrefixToInsert = @"?\UNC\";
internal const string UncExtendedPathPrefix = @"\\?\UNC\";
internal const string DevicePathPrefix = @"\\.\";
internal const string ParentDirectoryPrefix = @"..\";
internal const int MaxShortPath = 260;
internal const int MaxShortDirectoryPath = 248;
internal const int MaxLongPath = short.MaxValue;
// \\?\, \\.\, \??\
internal const int DevicePrefixLength = 4;
// \\
internal const int UncPrefixLength = 2;
// \\?\UNC\, \\.\UNC\
internal const int UncExtendedPrefixLength = 8;
internal static readonly int MaxComponentLength = 255;
internal static char[] GetInvalidPathChars() => new char[]
{
'|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31
};
// [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression
// https://msdn.microsoft.com/en-us/library/ff469270.aspx
private static readonly char[] s_wildcardChars =
{
'\"', '<', '>', '*', '?'
};
/// <summary>
/// Returns true if the given character is a valid drive letter
/// </summary>
internal static bool IsValidDriveChar(char value)
{
return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'));
}
/// <summary>
/// Returns true if the path is too long
/// </summary>
internal static bool IsPathTooLong(string fullPath)
{
// We'll never know precisely what will fail as paths get changed internally in Windows and
// may grow to exceed MaxLongPath.
return fullPath.Length >= MaxLongPath;
}
/// <summary>
/// Returns true if the directory is too long
/// </summary>
internal static bool IsDirectoryTooLong(string fullPath)
{
return IsPathTooLong(fullPath);
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative,
/// AND the path is more than 259 characters. (> MAX_PATH + null)
/// </summary>
internal static string EnsureExtendedPrefixOverMaxPath(string path)
{
if (path != null && path.Length >= MaxShortPath)
{
return EnsureExtendedPrefix(path);
}
else
{
return path;
}
}
/// <summary>
/// Adds the extended path prefix (\\?\) if not relative or already a device path.
/// </summary>
internal static string EnsureExtendedPrefix(string path)
{
// Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which
// means adding to relative paths will prevent them from getting the appropriate current directory inserted.
// If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it
// as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly
// in the future we wouldn't want normalization to come back and break existing code.
// In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this
// shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a
// normalized base path.)
if (IsPartiallyQualified(path) || IsDevice(path))
return path;
// Given \\server\share in longpath becomes \\?\UNC\server\share
if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase))
return path.Insert(2, PathInternal.UncExtendedPrefixToInsert);
return PathInternal.ExtendedPathPrefix + path;
}
/// <summary>
/// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\")
/// </summary>
internal static bool IsDevice(string path)
{
// If the path begins with any two separators is will be recognized and normalized and prepped with
// "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not.
return IsExtended(path)
||
(
path.Length >= DevicePrefixLength
&& IsDirectorySeparator(path[0])
&& IsDirectorySeparator(path[1])
&& (path[2] == '.' || path[2] == '?')
&& IsDirectorySeparator(path[3])
);
}
/// <summary>
/// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the
/// path matches exactly (cannot use alternate directory separators) Windows will skip normalization
/// and path length checks.
/// </summary>
internal static bool IsExtended(string path)
{
// While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths.
// Skipping of normalization will *only* occur if back slashes ('\') are used.
return path.Length >= DevicePrefixLength
&& path[0] == '\\'
&& (path[1] == '\\' || path[1] == '?')
&& path[2] == '?'
&& path[3] == '\\';
}
/// <summary>
/// Returns a value indicating if the given path contains invalid characters (", <, >, |
/// NUL, or any ASCII char whose integer representation is in the range of 1 through 31).
/// Does not check for wild card characters ? and *.
/// </summary>
internal static bool HasIllegalCharacters(string path)
{
// This is equivalent to IndexOfAny(InvalidPathChars) >= 0,
// except faster since IndexOfAny grows slower as the input
// array grows larger.
// Since we know that some of the characters we're looking
// for are contiguous in the alphabet-- the path cannot contain
// characters 0-31-- we can optimize this for our specific use
// case and use simple comparison operations.
for (int i = 0; i < path.Length; i++)
{
char c = path[i];
if (c <= '\u001f' || c == '|')
{
return true;
}
}
return false;
}
/// <summary>
/// Check for known wildcard characters. '*' and '?' are the most common ones.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe bool HasWildCardCharacters(string path)
{
// Question mark is part of dos device syntax so we have to skip if we are
int startIndex = PathInternal.IsDevice(path) ? ExtendedPathPrefix.Length : 0;
return path.IndexOfAny(s_wildcardChars, startIndex) >= 0;
}
/// <summary>
/// Gets the length of the root of the path (drive, share, etc.).
/// </summary>
internal static unsafe int GetRootLength(string path)
{
fixed(char* value = path)
{
return (int)GetRootLength(value, (uint)path.Length);
}
}
private static unsafe uint GetRootLength(char* path, uint pathLength)
{
uint i = 0;
uint volumeSeparatorLength = 2; // Length to the colon "C:"
uint uncRootLength = 2; // Length to the start of the server name "\\"
bool extendedSyntax = StartsWithOrdinal(path, pathLength, ExtendedPathPrefix);
bool extendedUncSyntax = StartsWithOrdinal(path, pathLength, UncExtendedPathPrefix);
if (extendedSyntax)
{
// Shift the position we look for the root from to account for the extended prefix
if (extendedUncSyntax)
{
// "\\" -> "\\?\UNC\"
uncRootLength = (uint)UncExtendedPathPrefix.Length;
}
else
{
// "C:" -> "\\?\C:"
volumeSeparatorLength += (uint)ExtendedPathPrefix.Length;
}
}
if ((!extendedSyntax || extendedUncSyntax) && pathLength > 0 && IsDirectorySeparator(path[0]))
{
// UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo")
i = 1; // Drive rooted (\foo) is one character
if (extendedUncSyntax || (pathLength > 1 && IsDirectorySeparator(path[1])))
{
// UNC (\\?\UNC\ or \\), scan past the next two directory separators at most
// (e.g. to \\?\UNC\Server\Share or \\Server\Share\)
i = uncRootLength;
int n = 2; // Maximum separators to skip
while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++;
}
}
else if (pathLength >= volumeSeparatorLength && path[volumeSeparatorLength - 1] == Path.VolumeSeparatorChar)
{
// Path is at least longer than where we expect a colon, and has a colon (\\?\A:, A:)
// If the colon is followed by a directory separator, move past it
i = volumeSeparatorLength;
if (pathLength >= volumeSeparatorLength + 1 && IsDirectorySeparator(path[volumeSeparatorLength])) i++;
}
return i;
}
private static unsafe bool StartsWithOrdinal(char* source, uint sourceLength, string value)
{
if (sourceLength < (uint)value.Length) return false;
for (int i = 0; i < value.Length; i++)
{
if (value[i] != source[i]) return false;
}
return true;
}
/// <summary>
/// Returns true if the path specified is relative to the current drive or working directory.
/// Returns false if the path is fixed to a specific drive or UNC path. This method does no
/// validation of the path (URIs will be returned as relative as a result).
/// </summary>
/// <remarks>
/// Handles paths that use the alternate directory separator. It is a frequent mistake to
/// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case.
/// "C:a" is drive relative- meaning that it will be resolved against the current directory
/// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
/// will not be used to modify the path).
/// </remarks>
internal static bool IsPartiallyQualified(string path)
{
if (path.Length < 2)
{
// It isn't fixed, it must be relative. There is no way to specify a fixed
// path with one character (or less).
return true;
}
if (IsDirectorySeparator(path[0]))
{
// There is no valid way to specify a relative path with two initial slashes or
// \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\
return !(path[1] == '?' || IsDirectorySeparator(path[1]));
}
// The only way to specify a fixed path that doesn't begin with two slashes
// is the drive, colon, slash format- i.e. C:\
return !((path.Length >= 3)
&& (path[1] == Path.VolumeSeparatorChar)
&& IsDirectorySeparator(path[2])
// To match old behavior we'll check the drive character for validity as the path is technically
// not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream.
&& IsValidDriveChar(path[0]));
}
/// <summary>
/// Returns the characters to skip at the start of the path if it starts with space(s) and a drive or directory separator.
/// (examples are " C:", " \")
/// This is a legacy behavior of Path.GetFullPath().
/// </summary>
/// <remarks>
/// Note that this conflicts with IsPathRooted() which doesn't (and never did) such a skip.
/// </remarks>
internal static int PathStartSkip(string path)
{
int startIndex = 0;
while (startIndex < path.Length && path[startIndex] == ' ') startIndex++;
if (startIndex > 0 && (startIndex < path.Length && PathInternal.IsDirectorySeparator(path[startIndex]))
|| (startIndex + 1 < path.Length && path[startIndex + 1] == ':' && PathInternal.IsValidDriveChar(path[startIndex])))
{
// Go ahead and skip spaces as we're either " C:" or " \"
return startIndex;
}
return 0;
}
/// <summary>
/// True if the given character is a directory separator.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static bool IsDirectorySeparator(char c)
{
return c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar;
}
/// <summary>
/// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present.
/// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip).
///
/// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false.
/// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as
/// such can't be used here (and is overkill for our uses).
///
/// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments.
/// </summary>
/// <remarks>
/// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do
/// not need trimming of trailing whitespace here.
///
/// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization.
///
/// For legacy desktop behavior with ExpandShortPaths:
/// - It has no impact on GetPathRoot() so doesn't need consideration.
/// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share).
///
/// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was
/// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you
/// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by
/// this undocumented behavior.
///
/// We won't match this old behavior because:
///
/// 1. It was undocumented
/// 2. It was costly (extremely so if it actually contained '~')
/// 3. Doesn't play nice with string logic
/// 4. Isn't a cross-plat friendly concept/behavior
/// </remarks>
internal static string NormalizeDirectorySeparators(string path)
{
if (string.IsNullOrEmpty(path)) return path;
char current;
int start = PathStartSkip(path);
if (start == 0)
{
// Make a pass to see if we need to normalize so we can potentially skip allocating
bool normalized = true;
for (int i = 0; i < path.Length; i++)
{
current = path[i];
if (IsDirectorySeparator(current)
&& (current != Path.DirectorySeparatorChar
// Check for sequential separators past the first position (we need to keep initial two for UNC/extended)
|| (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))))
{
normalized = false;
break;
}
}
if (normalized) return path;
}
StringBuilder builder = new StringBuilder(path.Length);
if (IsDirectorySeparator(path[start]))
{
start++;
builder.Append(Path.DirectorySeparatorChar);
}
for (int i = start; i < path.Length; i++)
{
current = path[i];
// If we have a separator
if (IsDirectorySeparator(current))
{
// If the next is a separator, skip adding this
if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1]))
{
continue;
}
// Ensure it is the primary separator
current = Path.DirectorySeparatorChar;
}
builder.Append(current);
}
return builder.ToString();
}
/// <summary>
/// Returns true if the character is a directory or volume separator.
/// </summary>
/// <param name="ch">The character to test.</param>
internal static bool IsDirectoryOrVolumeSeparator(char ch)
{
return PathInternal.IsDirectorySeparator(ch) || Path.VolumeSeparatorChar == ch;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Honey.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
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);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
namespace JIT.HardwareIntrinsics.General
{
public static partial class Program
{
private static void GetAndWithElementUInt160()
{
var test = new VectorGetAndWithElement__GetAndWithElementUInt160();
// Validates basic functionality works
test.RunBasicScenario();
// Validates calling via reflection works
test.RunReflectionScenario();
// Validates that invalid indices throws ArgumentOutOfRangeException
test.RunArgumentOutOfRangeScenario();
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class VectorGetAndWithElement__GetAndWithElementUInt160
{
private static readonly int LargestVectorSize = 16;
private static readonly int ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16);
public bool Succeeded { get; set; } = true;
public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector128<UInt16> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
UInt16 result = value.GetElement(imm);
ValidateGetResult(result, values);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
Vector128<UInt16> result2 = value.WithElement(imm, insertedValue);
ValidateWithResult(result2, values, insertedValue);
}
catch (ArgumentOutOfRangeException)
{
succeeded = expectedOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false)
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));
UInt16[] values = new UInt16[ElementCount];
for (int i = 0; i < ElementCount; i++)
{
values[i] = TestLibrary.Generator.GetUInt16();
}
Vector128<UInt16> value = Vector128.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);
bool succeeded = !expectedOutOfRangeException;
try
{
object result = typeof(Vector128)
.GetMethod(nameof(Vector128.GetElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm });
ValidateGetResult((UInt16)(result), values);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
succeeded = !expectedOutOfRangeException;
UInt16 insertedValue = TestLibrary.Generator.GetUInt16();
try
{
object result2 = typeof(Vector128)
.GetMethod(nameof(Vector128.WithElement))
.MakeGenericMethod(typeof(UInt16))
.Invoke(null, new object[] { value, imm, insertedValue });
ValidateWithResult((Vector128<UInt16>)(result2), values, insertedValue);
}
catch (TargetInvocationException e)
{
succeeded = expectedOutOfRangeException
&& e.InnerException is ArgumentOutOfRangeException;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException.");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
public void RunArgumentOutOfRangeScenario()
{
RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true);
RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true);
}
private void ValidateGetResult(UInt16 result, UInt16[] values, [CallerMemberName] string method = "")
{
if (result != values[0])
{
Succeeded = false;
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.GetElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
private void ValidateWithResult(Vector128<UInt16> result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
UInt16[] resultElements = new UInt16[ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref resultElements[0]), result);
ValidateWithResult(resultElements, values, insertedValue, method);
}
private void ValidateWithResult(UInt16[] result, UInt16[] values, UInt16 insertedValue, [CallerMemberName] string method = "")
{
bool succeeded = true;
for (int i = 0; i < ElementCount; i++)
{
if ((i != 0) && (result[i] != values[i]))
{
succeeded = false;
break;
}
}
if (result[0] != insertedValue)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"Vector128<UInt16.WithElement(0): {method} failed:");
TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})");
TestLibrary.TestFramework.LogInformation($" insert: insertedValue");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using 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.V10.Services
{
/// <summary>Settings for <see cref="AdGroupCustomizerServiceClient"/> instances.</summary>
public sealed partial class AdGroupCustomizerServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="AdGroupCustomizerServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="AdGroupCustomizerServiceSettings"/>.</returns>
public static AdGroupCustomizerServiceSettings GetDefault() => new AdGroupCustomizerServiceSettings();
/// <summary>
/// Constructs a new <see cref="AdGroupCustomizerServiceSettings"/> object with default settings.
/// </summary>
public AdGroupCustomizerServiceSettings()
{
}
private AdGroupCustomizerServiceSettings(AdGroupCustomizerServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
MutateAdGroupCustomizersSettings = existing.MutateAdGroupCustomizersSettings;
OnCopy(existing);
}
partial void OnCopy(AdGroupCustomizerServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>AdGroupCustomizerServiceClient.MutateAdGroupCustomizers</c> and
/// <c>AdGroupCustomizerServiceClient.MutateAdGroupCustomizersAsync</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 MutateAdGroupCustomizersSettings { 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="AdGroupCustomizerServiceSettings"/> object.</returns>
public AdGroupCustomizerServiceSettings Clone() => new AdGroupCustomizerServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="AdGroupCustomizerServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class AdGroupCustomizerServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCustomizerServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public AdGroupCustomizerServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public AdGroupCustomizerServiceClientBuilder()
{
UseJwtAccessWithScopes = AdGroupCustomizerServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref AdGroupCustomizerServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCustomizerServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override AdGroupCustomizerServiceClient Build()
{
AdGroupCustomizerServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<AdGroupCustomizerServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<AdGroupCustomizerServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private AdGroupCustomizerServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return AdGroupCustomizerServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<AdGroupCustomizerServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return AdGroupCustomizerServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => AdGroupCustomizerServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCustomizerServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCustomizerServiceClient.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>AdGroupCustomizerService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group customizer
/// </remarks>
public abstract partial class AdGroupCustomizerServiceClient
{
/// <summary>
/// The default endpoint for the AdGroupCustomizerService 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 AdGroupCustomizerService scopes.</summary>
/// <remarks>
/// The default AdGroupCustomizerService 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="AdGroupCustomizerServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCustomizerServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="AdGroupCustomizerServiceClient"/>.</returns>
public static stt::Task<AdGroupCustomizerServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new AdGroupCustomizerServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="AdGroupCustomizerServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="AdGroupCustomizerServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="AdGroupCustomizerServiceClient"/>.</returns>
public static AdGroupCustomizerServiceClient Create() => new AdGroupCustomizerServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="AdGroupCustomizerServiceClient"/> 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="AdGroupCustomizerServiceSettings"/>.</param>
/// <returns>The created <see cref="AdGroupCustomizerServiceClient"/>.</returns>
internal static AdGroupCustomizerServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCustomizerServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
AdGroupCustomizerService.AdGroupCustomizerServiceClient grpcClient = new AdGroupCustomizerService.AdGroupCustomizerServiceClient(callInvoker);
return new AdGroupCustomizerServiceClientImpl(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 AdGroupCustomizerService client</summary>
public virtual AdGroupCustomizerService.AdGroupCustomizerServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </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 MutateAdGroupCustomizersResponse MutateAdGroupCustomizers(MutateAdGroupCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </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<MutateAdGroupCustomizersResponse> MutateAdGroupCustomizersAsync(MutateAdGroupCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </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<MutateAdGroupCustomizersResponse> MutateAdGroupCustomizersAsync(MutateAdGroupCustomizersRequest request, st::CancellationToken cancellationToken) =>
MutateAdGroupCustomizersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group customizers are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group customizers.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateAdGroupCustomizersResponse MutateAdGroupCustomizers(string customerId, scg::IEnumerable<AdGroupCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCustomizers(new MutateAdGroupCustomizersRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group customizers are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group customizers.
/// </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<MutateAdGroupCustomizersResponse> MutateAdGroupCustomizersAsync(string customerId, scg::IEnumerable<AdGroupCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateAdGroupCustomizersAsync(new MutateAdGroupCustomizersRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose ad group customizers are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual ad group customizers.
/// </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<MutateAdGroupCustomizersResponse> MutateAdGroupCustomizersAsync(string customerId, scg::IEnumerable<AdGroupCustomizerOperation> operations, st::CancellationToken cancellationToken) =>
MutateAdGroupCustomizersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>AdGroupCustomizerService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage ad group customizer
/// </remarks>
public sealed partial class AdGroupCustomizerServiceClientImpl : AdGroupCustomizerServiceClient
{
private readonly gaxgrpc::ApiCall<MutateAdGroupCustomizersRequest, MutateAdGroupCustomizersResponse> _callMutateAdGroupCustomizers;
/// <summary>
/// Constructs a client wrapper for the AdGroupCustomizerService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="AdGroupCustomizerServiceSettings"/> used within this client.
/// </param>
public AdGroupCustomizerServiceClientImpl(AdGroupCustomizerService.AdGroupCustomizerServiceClient grpcClient, AdGroupCustomizerServiceSettings settings)
{
GrpcClient = grpcClient;
AdGroupCustomizerServiceSettings effectiveSettings = settings ?? AdGroupCustomizerServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callMutateAdGroupCustomizers = clientHelper.BuildApiCall<MutateAdGroupCustomizersRequest, MutateAdGroupCustomizersResponse>(grpcClient.MutateAdGroupCustomizersAsync, grpcClient.MutateAdGroupCustomizers, effectiveSettings.MutateAdGroupCustomizersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateAdGroupCustomizers);
Modify_MutateAdGroupCustomizersApiCall(ref _callMutateAdGroupCustomizers);
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_MutateAdGroupCustomizersApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCustomizersRequest, MutateAdGroupCustomizersResponse> call);
partial void OnConstruction(AdGroupCustomizerService.AdGroupCustomizerServiceClient grpcClient, AdGroupCustomizerServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC AdGroupCustomizerService client</summary>
public override AdGroupCustomizerService.AdGroupCustomizerServiceClient GrpcClient { get; }
partial void Modify_MutateAdGroupCustomizersRequest(ref MutateAdGroupCustomizersRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </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 MutateAdGroupCustomizersResponse MutateAdGroupCustomizers(MutateAdGroupCustomizersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCustomizersRequest(ref request, ref callSettings);
return _callMutateAdGroupCustomizers.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates or removes ad group customizers. Operation statuses are
/// returned.
/// </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<MutateAdGroupCustomizersResponse> MutateAdGroupCustomizersAsync(MutateAdGroupCustomizersRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateAdGroupCustomizersRequest(ref request, ref callSettings);
return _callMutateAdGroupCustomizers.Async(request, callSettings);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Reflection;
using Should;
using Xunit;
namespace AutoMapper.UnitTests
{
namespace CustomMapping
{
public class When_specifying_type_converters : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public string Value1 { get; set; }
public string Value2 { get; set; }
public string Value3 { get; set; }
}
public class Destination
{
public int Value1 { get; set; }
public DateTime Value2 { get; set; }
public Type Value3 { get; set; }
}
public class DateTimeTypeConverter : ITypeConverter<string, DateTime>
{
public DateTime Convert(string source, ResolutionContext context)
{
return System.Convert.ToDateTime(source);
}
}
public class TypeTypeConverter : ITypeConverter<string, Type>
{
public Type Convert(string source, ResolutionContext context)
{
Type type = Assembly.GetExecutingAssembly().GetType(source);
return type;
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<string, int>().ConvertUsing((string arg) => Convert.ToInt32(arg));
cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter());
cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>();
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
var source = new Source
{
Value1 = "5",
Value2 = "01/01/2000",
Value3 = "AutoMapper.UnitTests.CustomMapping.When_specifying_type_converters+Destination"
};
_result = Mapper.Map<Source, Destination>(source);
}
[Fact]
public void Should_convert_type_using_expression()
{
_result.Value1.ShouldEqual(5);
}
[Fact]
public void Should_convert_type_using_instance()
{
_result.Value2.ShouldEqual(new DateTime(2000, 1, 1));
}
[Fact]
public void Should_convert_type_using_Func_that_returns_instance()
{
_result.Value3.ShouldEqual(typeof(Destination));
}
}
public class When_specifying_type_converters_on_types_with_incompatible_members : AutoMapperSpecBase
{
private ParentDestination _result;
public class Source
{
public string Foo { get; set; }
}
public class Destination
{
public int Type { get; set; }
}
public class ParentSource
{
public Source Value { get; set; }
}
public class ParentDestination
{
public Destination Value { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Source, Destination>().ConvertUsing(arg => new Destination {Type = Convert.ToInt32(arg.Foo)});
cfg.CreateMap<ParentSource, ParentDestination>();
});
protected override void Because_of()
{
var source = new ParentSource
{
Value = new Source { Foo = "5", }
};
_result = Mapper.Map<ParentSource, ParentDestination>(source);
}
[Fact]
public void Should_convert_type_using_expression()
{
_result.Value.Type.ShouldEqual(5);
}
}
#if !PORTABLE
public class When_specifying_mapping_with_the_BCL_type_converter_class : NonValidatingSpecBase
{
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg => { });
[TypeConverter(typeof(CustomTypeConverter))]
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomTypeConverter : TypeConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof (Destination);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
return new Destination
{
OtherValue = ((Source) value).Value + 10
};
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(Destination);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
return new Source {Value = ((Destination) value).OtherValue - 10};
}
}
[Fact]
public void Should_convert_from_type_using_the_custom_type_converter()
{
var source = new Source
{
Value = 5
};
var destination = Mapper.Map<Source, Destination>(source);
destination.OtherValue.ShouldEqual(15);
}
[Fact]
public void Should_convert_to_type_using_the_custom_type_converter()
{
var source = new Destination()
{
OtherValue = 15
};
var destination = Mapper.Map<Destination, Source>(source);
destination.Value.ShouldEqual(5);
}
}
#endif
public class When_specifying_a_type_converter_for_a_non_generic_configuration : NonValidatingSpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomConverter : ITypeConverter<Source, Destination>
{
public Destination Convert(Source source, ResolutionContext context)
{
return new Destination
{
OtherValue = source.Value + 10
};
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof (Source), typeof (Destination)).ConvertUsing<CustomConverter>();
});
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Fact]
public void Should_use_converter_specified()
{
_result.OtherValue.ShouldEqual(15);
}
}
public class When_specifying_a_non_generic_type_converter_for_a_non_generic_configuration : AutoMapperSpecBase
{
private Destination _result;
public class Source
{
public int Value { get; set; }
}
public class Destination
{
public int OtherValue { get; set; }
}
public class CustomConverter : ITypeConverter<Source, Destination>
{
public Destination Convert(Source source, ResolutionContext context)
{
return new Destination
{
OtherValue = source.Value + 10
};
}
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof (Source), typeof (Destination)).ConvertUsing(typeof (CustomConverter));
});
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = 5});
}
[Fact]
public void Should_use_converter_specified()
{
_result.OtherValue.ShouldEqual(15);
}
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using Eto.Forms;
using Eto.Drawing;
using Eto.GtkSharp.Drawing;
using GLib;
using System.Text;
using System.Linq;
using System.Collections.Generic;
namespace Eto.GtkSharp.Forms
{
public interface IGtkControl
{
Point CurrentLocation { get; set; }
Gtk.Widget ContainerControl { get; }
Color? SelectedBackgroundColor { get; }
void SetBackgroundColor();
}
public static class GtkControlExtensions
{
public static Gtk.Widget GetContainerWidget(this Control control)
{
if (control == null)
return null;
var containerHandler = control.Handler as IGtkControl;
if (containerHandler != null)
return containerHandler.ContainerControl;
var controlObject = control.ControlObject as Control;
if (controlObject != null)
return controlObject.GetContainerWidget();
return control.ControlObject as Gtk.Widget;
}
public static IGtkControl GetGtkControlHandler(this Control control)
{
if (control == null)
return null;
var containerHandler = control.Handler as IGtkControl;
if (containerHandler != null)
return containerHandler;
var controlObject = control.ControlObject as Control;
return controlObject != null ? controlObject.GetGtkControlHandler() : null;
}
}
public abstract class GtkControl<TControl, TWidget, TCallback> : WidgetHandler<TControl, TWidget, TCallback>, Control.IHandler, IGtkControl
where TControl: Gtk.Widget
where TWidget: Control
where TCallback: Control.ICallback
{
Font font;
Size size;
Size asize;
bool mouseDownHandled;
Cursor cursor;
Color? cachedBackgroundColor;
Color? backgroundColor;
public static float ScrollAmount = 2f;
public override IntPtr NativeHandle { get { return Control.Handle; } }
protected GtkControl()
{
size = new Size(-1, -1);
}
public Size PreferredSize { get { return size; } }
public virtual Size DefaultSize { get { return new Size(-1, -1); } }
public virtual Gtk.Widget ContainerControl
{
get { return Control; }
}
public virtual Gtk.Widget EventControl
{
get { return Control; }
}
public virtual Gtk.Widget ContainerContentControl
{
get { return ContainerControl; }
}
public virtual Gtk.Widget BackgroundControl
{
get { return ContainerContentControl; }
}
public virtual Point CurrentLocation { get; set; }
public virtual Size Size
{
get
{
return ContainerControl.Visible ? ContainerControl.Allocation.Size.ToEto() : size;
}
set
{
if (size != value)
{
size = value;
if (size.Width == -1 || size.Height == -1)
{
var defSize = DefaultSize;
if (size.Width == -1)
size.Width = defSize.Width;
if (size.Height == -1)
size.Height = defSize.Height;
}
ContainerControl.SetSizeRequest(size.Width, size.Height);
}
}
}
public virtual bool Enabled
{
get { return Control.Sensitive; }
set
{
Control.Sensitive = value;
}
}
public virtual string Text
{
get { return Control.Name; }
set { Control.Name = value; }
}
public void Invalidate()
{
Control.QueueDraw();
}
public void Invalidate(Rectangle rect)
{
Control.QueueDrawArea(rect.X, rect.Y, rect.Width, rect.Height);
}
protected virtual bool IsTransparentControl { get { return true; } }
protected virtual Color DefaultBackgroundColor
{
get { return ContainerContentControl.GetBackground(); }
}
public virtual Color? SelectedBackgroundColor
{
get
{
Color? col;
if (cachedBackgroundColor != null)
return cachedBackgroundColor.Value;
if (IsTransparentControl)
{
var parent = Widget.Parent.GetGtkControlHandler();
col = parent != null ? parent.SelectedBackgroundColor : DefaultBackgroundColor;
}
else
col = DefaultBackgroundColor;
if (backgroundColor != null)
{
col = col != null ? Color.Blend(col.Value, backgroundColor.Value) : backgroundColor;
}
cachedBackgroundColor = col;
return col;
}
}
public virtual void SetBackgroundColor()
{
cachedBackgroundColor = null;
SetBackgroundColor(SelectedBackgroundColor);
}
protected virtual void SetBackgroundColor(Color? color)
{
if (color != null)
{
BackgroundControl.SetBackground(color.Value);
}
else
{
BackgroundControl.ClearBackground();
}
}
public virtual Color BackgroundColor
{
get
{
return backgroundColor ?? SelectedBackgroundColor ?? Colors.Transparent;
}
set
{
if (backgroundColor != value)
{
backgroundColor = value;
SetBackgroundColor();
}
}
}
public void SuspendLayout()
{
}
public void ResumeLayout()
{
}
public void Focus()
{
if (Widget.Loaded)
GrabFocus();
else
Widget.LoadComplete += Widget_SetFocus;
}
protected virtual void GrabFocus()
{
Control.GrabFocus();
}
void Widget_SetFocus(object sender, EventArgs e)
{
Widget.LoadComplete -= Widget_SetFocus;
Eto.Forms.Application.Instance.AsyncInvoke(GrabFocus);
}
public bool HasFocus
{
get { return Control.HasFocus; }
}
public bool Visible
{
get { return Control.Visible; }
set
{
Control.Visible = value;
Control.NoShowAll = !value;
if (value && Widget.Loaded)
{
Control.ShowAll();
}
}
}
public virtual void SetParent(Container parent)
{
/*if (parent == null)
{
if (ContainerControl.Parent != null)
((Gtk.Container)ContainerControl.Parent).Remove(ContainerControl);
}*/
}
public virtual void OnPreLoad(EventArgs e)
{
}
public virtual void OnLoad(EventArgs e)
{
}
public virtual void OnLoadComplete(EventArgs e)
{
if (!Control.IsRealized)
Control.Realized += Connector.HandleControlRealized;
else
RealizedSetup();
}
public virtual void OnUnLoad(EventArgs e)
{
}
void RealizedSetup()
{
if (cursor != null)
Control.GetWindow().Cursor = cursor.ControlObject as Gdk.Cursor;
SetBackgroundColor();
}
public override void AttachEvent(string id)
{
switch (id)
{
case Eto.Forms.Control.KeyDownEvent:
EventControl.AddEvents((int)Gdk.EventMask.KeyPressMask);
EventControl.KeyPressEvent += Connector.HandleKeyPressEvent;
break;
case Eto.Forms.Control.TextInputEvent:
HandleEvent(Eto.Forms.Control.KeyDownEvent);
break;
case Eto.Forms.Control.KeyUpEvent:
EventControl.AddEvents((int)Gdk.EventMask.KeyReleaseMask);
EventControl.KeyReleaseEvent += Connector.HandleKeyReleaseEvent;
break;
case Eto.Forms.Control.SizeChangedEvent:
EventControl.AddEvents((int)Gdk.EventMask.StructureMask);
EventControl.SizeAllocated += Connector.HandleSizeAllocated;
break;
case Eto.Forms.Control.MouseDoubleClickEvent:
case Eto.Forms.Control.MouseDownEvent:
if (!mouseDownHandled)
{
EventControl.AddEvents((int)Gdk.EventMask.ButtonPressMask);
EventControl.AddEvents((int)Gdk.EventMask.ButtonReleaseMask);
EventControl.ButtonPressEvent += Connector.HandleButtonPressEvent;
mouseDownHandled = true;
}
break;
case Eto.Forms.Control.MouseUpEvent:
EventControl.AddEvents((int)Gdk.EventMask.ButtonReleaseMask);
EventControl.ButtonReleaseEvent += Connector.HandleButtonReleaseEvent;
break;
case Eto.Forms.Control.MouseEnterEvent:
EventControl.AddEvents((int)Gdk.EventMask.EnterNotifyMask);
EventControl.EnterNotifyEvent += Connector.HandleControlEnterNotifyEvent;
break;
case Eto.Forms.Control.MouseLeaveEvent:
EventControl.AddEvents((int)Gdk.EventMask.LeaveNotifyMask);
EventControl.LeaveNotifyEvent += Connector.HandleControlLeaveNotifyEvent;
break;
case Eto.Forms.Control.MouseMoveEvent:
EventControl.AddEvents((int)Gdk.EventMask.ButtonMotionMask);
EventControl.AddEvents((int)Gdk.EventMask.PointerMotionMask);
//GtkControlObject.Events |= Gdk.EventMask.PointerMotionHintMask;
EventControl.MotionNotifyEvent += Connector.HandleMotionNotifyEvent;
break;
case Eto.Forms.Control.MouseWheelEvent:
EventControl.AddEvents((int)Gdk.EventMask.ScrollMask);
EventControl.ScrollEvent += Connector.HandleScrollEvent;
break;
case Eto.Forms.Control.GotFocusEvent:
EventControl.AddEvents((int)Gdk.EventMask.FocusChangeMask);
EventControl.FocusInEvent += Connector.FocusInEvent;
break;
case Eto.Forms.Control.LostFocusEvent:
EventControl.AddEvents((int)Gdk.EventMask.FocusChangeMask);
EventControl.FocusOutEvent += Connector.FocusOutEvent;
break;
case Eto.Forms.Control.ShownEvent:
EventControl.AddEvents((int)Gdk.EventMask.VisibilityNotifyMask);
EventControl.VisibilityNotifyEvent += Connector.VisibilityNotifyEvent;
break;
default:
base.AttachEvent(id);
return;
}
}
protected new GtkControlConnector Connector { get { return (GtkControlConnector)base.Connector; } }
protected override WeakConnector CreateConnector()
{
return new GtkControlConnector();
}
/// <summary>
/// Connector for events to keep a weak reference to allow gtk controls to be garbage collected when no longer referenced
/// </summary>
protected class GtkControlConnector : WeakConnector
{
new GtkControl<TControl, TWidget, TCallback> Handler { get { return (GtkControl<TControl, TWidget, TCallback>)base.Handler; } }
public void HandleScrollEvent(object o, Gtk.ScrollEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = args.Event.State.ToEtoMouseButtons();
SizeF delta;
switch (args.Event.Direction)
{
case Gdk.ScrollDirection.Down:
delta = new SizeF(0f, -ScrollAmount);
break;
case Gdk.ScrollDirection.Left:
delta = new SizeF(ScrollAmount, 0f);
break;
case Gdk.ScrollDirection.Right:
delta = new SizeF(-ScrollAmount, 0f);
break;
case Gdk.ScrollDirection.Up:
delta = new SizeF(0f, ScrollAmount);
break;
default:
throw new NotSupportedException();
}
Handler.Callback.OnMouseWheel(Handler.Widget, new MouseEventArgs(buttons, modifiers, p, delta));
}
[GLib.ConnectBefore]
public void HandleControlLeaveNotifyEvent(object o, Gtk.LeaveNotifyEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = MouseButtons.None;
Handler.Callback.OnMouseLeave(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
[GLib.ConnectBefore]
public void HandleControlEnterNotifyEvent(object o, Gtk.EnterNotifyEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = MouseButtons.None;
Handler.Callback.OnMouseEnter(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
[GLib.ConnectBefore]
public void HandleMotionNotifyEvent(System.Object o, Gtk.MotionNotifyEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = args.Event.State.ToEtoMouseButtons();
Handler.Callback.OnMouseMove(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
public void HandleButtonReleaseEvent(object o, Gtk.ButtonReleaseEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = args.Event.ToEtoMouseButtons();
Handler.Callback.OnMouseUp(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
public void HandleButtonPressEvent(object sender, Gtk.ButtonPressEventArgs args)
{
var p = new PointF((float)args.Event.X, (float)args.Event.Y);
Keys modifiers = args.Event.State.ToEtoKey();
MouseButtons buttons = args.Event.ToEtoMouseButtons();
if (Handler.Control.CanFocus && !Handler.Control.HasFocus)
Handler.Control.GrabFocus();
if (args.Event.Type == Gdk.EventType.ButtonPress)
{
Handler.Callback.OnMouseDown(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
else if (args.Event.Type == Gdk.EventType.TwoButtonPress)
{
Handler.Callback.OnMouseDoubleClick(Handler.Widget, new MouseEventArgs(buttons, modifiers, p));
}
}
public void HandleSizeAllocated(object o, Gtk.SizeAllocatedArgs args)
{
if (Handler.asize != args.Allocation.Size.ToEto())
{
// only call when the size has actually changed, gtk likes to call anyway!! grr.
Handler.asize = args.Allocation.Size.ToEto();
Handler.Callback.OnSizeChanged(Handler.Widget, EventArgs.Empty);
}
}
Gtk.IMContext context;
bool commitHandled;
Gtk.IMContext Context
{
get
{
if (context != null)
return context;
context = new Gtk.IMContextSimple();
context.Commit += (o, args) =>
{
var handler = Handler;
if (handler == null || string.IsNullOrEmpty(args.Str))
return;
var tia = new TextInputEventArgs(args.Str);
handler.Callback.OnTextInput(handler.Widget, tia);
commitHandled = tia.Cancel;
context.Reset();
};
return context;
}
}
[ConnectBefore]
public void HandleKeyPressEvent(object o, Gtk.KeyPressEventArgs args)
{
var handler = Handler;
if (handler == null)
return;
var e = args.Event.ToEto();
if (e != null)
{
handler.Callback.OnKeyDown(Handler.Widget, e);
args.RetVal = e.Handled;
}
if (e == null || !e.Handled)
{
commitHandled = false;
if (Context.FilterKeypress(args.Event))
{
args.RetVal = commitHandled;
}
}
}
public void HandleKeyReleaseEvent(object o, Gtk.KeyReleaseEventArgs args)
{
var handler = Handler;
if (handler == null)
return;
var e = args.Event.ToEto();
if (e != null)
{
handler.Callback.OnKeyUp(handler.Widget, e);
args.RetVal = e.Handled;
}
}
public void FocusInEvent(object o, Gtk.FocusInEventArgs args)
{
var handler = Handler;
if (handler == null)
return;
handler.Callback.OnGotFocus(handler.Widget, EventArgs.Empty);
}
public void FocusOutEvent(object o, Gtk.FocusOutEventArgs args)
{
// Handler can be null here after window is closed
var handler = Handler;
if (handler != null)
handler.Callback.OnLostFocus(Handler.Widget, EventArgs.Empty);
}
public void VisibilityNotifyEvent(object o, Gtk.VisibilityNotifyEventArgs args)
{
if (args.Event.State == Gdk.VisibilityState.FullyObscured)
Handler.Callback.OnShown(Handler.Widget, EventArgs.Empty);
}
public void HandleControlRealized(object sender, EventArgs e)
{
Handler.RealizedSetup();
Handler.Control.Realized -= HandleControlRealized;
}
}
protected virtual Gtk.Widget FontControl
{
get { return Control; }
}
public virtual Font Font
{
get
{
if (font == null)
font = new Font(new FontHandler(FontControl));
return font;
}
set
{
font = value;
FontControl.SetFont(font.ToPango());
}
}
public Cursor Cursor
{
get { return cursor; }
set
{
cursor = value;
var gdkWindow = Control.GetWindow();
if (gdkWindow != null)
{
gdkWindow.Cursor = cursor != null ? cursor.ControlObject as Gdk.Cursor : null;
}
}
}
public string ToolTip
{
get { return Control.TooltipText; }
set { Control.TooltipText = value; }
}
public virtual IEnumerable<string> SupportedPlatformCommands
{
get { return Enumerable.Empty<string>(); }
}
public virtual void MapPlatformCommand(string systemAction, Command action)
{
}
public PointF PointFromScreen(PointF point)
{
var gdkWindow = Control.GetWindow();
if (gdkWindow != null)
{
int x, y;
gdkWindow.GetOrigin(out x, out y);
return new PointF(point.X - x, point.Y - y);
}
return point;
}
public PointF PointToScreen(PointF point)
{
var gdkWindow = Control.GetWindow();
if (gdkWindow != null)
{
int x, y;
gdkWindow.GetOrigin(out x, out y);
return new PointF(point.X + x, point.Y + y);
}
return point;
}
public Point Location
{
get { return Control.Allocation.Location.ToEto(); }
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// TypeDelegator
//
// <OWNER>[....]</OWNER>
// This class wraps a Type object and delegates all methods to that Type.
namespace System.Reflection {
using System;
using System.Runtime.InteropServices;
using System.Diagnostics.Contracts;
using CultureInfo = System.Globalization.CultureInfo;
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class TypeDelegator : TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
protected Type typeImpl;
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical] // auto-generated
#endif
protected TypeDelegator() {}
public TypeDelegator(Type delegatingType) {
if (delegatingType == null)
throw new ArgumentNullException("delegatingType");
Contract.EndContractBlock();
typeImpl = delegatingType;
}
public override Guid GUID {
get {return typeImpl.GUID;}
}
public override int MetadataToken { get { return typeImpl.MetadataToken; } }
public override Object InvokeMember(String name,BindingFlags invokeAttr,Binder binder,Object target,
Object[] args,ParameterModifier[] modifiers,CultureInfo culture,String[] namedParameters)
{
return typeImpl.InvokeMember(name,invokeAttr,binder,target,args,modifiers,culture,namedParameters);
}
public override Module Module {
get {return typeImpl.Module;}
}
public override Assembly Assembly {
get {return typeImpl.Assembly;}
}
public override RuntimeTypeHandle TypeHandle {
get{return typeImpl.TypeHandle;}
}
public override String Name {
get{return typeImpl.Name;}
}
public override String FullName {
get{return typeImpl.FullName;}
}
public override String Namespace {
get{return typeImpl.Namespace;}
}
public override String AssemblyQualifiedName {
get {
return typeImpl.AssemblyQualifiedName;
}
}
public override Type BaseType {
get{return typeImpl.BaseType;}
}
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
return typeImpl.GetConstructor(bindingAttr,binder,callConvention,types,modifiers);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
{
return typeImpl.GetConstructors(bindingAttr);
}
protected override MethodInfo GetMethodImpl(String name,BindingFlags bindingAttr,Binder binder,
CallingConventions callConvention, Type[] types,ParameterModifier[] modifiers)
{
// This is interesting there are two paths into the impl. One that validates
// type as non-null and one where type may be null.
if (types == null)
return typeImpl.GetMethod(name,bindingAttr);
else
return typeImpl.GetMethod(name,bindingAttr,binder,callConvention,types,modifiers);
}
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
return typeImpl.GetMethods(bindingAttr);
}
public override FieldInfo GetField(String name, BindingFlags bindingAttr)
{
return typeImpl.GetField(name,bindingAttr);
}
public override FieldInfo[] GetFields(BindingFlags bindingAttr)
{
return typeImpl.GetFields(bindingAttr);
}
public override Type GetInterface(String name, bool ignoreCase)
{
return typeImpl.GetInterface(name,ignoreCase);
}
public override Type[] GetInterfaces()
{
return typeImpl.GetInterfaces();
}
public override EventInfo GetEvent(String name,BindingFlags bindingAttr)
{
return typeImpl.GetEvent(name,bindingAttr);
}
public override EventInfo[] GetEvents()
{
return typeImpl.GetEvents();
}
protected override PropertyInfo GetPropertyImpl(String name,BindingFlags bindingAttr,Binder binder,
Type returnType, Type[] types, ParameterModifier[] modifiers)
{
if (returnType == null && types == null)
return typeImpl.GetProperty(name,bindingAttr);
else
return typeImpl.GetProperty(name,bindingAttr,binder,returnType,types,modifiers);
}
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr)
{
return typeImpl.GetProperties(bindingAttr);
}
public override EventInfo[] GetEvents(BindingFlags bindingAttr)
{
return typeImpl.GetEvents(bindingAttr);
}
public override Type[] GetNestedTypes(BindingFlags bindingAttr)
{
return typeImpl.GetNestedTypes(bindingAttr);
}
public override Type GetNestedType(String name, BindingFlags bindingAttr)
{
return typeImpl.GetNestedType(name,bindingAttr);
}
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr)
{
return typeImpl.GetMember(name,type,bindingAttr);
}
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
return typeImpl.GetMembers(bindingAttr);
}
protected override TypeAttributes GetAttributeFlagsImpl()
{
return typeImpl.Attributes;
}
protected override bool IsArrayImpl()
{
return typeImpl.IsArray;
}
protected override bool IsPrimitiveImpl()
{
return typeImpl.IsPrimitive;
}
protected override bool IsByRefImpl()
{
return typeImpl.IsByRef;
}
protected override bool IsPointerImpl()
{
return typeImpl.IsPointer;
}
protected override bool IsValueTypeImpl()
{
return typeImpl.IsValueType;
}
protected override bool IsCOMObjectImpl()
{
return typeImpl.IsCOMObject;
}
public override bool IsConstructedGenericType
{
get
{
return typeImpl.IsConstructedGenericType;
}
}
public override Type GetElementType()
{
return typeImpl.GetElementType();
}
protected override bool HasElementTypeImpl()
{
return typeImpl.HasElementType;
}
public override Type UnderlyingSystemType
{
get {return typeImpl.UnderlyingSystemType;}
}
// ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return typeImpl.GetCustomAttributes(inherit);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return typeImpl.GetCustomAttributes(attributeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return typeImpl.IsDefined(attributeType, inherit);
}
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType)
{
return typeImpl.GetInterfaceMap(interfaceType);
}
}
}
| |
using System;
using Microsoft.Msagl.Core.Geometry;
using Microsoft.Msagl.Core.Geometry.Curves;
using System.Collections.Generic;
using System.Windows.Media;
namespace Microsoft.Msagl.Core.Layout {
/// <summary>
/// Edge of the graph
/// </summary>
#if TEST_MSAGL
[Serializable]
#endif
#pragma warning disable 1591
public class Edge : GeometryObject, ILabeledObject {
#pragma warning restore 1591
/// <summary>
/// Defines the way the edge connects to the source.
/// The member is used at the moment only when adding an edge to the graph.
/// </summary>
public Port SourcePort {
get { return EdgeGeometry.SourcePort; }
set { EdgeGeometry.SourcePort = value; }
}
/// <summary>
/// defines the way the edge connects to the target
/// The member is used at the moment only when adding an edge to the graph.
/// </summary>
public Port TargetPort {
get { return EdgeGeometry.TargetPort; }
set { EdgeGeometry.TargetPort = value; }
}
readonly List<Label> labels = new List<Label>();
/// <summary>
/// gets the default (first) label of the edge
/// </summary>
public Label Label {
get{
if (labels.Count == 0)
return null;
return labels[0];
}
set {
if (labels.Count == 0) {
labels.Add(value);
} else {
labels[0] = value;
}
}
}
/// <summary>
/// Returns the full enumeration of labels associated with this edge
/// </summary>
public IList<Label> Labels {
get { return labels; }
}
Node source;
/// <summary>
/// id of the source node
/// </summary>
public Node Source {
get { return source; }
set { source = value; }
}
int sourceAnchorNumber;
/// <summary>
/// For future use: The index of the anchor at the source node. By default is zero.
/// </summary>
public int SourceAnchorNumber {
get { return sourceAnchorNumber; }
set { sourceAnchorNumber = value; }
}
Node target;
/// <summary>
/// id of the target node
/// </summary>
public Node Target {
get { return target; }
set { target = value; }
}
int targetAnchorNumber;
/// <summary>
/// For future use:The index of the anchor at the target node. By default is zero.
/// </summary>
public int TargetAnchorNumber {
get { return targetAnchorNumber; }
set { targetAnchorNumber = value; }
}
/// <summary>
/// Label width, need to backup it for transformation purposes
/// </summary>
internal double OriginalLabelWidth { get; set; }
/// <summary>
/// Original label height
/// </summary>
internal double OriginalLabelHeight { get; set; }
/// <summary>
/// Edge constructor
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <param name="labelWidth"></param>
/// <param name="labelHeight"></param>
/// <param name="edgeThickness"></param>
public Edge(Node source, Node target, double labelWidth, double labelHeight, double edgeThickness) {
this.source = source;
this.target = target;
if (labelWidth > 0)
Label = new Label(labelWidth, labelHeight, this);
LineWidth = edgeThickness;
}
/// <summary>
/// Constructs an edge without a label or arrowheads and with edge thickness 1.
/// </summary>
/// <param name="source">souce node</param>
/// <param name="target">target node</param>
public Edge(Node source, Node target)
: this(source, target, 0, 0, 1) {
}
/// <summary>
/// The default constructor
/// </summary>
public Edge() : this(null, null) {
}
/// <summary>
/// The label bounding box
/// </summary>
internal Rectangle LabelBBox {
get { return Label.BoundingBox; }
}
double length = 1;
/// <summary>
/// applicable for MDS layouts
/// </summary>
public double Length {
get { return length; }
set { length = value; }
}
int weight = 1;
/// <summary>
/// The greater is the weight the more important is keeping the edge short. It is 1 by default.
/// Other values are not tested yet.
/// </summary>
public int Weight {
get { return weight; }
set { weight = value; }
}
int separation = 1;
/// <summary>
/// The minimum number of levels dividing source from target: 1 means that the edge goes down at least one level.
/// Separation is 1 by default. Other values are not tested yet.
/// </summary>
public int Separation {
get { return separation; }
set { separation = value; }
}
/// <summary>
/// overrides ToString
/// </summary>
/// <returns></returns>
public override string ToString() {
return source + "->" + target;
}
/// <summary>
/// edge thickness
/// </summary>
public double LineWidth {
get { return EdgeGeometry.LineWidth; }
set { EdgeGeometry.LineWidth = value; }
}
/// <summary>
/// The bounding box of the edge curve
/// </summary>
public override Rectangle BoundingBox {
get {
var rect = Rectangle.CreateAnEmptyBox();
if (UnderlyingPolyline != null)
foreach (Point p in UnderlyingPolyline)
rect.Add(p);
if (Curve != null)
rect.Add(Curve.BoundingBox);
if (EdgeGeometry != null) {
if (EdgeGeometry.SourceArrowhead != null)
rect.Add(EdgeGeometry.SourceArrowhead.TipPosition);
if (EdgeGeometry.TargetArrowhead != null)
rect.Add(EdgeGeometry.TargetArrowhead.TipPosition);
}
double del = LineWidth;
rect.Left -= del;
rect.Top += del;
rect.Right += del;
rect.Bottom -= del;
return rect;
}
set { throw new NotImplementedException(); }
}
EdgeGeometry edgeGeometry = new EdgeGeometry();
public SolidColorBrush Color;
/// <summary>
/// Gets or sets the edge geometry: the curve, the arrowhead positions and the underlying polyline
/// </summary>
public EdgeGeometry EdgeGeometry {
get { return edgeGeometry; }
set { edgeGeometry = value; }
}
/// <summary>
/// the polyline of the untrimmed spline
/// </summary>
public SmoothedPolyline UnderlyingPolyline {
get { return edgeGeometry.SmoothedPolyline; }
set { edgeGeometry.SmoothedPolyline = value; }
}
/// <summary>
/// A curve representing the edge
/// </summary>
public ICurve Curve {
get { return edgeGeometry != null ? edgeGeometry.Curve : null; }
set {
RaiseLayoutChangeEvent(value);
edgeGeometry.Curve = value;
}
}
/// <summary>
/// Transform the curve, arrowheads and label according to the given matrix
/// </summary>
/// <param name="matrix">affine transform matrix</param>
internal void Transform(PlaneTransformation matrix)
{
if (Curve == null)
return;
Curve = Curve.Transform(matrix);
if (UnderlyingPolyline != null)
for (Site s = UnderlyingPolyline.HeadSite, s0 = UnderlyingPolyline.HeadSite;
s != null;
s = s.Next, s0 = s0.Next)
s.Point = matrix * s.Point;
var sourceArrow = edgeGeometry.SourceArrowhead;
if (sourceArrow != null)
sourceArrow.TipPosition = matrix * sourceArrow.TipPosition;
var targetArrow = edgeGeometry.TargetArrowhead;
if (targetArrow != null)
targetArrow.TipPosition = matrix * targetArrow.TipPosition;
if (Label != null)
Label.Center = matrix * LabelBBox.Center;
}
/// <summary>
/// Translate the edge curve arrowheads and label by the specified delta
/// </summary>
/// <param name="delta">amount to shift geometry</param>
public void Translate(Point delta)
{
if (this.EdgeGeometry != null)
{
this.EdgeGeometry.Translate(delta);
}
foreach (var l in this.Labels)
{
l.Translate(delta);
}
}
/// <summary>
/// transforms relative to given rectangles
/// </summary>
public void TransformRelativeTo(Rectangle oldBounds, Rectangle newBounds)
{
if (EdgeGeometry != null) {
var toOrigin = new PlaneTransformation(1, 0, -oldBounds.Left, 0, 1, -oldBounds.Bottom);
var scale = new PlaneTransformation(newBounds.Width/oldBounds.Width, 0, 0,
0,newBounds.Height/oldBounds.Height, 0);
var toNewBounds = new PlaneTransformation(1, 0, newBounds.Left, 0, 1, newBounds.Bottom);
Transform(toNewBounds*scale*toOrigin);
}
foreach (var l in this.Labels)
{
l.Translate(newBounds.LeftBottom - oldBounds.LeftBottom);
}
}
/// <summary>
/// Checks if an arrowhead is needed at the source
/// </summary>
public bool ArrowheadAtSource
{
get
{
return EdgeGeometry != null && EdgeGeometry.SourceArrowhead != null;
}
}
/// <summary>
/// Checks if an arrowhead is needed at the target
/// </summary>
public bool ArrowheadAtTarget
{
get
{
return EdgeGeometry != null && EdgeGeometry.TargetArrowhead != null;
}
}
/// <summary>
/// Routes a self edge inside the given "howMuchToStickOut" parameter
/// </summary>
/// <param name="boundaryCurve"></param>
/// <param name="howMuchToStickOut"></param>
/// <param name="smoothedPolyline"> the underlying polyline used later for editing</param>
/// <returns></returns>
static internal ICurve RouteSelfEdge(ICurve boundaryCurve, double howMuchToStickOut, out SmoothedPolyline smoothedPolyline)
{
//we just need to find the box of the corresponding node
var w = boundaryCurve.BoundingBox.Width;
var h = boundaryCurve.BoundingBox.Height;
var center = boundaryCurve.BoundingBox.Center;
var p0 = new Point(center.X - w / 4, center.Y);
var p1 = new Point(center.X - w / 4, center.Y - h / 2 - howMuchToStickOut);
var p2 = new Point(center.X + w / 4, center.Y - h / 2 - howMuchToStickOut);
var p3 = new Point(center.X + w / 4, center.Y);
smoothedPolyline = SmoothedPolyline.FromPoints(new[] { p0, p1, p2, p3 });
return smoothedPolyline.CreateCurve();
}
/// <summary>
///
/// </summary>
/// <param name="newValue"></param>
public override void RaiseLayoutChangeEvent(object newValue) {
edgeGeometry.RaiseLayoutChangeEvent(newValue);
}
/// <summary>
///
/// </summary>
public override event EventHandler<LayoutChangeEventArgs> BeforeLayoutChangeEvent {
add { edgeGeometry.LayoutChangeEvent+=value; }
remove { edgeGeometry.LayoutChangeEvent-=value; }
}
internal bool UnderCollapsedCluster() {
return Source.UnderCollapsedCluster() || Target.UnderCollapsedCluster();
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
using System;
using System.Collections;
using System.IO;
using NUnit.Framework;
using NPOI.POIFS.FileSystem;
using NPOI.Util;
using NPOI.POIFS.Storage;
using NPOI.POIFS.Properties;
namespace TestCases.POIFS.FileSystem
{
/**
* Class to Test DocumentDescriptor functionality
*
* @author Marc Johnson
*/
[TestFixture]
public class TestDocumentDescriptor
{
/**
* Constructor TestDocumentDescriptor
*
* @param name
*/
public TestDocumentDescriptor()
{
}
/**
* Test equality
*/
[Test]
public void TestEquality()
{
String[] names =
{
"c1", "c2", "c3", "c4", "c5"
};
POIFSDocumentPath a1 = new POIFSDocumentPath();
POIFSDocumentPath a2 = new POIFSDocumentPath(null);
POIFSDocumentPath a3 = new POIFSDocumentPath(new String[0]);
POIFSDocumentPath a4 = new POIFSDocumentPath(a1, null);
POIFSDocumentPath a5 = new POIFSDocumentPath(a1,
new String[0]);
POIFSDocumentPath[] paths =
{
a1, a2, a3, a4, a5
};
for (int j = 0; j < paths.Length; j++)
{
for (int k = 0; k < paths.Length; k++)
{
for (int m = 0; m < names.Length; m++)
{
DocumentDescriptor d1 = new DocumentDescriptor(paths[j],
names[m]);
for (int n = 0; n < names.Length; n++)
{
DocumentDescriptor d2 =
new DocumentDescriptor(paths[k], names[n]);
if (m == n)
{
Assert.AreEqual(d1, d2, "" + j + "," + k + "," + m + ","
+ n);
}
else
{
Assert.IsTrue(!d1.Equals(d2), "" + j + "," + k + "," + m + "," + n);
}
}
}
}
}
a2 = new POIFSDocumentPath(a1, new String[]
{
"foo"
});
a3 = new POIFSDocumentPath(a2, new String[]
{
"bar"
});
a4 = new POIFSDocumentPath(a3, new String[]
{
"fubar"
});
a5 = new POIFSDocumentPath(a4, new String[]
{
"foobar"
});
POIFSDocumentPath[] builtUpPaths =
{
a1, a2, a3, a4, a5
};
POIFSDocumentPath[] fullPaths =
{
new POIFSDocumentPath(), new POIFSDocumentPath(new String[]
{
"foo"
}), new POIFSDocumentPath(new String[]
{
"foo", "bar"
}), new POIFSDocumentPath(new String[]
{
"foo", "bar", "fubar"
}), new POIFSDocumentPath(new String[]
{
"foo", "bar", "fubar", "foobar"
})
};
for (int k = 0; k < builtUpPaths.Length; k++)
{
for (int j = 0; j < fullPaths.Length; j++)
{
for (int m = 0; m < names.Length; m++)
{
DocumentDescriptor d1 =
new DocumentDescriptor(fullPaths[j], names[m]);
for (int n = 0; n < names.Length; n++)
{
DocumentDescriptor d2 =
new DocumentDescriptor(builtUpPaths[k],
names[n]);
if ((k == j) && (m == n))
{
Assert.AreEqual(d1, d2, "" + j + "," + k + "," + m + ","
+ n);
}
else
{
Assert.IsTrue(!(d1.Equals(d2)), "" + j + "," + k + "," + m + "," + n);
}
}
}
}
}
POIFSDocumentPath[] badPaths =
{
new POIFSDocumentPath(new String[]
{
"_foo"
}), new POIFSDocumentPath(new String[]
{
"foo", "_bar"
}), new POIFSDocumentPath(new String[]
{
"foo", "bar", "_fubar"
}), new POIFSDocumentPath(new String[]
{
"foo", "bar", "fubar", "_foobar"
})
};
for (int k = 0; k < builtUpPaths.Length; k++)
{
for (int j = 0; j < badPaths.Length; j++)
{
for (int m = 0; m < names.Length; m++)
{
DocumentDescriptor d1 =
new DocumentDescriptor(badPaths[j], names[m]);
for (int n = 0; n < names.Length; n++)
{
DocumentDescriptor d2 =
new DocumentDescriptor(builtUpPaths[k],
names[n]);
Assert.IsTrue(!(d1.Equals(d2)), "" + j + "," + k + "," + m + "," + n);
}
}
}
}
}
}
}
| |
// 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 Microsoft.Research.DataStructures;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace Microsoft.Research.CodeAnalysis
{
using SubroutineContext = FList<STuple<CFGBlock, CFGBlock, string>>;
using SubroutineEdge = STuple<CFGBlock, CFGBlock, string>;
public static class Quantifiers
{
internal enum Quantifier { ForAll = 0, Exists = 1 }
public static ForAllIndexedExpression AsForAllIndexed<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions>(
this IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver,
APC pc,
SymbolicValue value)
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
where Expression : IEquatable<Expression>
{
var qd = new QuantifierDecompiler<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions>(driver);
return qd.AsQuantifiedIndexed(Quantifier.ForAll, pc, value) as ForAllIndexedExpression;
}
public static ExistsIndexedExpression AsExistsIndexed<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions>(
this IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver,
APC pc,
SymbolicValue value)
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
where Expression : IEquatable<Expression>
{
var qd = new QuantifierDecompiler<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions>(driver);
return qd.AsQuantifiedIndexed(Quantifier.Exists, pc, value) as ExistsIndexedExpression;
}
internal class QuantifierDecompiler<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions>
: IMethodCodeConsumer<Local, Parameter, Method, Field, Type, Unit, BoxedExpression>
where LogOptions : IFrameworkLogOptions
where Type : IEquatable<Type>
where Expression : IEquatable<Expression>
{
private enum TypeName { Contract = 0, Enumerable = 1, Array = 2 }
// T
private static readonly string[,] NameTable = {
// Contract Enumerable Array
/* ForAll */ {"ForAll", "All", "TrueForAll"},
/* Exist */ {"Exists", "Any", "Exists"}
};
private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver;
private SymbolicValue targetObject;
private APC contractPC;
private BoxedExpression boundVariable;
public QuantifierDecompiler(
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver
)
{
this.driver = driver;
}
[ContractVerification(true)]
internal QuantifiedIndexedExpression AsQuantifiedIndexed(Quantifier quantifier, APC pc, SymbolicValue value)
{
var MetaDataDecoder = driver.RawLayer.MetaDataDecoder;
Method method;
SymbolicValue[] args;
contractPC = pc;
if (!driver.Context.ValueContext.IsPureFunctionCall(pc, value, out method, out args)) return null;
var methodName = MetaDataDecoder.Name(method);
var typeName = MetaDataDecoder.Name(MetaDataDecoder.DeclaringType(method));
if (args.Length == 2)
{
if (methodName == NameTable[(int)quantifier, 0] && typeName == "Contract"
|| methodName == NameTable[(int)quantifier, 1] && typeName == "Enumerable")
{
Method forallBody;
if (!driver.Context.ValueContext.IsDelegateValue(pc, args[1], out targetObject, out forallBody)) return null;
var boundParameters = MetaDataDecoder.Parameters(forallBody);
Contract.Assume(boundParameters.Count == 1, "should be ensured by ForAll/Exists type");
var boundParameter = boundParameters[0];
var boundParameterType = MetaDataDecoder.ParameterType(boundParameter);
forallBody = MetaDataDecoder.Unspecialized(forallBody);
if (!MetaDataDecoder.HasBody(forallBody)) return null;
// find enumerable (arg to forall is enumerable object version)
SymbolicValue enumerable;
if (!driver.Context.ValueContext.TryGetObjectFromObjectVersion(pc, args[0], out enumerable)) return null;
// find model array in enumerable
var enumerableType = driver.Context.ValueContext.GetType(pc, enumerable);
SymbolicValue modelArray;
if (enumerableType.IsNormal && MetaDataDecoder.IsArray(enumerableType.Value))
{
modelArray = enumerable; // itself
}
else
{
if (!driver.Context.ValueContext.TryGetModelArray(pc, enumerable, out modelArray)) return null;
}
SymbolicValue arrayLen;
if (!driver.Context.ValueContext.TryGetArrayLength(pc, modelArray, out arrayLen)) return null;
// bound variable is array index
var index = BoxedExpression.Var("i", null, MetaDataDecoder.System_Int32);
var arrayBox = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, modelArray), driver.ExpressionDecoder);
if (arrayBox != null)
{
boundVariable = BoxedExpression.ArrayIndex<Type>(arrayBox, index, boundParameterType);
var bodyDecoded = MetaDataDecoder.AccessMethodBody(forallBody, this, Unit.Value);
if (bodyDecoded == null) return null;
var lowerBound = BoxedExpression.Const(0, MetaDataDecoder.System_Int32, MetaDataDecoder);
var upperBound = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, arrayLen), driver.ExpressionDecoder);
if (/*lowerBound != null && */ upperBound != null)
{
return MakeQuantifierExpression(value, quantifier, index, lowerBound, upperBound, bodyDecoded);
}
}
}
else if (methodName == NameTable[(int)quantifier, 2] && typeName == "Array")
{
Method forallBody;
if (!driver.Context.ValueContext.IsDelegateValue(pc, args[1], out targetObject, out forallBody)) return null;
var boundParameters = MetaDataDecoder.Parameters(forallBody);
Contract.Assume(boundParameters != null && boundParameters.Count == 1, "should be ensured by TrueForAll/Exists type");
var boundParameter = boundParameters[0];
var boundParameterType = MetaDataDecoder.ParameterType(boundParameter);
forallBody = MetaDataDecoder.Unspecialized(forallBody);
if (!MetaDataDecoder.HasBody(forallBody)) return null;
// find enumerable (arg to forall is enumerable object version)
SymbolicValue modelArray;
if (!driver.Context.ValueContext.TryGetObjectFromObjectVersion(pc, args[0], out modelArray)) return null;
// find array length
SymbolicValue arrayLen;
if (!driver.Context.ValueContext.TryGetArrayLength(pc, modelArray, out arrayLen)) return null;
// bound variable is array index
var index = BoxedExpression.Var("i", null, MetaDataDecoder.System_Int32);
var arrayBox = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, modelArray), driver.ExpressionDecoder);
if (arrayBox != null)
{
boundVariable = BoxedExpression.ArrayIndex<Type>(arrayBox, index, boundParameterType);
var bodyDecoded = MetaDataDecoder.AccessMethodBody(forallBody, this, Unit.Value);
if (bodyDecoded == null) return null;
var lowerBound = BoxedExpression.Const(0, MetaDataDecoder.System_Int32, MetaDataDecoder);
var upperBound = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, arrayLen), driver.ExpressionDecoder);
if (/*lowerBound != null && */ upperBound != null)
{
return MakeQuantifierExpression(value, quantifier, index, lowerBound, upperBound, bodyDecoded);
}
}
}
return null;
}
if (args.Length == 3)
{
if (driver.MetaDataDecoder.Name(method) != NameTable[(int)quantifier, 0]) return null;
if (driver.MetaDataDecoder.Name(driver.MetaDataDecoder.DeclaringType(method)) != "Contract") return null;
Method forallBody;
if (!driver.Context.ValueContext.IsDelegateValue(pc, args[2], out targetObject, out forallBody)) return null;
forallBody = driver.MetaDataDecoder.Unspecialized(forallBody);
if (!driver.MetaDataDecoder.HasBody(forallBody)) return null;
// bound variable is index
boundVariable = BoxedExpression.Var("i", null, driver.MetaDataDecoder.System_Int32);
var bodyDecoded = driver.MetaDataDecoder.AccessMethodBody(forallBody, this, Unit.Value);
if (bodyDecoded == null) return null;
var lowerBound = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, args[0]), driver.ExpressionDecoder);
var upperBound = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(pc, args[1]), driver.ExpressionDecoder);
if (lowerBound != null && upperBound != null)
{
return MakeQuantifierExpression(value, quantifier, boundVariable, lowerBound, upperBound, bodyDecoded);
}
}
return null;
}
[ContractVerification(true)]
private static QuantifiedIndexedExpression MakeQuantifierExpression(
object variable,
Quantifier quantifier,
BoxedExpression index, BoxedExpression lowerBound, BoxedExpression upperBound, BoxedExpression body)
{
Contract.Requires(index != null);
Contract.Requires(lowerBound != null);
Contract.Requires(upperBound != null);
Contract.Requires(body != null);
Contract.Ensures(Contract.Result<QuantifiedIndexedExpression>() != null);
switch (quantifier)
{
case Quantifier.Exists:
return new ExistsIndexedExpression(variable, index, lowerBound, upperBound, body);
case Quantifier.ForAll:
return new ForAllIndexedExpression(variable, index, lowerBound, upperBound, body);
default:
Contract.Assert(false);
return null;
}
}
#region IMethodCodeConsumer<Local,Parameter,Method,Field,Type,Env,BoxedExpression> Members
private class Env
{
public struct Both
{
public BoxedExpression Boxed;
public SymbolicValue Sym;
public Both(BoxedExpression boxedExpression)
{
this.Boxed = boxedExpression;
this.Sym = default(SymbolicValue);
}
public Both(SymbolicValue sym)
{
this.Boxed = null;
this.Sym = sym;
}
}
private readonly Stack<Both> stack = new Stack<Both>();
readonly private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver;
readonly private APC contractPC;
public Env(IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> iMethodDriver,
APC contractPC)
{
Contract.Requires(iMethodDriver != null);
this.contractPC = contractPC;
driver = iMethodDriver;
}
internal bool PopBE(out BoxedExpression boxed)
{
Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out boxed) != null);
var both = Pop();
if (both.Boxed != null) { boxed = both.Boxed; return true; }
if (!driver.Context.ValueContext.IsValid(both.Sym)) { boxed = null; return false; }
boxed = BoxedExpression.Convert(driver.Context.ExpressionContext.Refine(contractPC, both.Sym), driver.ExpressionDecoder);
// conversion may fail, so we check it
return boxed != null ? true : false;
}
internal void Push(BoxedExpression boxedExpression)
{
stack.Push(new Both(boxedExpression));
}
internal void Push(SymbolicValue sym)
{
stack.Push(new Both(sym));
}
internal bool PopSV(out SymbolicValue sym)
{
var both = Pop();
if (!driver.Context.ValueContext.IsValid(both.Sym)) { sym = default(SymbolicValue); return false; }
sym = both.Sym;
return true;
}
internal Both Pop()
{
if (stack.Count > 0) { return stack.Pop(); }
return default(Both);
}
internal bool Dup(int offset)
{
if (stack.Count > offset)
{
var array = stack.ToArray();
var toCopy = array[stack.Count - 1 - offset];
stack.Push(toCopy);
return true;
}
return false;
}
public int StackDepth { get { return stack.Count; } }
}
private class Decoder<Label2, Handler> : ICodeQuery<Label2, Local, Parameter, Method, Field, Type, Env, bool>
{
internal BoxedExpression resultExpression;
private BoxedExpression boundVar;
private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> driver;
private Method body;
private bool isStatic;
private SymbolicValue closure;
private APC contractPC;
private IMethodCodeProvider<Label2, Local, Parameter, Method, Field, Type, Handler> codeProvider;
public Decoder(
APC contractPC,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, SymbolicValue, LogOptions> iMethodDriver,
SymbolicValue closure,
Method body,
BoxedExpression boundVar,
IMethodCodeProvider<Label2, Local, Parameter, Method, Field, Type, Handler> codeProvider)
{
this.closure = closure;
this.contractPC = contractPC;
driver = iMethodDriver;
this.body = body;
this.codeProvider = codeProvider;
this.boundVar = boundVar;
isStatic = driver.MetaDataDecoder.IsStatic(body);
}
#region ICodeQuery<Label2,Local,Parameter,Method,Field,Type,Env,BoxedExpression> Members
public bool Aggregate(Label2 current, Label2 aggregateStart, bool canBeTargetOfBranch, Env data)
{
current = aggregateStart;
do
{
var success = codeProvider.Decode<Decoder<Label2, Handler>, Env, bool>(current, this, data);
if (!success) return false;
}
while (codeProvider.Next(current, out current));
return true;
}
#endregion
#region IVisitMSIL<Label2,Local,Parameter,Method,Field,Type,Unit,Unit,Env,BoxedExpression> Members
public bool Arglist(Label2 pc, DataStructures.Unit dest, Env data)
{
return false;
}
public bool BranchCond(Label2 pc, Label2 target, BranchOperator bop, DataStructures.Unit value1, DataStructures.Unit value2, Env data)
{
return false;
}
public bool BranchTrue(Label2 pc, Label2 target, DataStructures.Unit cond, Env data)
{
return false;
}
public bool BranchFalse(Label2 pc, Label2 target, DataStructures.Unit cond, Env data)
{
return false;
}
public bool Branch(Label2 pc, Label2 target, bool leave, Env data)
{
return false;
}
public bool Break(Label2 pc, Env data)
{
return true;
}
public bool Call<TypeList, ArgList>(Label2 pc, Method method, bool tail, bool virt, TypeList extraVarargs, DataStructures.Unit dest, ArgList args, Env data)
where TypeList : DataStructures.IIndexable<Type>
where ArgList : DataStructures.IIndexable<DataStructures.Unit>
{
var mdDecoder = driver.MetaDataDecoder;
var declaringType = mdDecoder.DeclaringType(method);
var methodName = mdDecoder.Name(method);
#region explicit == operator overloads
if (args.Count > 1 && (mdDecoder.IsReferenceType(declaringType) || mdDecoder.IsNativePointerType(declaringType)))
{
if (methodName.EndsWith("op_Inequality"))
{
return this.Binary(pc, BinaryOperator.Cne_Un, dest, args[0], args[1], data);
}
else if (methodName.EndsWith("op_Equality"))
{
if (mdDecoder.IsNativePointerType(declaringType))
{
return this.Binary(pc, BinaryOperator.Ceq, dest, args[0], args[1], data);
}
else
{
return this.Binary(pc, BinaryOperator.Cobjeq, dest, args[0], args[1], data);
}
}
}
#endregion
#region Identity functions
if ((mdDecoder.Equal(declaringType, mdDecoder.System_UIntPtr)
|| mdDecoder.Equal(declaringType, mdDecoder.System_IntPtr))
&& methodName.StartsWith("op_Explicit"))
{
Contract.Assert(0 <= args.Count);
return this.Ldstack(pc, 0, dest, args[0], false, data);
}
// VB's funny copy method that copies boxed objects to avoid aliasing by accident
if (methodName == "GetObjectValue" && mdDecoder.Name(declaringType) == "RuntimeHelpers")
{
return this.Ldstack(pc, 0, dest, args[0], false, data);
}
#endregion
return false;
}
public bool Calli<TypeList, ArgList>(Label2 pc, Type returnType, TypeList argTypes, bool tail, bool isInstance, DataStructures.Unit dest, DataStructures.Unit fp, ArgList args, Env data)
where TypeList : DataStructures.IIndexable<Type>
where ArgList : DataStructures.IIndexable<DataStructures.Unit>
{
return false;
}
public bool Ckfinite(Label2 pc, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
return false;
}
public bool Cpblk(Label2 pc, bool @volatile, DataStructures.Unit destaddr, DataStructures.Unit srcaddr, DataStructures.Unit len, Env data)
{
return false;
}
public bool Endfilter(Label2 pc, DataStructures.Unit decision, Env data)
{
return false;
}
public bool Endfinally(Label2 pc, Env data)
{
return false;
}
public bool Initblk(Label2 pc, bool @volatile, DataStructures.Unit destaddr, DataStructures.Unit value, DataStructures.Unit len, Env data)
{
return false;
}
public bool Jmp(Label2 pc, Method method, Env data)
{
return false;
}
/// <summary>
/// Remaps a parameter referenced in a subroutine to the parameter used in the calling context
/// This is needed e.g. when inheriting requires/ensures/invariant subroutines, as the parameter
/// identities are different in each override.
/// </summary>
/// <param name="p">Parameter as appearing in the subroutine</param>
/// <param name="parentMethodBlock">block in the method calling the subroutine</param>
/// <param name="subroutineBlock">block in the subroutine</param>
/// <returns>The equivalent parameter in the calling method's context</returns>
private Parameter RemapParameter(Parameter p, CFGBlock parentMethodBlock, CFGBlock subroutineBlock)
{
Contract.Requires(subroutineBlock != null);// F: added because of Clousot suggestion
Contract.Requires(parentMethodBlock != null);// F: added because of Clousot suggestion
var mdDecoder = driver.MetaDataDecoder;
IMethodInfo<Method> parentMethodInfo = (IMethodInfo<Method>)parentMethodBlock.Subroutine;
IMethodInfo<Method> subroutineMethodInfo = (IMethodInfo<Method>)subroutineBlock.Subroutine;
if (mdDecoder.Equal(parentMethodInfo.Method, subroutineMethodInfo.Method))
{
return p;
}
var argIndex = mdDecoder.ArgumentIndex(p);
Contract.Assume(argIndex >= 0);
if (mdDecoder.IsStatic(parentMethodInfo.Method))
{
return mdDecoder.Parameters(parentMethodInfo.Method)[argIndex];
}
else
{
if (argIndex == 0)
{
// refers to "this"
return mdDecoder.This(parentMethodInfo.Method);
}
var parameters = mdDecoder.Parameters(parentMethodInfo.Method).AssumeNotNull();
Contract.Assume(argIndex < parameters.Count);
return parameters[argIndex - 1];
}
}
/// <summary>
/// Implementes the logic outlined in Ldarg by mapping a parameter x APC context into one of
/// three cases:
/// - ldresult (indicated by setting isLdResult true and setting ldStackOffset)
/// - ldstack offset (indicated by returning true, and setting ldStackOffset)
/// - ldarg P' (otherwise, where the parameter ref contains p' on exit)
/// </summary>
/// <param name="isOld">set to true if the resulting instruction should execute in the pre-state of the
/// method.</param>
/// <param name="lookupPC">Set to the pc at which we need to consider the ldStackOffset. Valid on true return.</param>
/// <returns>true if the parameter access maps to ldresult</returns>
private bool RemapParameterToLdStack(APC pc, ref Parameter p, out bool isLdResult, out int ldStackOffset, out bool isOld, out APC lookupPC, Env data)
{
Contract.Requires(data != null);
if (pc.SubroutineContext != null)
{
#region Requires
if (pc.Block.Subroutine.IsRequires)
{
// find whether calling context is entry, newObj, or call. In the first case, also remap
// the parameter if necessary
isLdResult = false;
isOld = false;
lookupPC = pc;
for (var scontext = pc.SubroutineContext; scontext != null; scontext = scontext.Tail)
{
var callTag = scontext.Head.Three;
Contract.Assume(callTag != null);
if (callTag == "entry")
{
// keep as ldarg, but figure out whether we need to remap
Contract.Assume(scontext.Head.One != null);
p = RemapParameter(p, scontext.Head.One, pc.Block);
ldStackOffset = 0;
return false;
}
if (callTag.StartsWith("before")) // beforeCall | beforeNewObj
{
int localStackDepth = driver.Context.StackContext.LocalStackDepth(contractPC) + data.StackDepth;
ldStackOffset = driver.MetaDataDecoder.ArgumentStackIndex(p) + localStackDepth;
return true;
}
}
throw new NotImplementedException();
}
#endregion
#region Ensures
else if (pc.Block.Subroutine.IsEnsuresOrOld)
{
// find whether calling context is exit, newObj, or call. In the first case, also remap
// the parameter if necessary
isOld = true;
for (SubroutineContext scontext = pc.SubroutineContext; scontext != null; scontext = scontext.Tail)
{
string callTag = scontext.Head.Three;
if (callTag == "exit")
{
// keep as ldarg, but figure out whether we need to remap
Contract.Assume(scontext.Head.One != null);
p = RemapParameter(p, scontext.Head.One, pc.Block);
isLdResult = false;
ldStackOffset = 0;
lookupPC = pc; // irrelevant
return false;
}
if (callTag == "afterCall")
{
// we need to compute the offset to the "parameter" on the stack. For this we must
// know what method is being called.
ldStackOffset = driver.MetaDataDecoder.ArgumentStackIndex(p);
// no need to correct for local stack depth, as we lookup the stack in the old-state
isLdResult = false;
lookupPC = new APC(scontext.Head.One, 0, scontext.Tail);
return true;
}
if (callTag == "afterNewObj")
{
// here we have to deal with the special case of referencing argument 0, which is the result
// of the construction. In that case we have to return "ldresult"
int parameterIndex = driver.MetaDataDecoder.ArgumentIndex(p);
if (parameterIndex == 0)
{
ldStackOffset = driver.Context.StackContext.LocalStackDepth(pc) + data.StackDepth;
isLdResult = true;
lookupPC = pc; // irrelevant
isOld = false;
return false;
}
// we need to compute the offset to the "parameter" on the stack. For this we must
// know what method is being called.
ldStackOffset = driver.MetaDataDecoder.ArgumentStackIndex(p);
// no need to correct for local stack depth, as we lookup the stack in the old-state
isLdResult = false;
lookupPC = new APC(scontext.Head.One, 0, scontext.Tail);
return true;
}
if (callTag == "oldmanifest")
{
// used to manifest the old values on entry to a method
// keep as ldarg, but figure out whether we need to remap
Contract.Assume(scontext.Tail.Head.One != null);
p = RemapParameter(p, scontext.Tail.Head.One, pc.Block);
isOld = false;
isLdResult = false;
ldStackOffset = 0;
lookupPC = pc; // irrelevant
return false;
}
}
throw new NotImplementedException();
}
#endregion
#region Invariant
else if (pc.Block.Subroutine.IsInvariant)
{
for (SubroutineContext scontext = pc.SubroutineContext; scontext != null; scontext = scontext.Tail)
{
string callTag = scontext.Head.Three;
// must be "this"
Contract.Assume(driver.MetaDataDecoder.ArgumentIndex(p) == 0);
if (callTag == "entry" || callTag == "exit")
{
// keep as ldarg, but remap to this of containing method
Method containingMethod;
if (pc.TryGetContainingMethod(out containingMethod))
{
p = driver.MetaDataDecoder.This(containingMethod);
isLdResult = false;
ldStackOffset = 0;
isOld = (callTag == "exit");
lookupPC = pc; // irrelevant
return false;
}
else
{
Contract.Assume(false, "Not in a method context");
// dont'r remap
isLdResult = false;
ldStackOffset = 0;
isOld = false;
lookupPC = pc;
return false;
}
}
if (callTag == "afterCall")
{
// we need to compute the offset to the "this" receiver on the stack. For this we must
// know what method is being called.
Method calledMethod;
bool isNewObj;
bool isVirtualCall;
var success = scontext.Head.One.IsMethodCallBlock(out calledMethod, out isNewObj, out isVirtualCall);
Contract.Assume(success); // must be a method call blcok
int parameterCount = driver.MetaDataDecoder.Parameters(calledMethod).Count;
ldStackOffset = parameterCount; // 0 is top, 1 is 1 step below top of stack, etc...
// no need to correct for local stack depth, as we lookup the stack in the old-state
isLdResult = false;
isOld = true;
lookupPC = new APC(scontext.Head.One, 0, scontext.Tail);
return true;
}
if (callTag == "afterNewObj")
{
// we need to map "this" to ldresult
isLdResult = true;
ldStackOffset = driver.Context.StackContext.LocalStackDepth(pc) + data.StackDepth;
isOld = false;
lookupPC = pc;
return false;
}
if (callTag == "assumeInvariant")
{
// we need to map "this" to ldstack.0 just prior to call (object must be on top of stack)
isLdResult = false;
ldStackOffset = 0;
isOld = true;
lookupPC = new APC(scontext.Head.One, 0, scontext.Tail);
return true;
}
if (callTag == "beforeCall")
{
throw new InvalidOperationException("This should never happen");
}
if (callTag == "beforeNewObj")
{
throw new InvalidOperationException("This should never happen");
}
}
throw new NotImplementedException();
}
#endregion
}
isLdResult = false;
ldStackOffset = 0;
isOld = false;
lookupPC = pc;
return false;
}
/// <summary>
/// We have to distinguish 3 cases:
///
/// 1. Access to an argument of the closure method (the index)
/// 2. Access to the "this" argument of the closure method (to get to the closure values under CCI1)
/// 3. Access to the enclosing method parameters (under CCI2)
/// 3a. This can be the method under analysis, if the forall is a pre/post condition
/// 3b. This can be a called method from the method under analysis (at new or call)
/// 3c. This can be called methods from within contracts of called methods
/// </summary>
public bool Ldarg(Label2 pc, Parameter argument, bool isOldIgnored, DataStructures.Unit dest, Env data)
{
Contract.Assume(data != null);
// determine if argument belongs to method on stack at contarctPC
if (!OnStack(contractPC, driver.MetaDataDecoder.DeclaringMethod(argument)))
{
// could be closure this
if (!isStatic && driver.MetaDataDecoder.ArgumentIndex(argument) == 0)
{
data.Push(closure);
return true;
}
// can only be index
data.Push(boundVar);
return true;
}
// First check to see if the parameter is a parameter of the method enclosing the
// quantifier.
SymbolicValue sv;
if (driver.Context.ValueContext.TryParameterValue(contractPC, argument, out sv))
{
data.Push(sv);
return true;
}
// Now try to figure out where on the evaluation stack the parameters of this inner call would be
bool isLdResult;
int ldStackOffset;
bool isOld;
APC lookupPC;
var mdDecoder = driver.MetaDataDecoder;
Parameter oldArgument = argument;
if (RemapParameterToLdStack(contractPC, ref argument, out isLdResult, out ldStackOffset, out isOld, out lookupPC, data))
{
// ldstack
return this.LdstackSpecial(lookupPC, ldStackOffset, dest, Unit.Value, isOld, data);
}
// F: TODOTODO Awfull fix!!!! But I do not really understand the code, I should talk with MAF about it
if (argument == null)
{
argument = oldArgument;
}
// F: End
if (isLdResult)
{
// ldresult
// special case: if the parameter is typed address of struct, then we must be
// referring to the post state of a struct constructor. In this case, map it to ldstacka
if (mdDecoder.IsStruct(mdDecoder.DeclaringType(mdDecoder.DeclaringMethod(argument))))
{
return this.Ldstacka(pc, ldStackOffset, dest, Unit.Value, mdDecoder.ParameterType(argument), isOld, data);
}
return this.Ldresult(pc, mdDecoder.ParameterType(argument), dest, Unit.Value, data);
}
// if we can't find anything, it might be the index
data.Push(boundVar);
return true;
}
private bool OnStack(APC aPC, Method method)
{
var pcMethod = aPC.Block.Subroutine as IMethodInfo<Method>;
if (pcMethod != null && driver.MetaDataDecoder.Equal(pcMethod.Method, method)) return true;
for (var context = aPC.SubroutineContext; context != null; context = context.Tail)
{
pcMethod = context.Head.One.AssumeNotNull().Subroutine as IMethodInfo<Method>;
if (pcMethod != null && driver.MetaDataDecoder.Equal(pcMethod.Method, method)) return true;
}
return false;
}
public bool Ldarga(Label2 pc, Parameter argument, bool isOld, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldftn(Label2 pc, Method method, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldind(Label2 pc, Type type, bool @volatile, DataStructures.Unit dest, DataStructures.Unit ptr, Env data)
{
SymbolicValue ptrValue;
if (!data.PopSV(out ptrValue)) return false;
SymbolicValue result;
if (!driver.Context.ValueContext.TryLoadIndirect(contractPC, ptrValue, out result)) return false;
data.Push(result);
return true;
}
public bool Ldloc(Label2 pc, Local local, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldloca(Label2 pc, Local local, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Localloc(Label2 pc, DataStructures.Unit dest, DataStructures.Unit size, Env data)
{
return false;
}
public bool Nop(Label2 pc, Env data)
{
return true;
}
public bool Pop(Label2 pc, DataStructures.Unit source, Env data)
{
data.Pop();
return true;
}
public bool Return(Label2 pc, DataStructures.Unit source, Env data)
{
return data.PopBE(out this.resultExpression);
}
public bool Starg(Label2 pc, Parameter argument, DataStructures.Unit source, Env data)
{
return false;
}
public bool Stind(Label2 pc, Type type, bool @volatile, DataStructures.Unit ptr, DataStructures.Unit value, Env data)
{
return false;
}
public bool Stloc(Label2 pc, Local local, DataStructures.Unit source, Env data)
{
return false;
}
public bool Switch(Label2 pc, Type type, System.Collections.Generic.IEnumerable<DataStructures.Pair<object, Label2>> cases, DataStructures.Unit value, Env data)
{
return false;
}
public bool Box(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
// HACK: just leave the same value on the stack
return true;
}
public bool ConstrainedCallvirt<TypeList, ArgList>(Label2 pc, Method method, bool tail, Type constraint, TypeList extraVarargs, DataStructures.Unit dest, ArgList args, Env data)
where TypeList : DataStructures.IIndexable<Type>
where ArgList : DataStructures.IIndexable<DataStructures.Unit>
{
return false;
}
public bool Castclass(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return true; // just leave the same value on the stack
}
public bool Cpobj(Label2 pc, Type type, DataStructures.Unit destptr, DataStructures.Unit srcptr, Env data)
{
return false;
}
public bool Initobj(Label2 pc, Type type, DataStructures.Unit ptr, Env data)
{
return false;
}
public bool Ldelem(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit array, DataStructures.Unit index, Env data)
{
BoxedExpression indexExpr;
if (!data.PopBE(out indexExpr)) return false;
BoxedExpression arrayExpr;
if (!data.PopBE(out arrayExpr)) return false;
data.Push(BoxedExpression.ArrayIndex(arrayExpr, indexExpr, type));
return true;
}
public bool Ldelema(Label2 pc, Type type, bool @readonly, DataStructures.Unit dest, DataStructures.Unit array, DataStructures.Unit index, Env data)
{
return false;
}
public bool Ldfld(Label2 pc, Field field, bool @volatile, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
SymbolicValue objectValue;
if (!data.PopSV(out objectValue)) return false;
SymbolicValue fieldAddress;
if (!driver.Context.ValueContext.TryFieldAddress(contractPC, objectValue, field, out fieldAddress)) return false;
SymbolicValue result;
if (!driver.Context.ValueContext.TryLoadIndirect(contractPC, fieldAddress, out result)) return false;
data.Push(result);
return true;
}
public bool Ldflda(Label2 pc, Field field, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
public bool Ldlen(Label2 pc, DataStructures.Unit dest, DataStructures.Unit array, Env data)
{
SymbolicValue objectValue;
if (!data.PopSV(out objectValue)) return false;
SymbolicValue length;
if (!driver.Context.ValueContext.TryGetArrayLength(contractPC, objectValue, out length)) return false;
data.Push(length);
return true;
}
public bool Ldsfld(Label2 pc, Field field, bool @volatile, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldsflda(Label2 pc, Field field, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldtypetoken(Label2 pc, Type type, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldfieldtoken(Label2 pc, Field field, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldmethodtoken(Label2 pc, Method method, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Ldvirtftn(Label2 pc, Method method, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
public bool Mkrefany(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
public bool Newarray<ArgList>(Label2 pc, Type type, DataStructures.Unit dest, ArgList len, Env data) where ArgList : DataStructures.IIndexable<DataStructures.Unit>
{
return false;
}
public bool Newobj<ArgList>(Label2 pc, Method ctor, DataStructures.Unit dest, ArgList args, Env data) where ArgList : DataStructures.IIndexable<DataStructures.Unit>
{
return false;
}
public bool Refanytype(Label2 pc, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
return false;
}
public bool Refanyval(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
return false;
}
public bool Rethrow(Label2 pc, Env data)
{
return false;
}
public bool Stelem(Label2 pc, Type type, DataStructures.Unit array, DataStructures.Unit index, DataStructures.Unit value, Env data)
{
return false;
}
public bool Stfld(Label2 pc, Field field, bool @volatile, DataStructures.Unit obj, DataStructures.Unit value, Env data)
{
return false;
}
public bool Stsfld(Label2 pc, Field field, bool @volatile, DataStructures.Unit value, Env data)
{
return false;
}
public bool Throw(Label2 pc, DataStructures.Unit exn, Env data)
{
return false;
}
public bool Unbox(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
public bool Unboxany(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
#endregion
#region IVisitSynthIL<Label2,Method,Type,Unit,Unit,Env,BoxedExpression> Members
public bool Entry(Label2 pc, Method method, Env data)
{
return true;
}
public bool Assume(Label2 pc, string tag, DataStructures.Unit condition, object provenance, Env data)
{
return false;
}
public bool Assert(Label2 pc, string tag, DataStructures.Unit condition, object provenance, Env data)
{
return false;
}
private bool LdstackSpecial(APC apc, int offset, DataStructures.Unit dest, DataStructures.Unit source, bool isOld, Env data)
{
if (offset >= data.StackDepth)
{
var normalizedOffset = offset - data.StackDepth;
var top = driver.Context.StackContext.StackDepth(apc) - 1;
var index = top - normalizedOffset;
SymbolicValue result;
if (driver.Context.ValueContext.TryStackValue(apc, index, out result))
{
data.Push(result);
return true;
}
}
return data.Dup(offset);
}
public bool Ldstack(Label2 pc, int offset, DataStructures.Unit dest, DataStructures.Unit source, bool isOld, Env data)
{
return data.Dup(offset);
}
public bool Ldstacka(Label2 pc, int offset, DataStructures.Unit dest, DataStructures.Unit source, Type origParamType, bool isOld, Env data)
{
return false;
}
public bool Ldresult(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
SymbolicValue result;
if (!driver.Context.ValueContext.TryResultValue(contractPC, out result)) return false;
data.Push(result);
return true;
}
public bool BeginOld(Label2 pc, Label2 matchingEnd, Env data)
{
return false;
}
public bool EndOld(Label2 pc, Label2 matchingBegin, Type type, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
return false;
}
#endregion
#region IVisitExprIL<Label2,Type,Unit,Unit,Env,BoxedExpression> Members
public bool Binary(Label2 pc, BinaryOperator op, DataStructures.Unit dest, DataStructures.Unit s1, DataStructures.Unit s2, Env data)
{
BoxedExpression right;
if (!data.PopBE(out right)) return false;
BoxedExpression left;
if (!data.PopBE(out left)) return false;
data.Push(BoxedExpression.Binary(op, left, right));
return true;
}
public bool Isinst(Label2 pc, Type type, DataStructures.Unit dest, DataStructures.Unit obj, Env data)
{
return false;
}
public bool Ldconst(Label2 pc, object constant, Type type, DataStructures.Unit dest, Env data)
{
data.Push(BoxedExpression.Const(constant, type, driver.MetaDataDecoder));
return true;
}
public bool Ldnull(Label2 pc, DataStructures.Unit dest, Env data)
{
data.Push(BoxedExpression.Const(null, default(Type), driver.MetaDataDecoder));
return true;
}
public bool Sizeof(Label2 pc, Type type, DataStructures.Unit dest, Env data)
{
return false;
}
public bool Unary(Label2 pc, UnaryOperator op, bool overflow, bool unsigned, DataStructures.Unit dest, DataStructures.Unit source, Env data)
{
BoxedExpression arg;
if (!data.PopBE(out arg)) return false;
data.Push(BoxedExpression.Unary(op, arg));
return true;
}
#endregion
}
BoxedExpression IMethodCodeConsumer<Local, Parameter, Method, Field, Type, Unit, BoxedExpression>.Accept<Label2, Handler>(
IMethodCodeProvider<Label2, Local, Parameter, Method, Field, Type, Handler> codeProvider,
Label2 entryPoint, Method method, Unit unit)
{
var current = entryPoint;
Env env = new Env(driver, contractPC);
var decoder = new Decoder<Label2, Handler>(contractPC, driver, targetObject, method, boundVariable, codeProvider);
if (!decoder.Aggregate(entryPoint, entryPoint, false, env)) return null;
return decoder.resultExpression;
}
#endregion
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Financial History Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class FINHISTDataSet : EduHubDataSet<FINHIST>
{
/// <inheritdoc />
public override string Name { get { return "FINHIST"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal FINHISTDataSet(EduHubContext Context)
: base(Context)
{
Index_ID = new Lazy<Dictionary<int, FINHIST>>(() => this.ToDictionary(i => i.ID));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="FINHIST" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="FINHIST" /> fields for each CSV column header</returns>
internal override Action<FINHIST, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<FINHIST, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "ID":
mapper[i] = (e, v) => e.ID = int.Parse(v);
break;
case "LEDGER":
mapper[i] = (e, v) => e.LEDGER = v;
break;
case "ENTITY":
mapper[i] = (e, v) => e.ENTITY = v;
break;
case "TRANSACTION_ID":
mapper[i] = (e, v) => e.TRANSACTION_ID = v == null ? (int?)null : int.Parse(v);
break;
case "BSB":
mapper[i] = (e, v) => e.BSB = v;
break;
case "ACCOUNT_NO":
mapper[i] = (e, v) => e.ACCOUNT_NO = v;
break;
case "ACCOUNT_NAME":
mapper[i] = (e, v) => e.ACCOUNT_NAME = v;
break;
case "BILLER_CODE":
mapper[i] = (e, v) => e.BILLER_CODE = v;
break;
case "BPAY_REFERENCE":
mapper[i] = (e, v) => e.BPAY_REFERENCE = v;
break;
case "CREATION_DATE":
mapper[i] = (e, v) => e.CREATION_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="FINHIST" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="FINHIST" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="FINHIST" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{FINHIST}"/> of entities</returns>
internal override IEnumerable<FINHIST> ApplyDeltaEntities(IEnumerable<FINHIST> Entities, List<FINHIST> DeltaEntities)
{
HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.ID;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_ID.Remove(entity.ID);
if (entity.ID.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<int, FINHIST>> Index_ID;
#endregion
#region Index Methods
/// <summary>
/// Find FINHIST by ID field
/// </summary>
/// <param name="ID">ID value used to find FINHIST</param>
/// <returns>Related FINHIST entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public FINHIST FindByID(int ID)
{
return Index_ID.Value[ID];
}
/// <summary>
/// Attempt to find FINHIST by ID field
/// </summary>
/// <param name="ID">ID value used to find FINHIST</param>
/// <param name="Value">Related FINHIST entity</param>
/// <returns>True if the related FINHIST entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByID(int ID, out FINHIST Value)
{
return Index_ID.Value.TryGetValue(ID, out Value);
}
/// <summary>
/// Attempt to find FINHIST by ID field
/// </summary>
/// <param name="ID">ID value used to find FINHIST</param>
/// <returns>Related FINHIST entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public FINHIST TryFindByID(int ID)
{
FINHIST value;
if (Index_ID.Value.TryGetValue(ID, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a FINHIST table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[FINHIST]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[FINHIST](
[ID] int IDENTITY NOT NULL,
[LEDGER] varchar(10) NULL,
[ENTITY] varchar(10) NULL,
[TRANSACTION_ID] int NULL,
[BSB] varchar(6) NULL,
[ACCOUNT_NO] varchar(15) NULL,
[ACCOUNT_NAME] varchar(60) NULL,
[BILLER_CODE] varchar(10) NULL,
[BPAY_REFERENCE] varchar(20) NULL,
[CREATION_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_DATE] datetime NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [FINHIST_Index_ID] PRIMARY KEY CLUSTERED (
[ID] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="FINHISTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="FINHISTDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="FINHIST"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="FINHIST"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<FINHIST> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_ID = new List<int>();
foreach (var entity in Entities)
{
Index_ID.Add(entity.ID);
}
builder.AppendLine("DELETE [dbo].[FINHIST] WHERE");
// Index_ID
builder.Append("[ID] IN (");
for (int index = 0; index < Index_ID.Count; index++)
{
if (index != 0)
builder.Append(", ");
// ID
var parameterID = $"@p{parameterIndex++}";
builder.Append(parameterID);
command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the FINHIST data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the FINHIST data set</returns>
public override EduHubDataSetDataReader<FINHIST> GetDataSetDataReader()
{
return new FINHISTDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the FINHIST data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the FINHIST data set</returns>
public override EduHubDataSetDataReader<FINHIST> GetDataSetDataReader(List<FINHIST> Entities)
{
return new FINHISTDataReader(new EduHubDataSetLoadedReader<FINHIST>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class FINHISTDataReader : EduHubDataSetDataReader<FINHIST>
{
public FINHISTDataReader(IEduHubDataSetReader<FINHIST> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 13; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // ID
return Current.ID;
case 1: // LEDGER
return Current.LEDGER;
case 2: // ENTITY
return Current.ENTITY;
case 3: // TRANSACTION_ID
return Current.TRANSACTION_ID;
case 4: // BSB
return Current.BSB;
case 5: // ACCOUNT_NO
return Current.ACCOUNT_NO;
case 6: // ACCOUNT_NAME
return Current.ACCOUNT_NAME;
case 7: // BILLER_CODE
return Current.BILLER_CODE;
case 8: // BPAY_REFERENCE
return Current.BPAY_REFERENCE;
case 9: // CREATION_DATE
return Current.CREATION_DATE;
case 10: // LW_TIME
return Current.LW_TIME;
case 11: // LW_DATE
return Current.LW_DATE;
case 12: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // LEDGER
return Current.LEDGER == null;
case 2: // ENTITY
return Current.ENTITY == null;
case 3: // TRANSACTION_ID
return Current.TRANSACTION_ID == null;
case 4: // BSB
return Current.BSB == null;
case 5: // ACCOUNT_NO
return Current.ACCOUNT_NO == null;
case 6: // ACCOUNT_NAME
return Current.ACCOUNT_NAME == null;
case 7: // BILLER_CODE
return Current.BILLER_CODE == null;
case 8: // BPAY_REFERENCE
return Current.BPAY_REFERENCE == null;
case 9: // CREATION_DATE
return Current.CREATION_DATE == null;
case 10: // LW_TIME
return Current.LW_TIME == null;
case 11: // LW_DATE
return Current.LW_DATE == null;
case 12: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // ID
return "ID";
case 1: // LEDGER
return "LEDGER";
case 2: // ENTITY
return "ENTITY";
case 3: // TRANSACTION_ID
return "TRANSACTION_ID";
case 4: // BSB
return "BSB";
case 5: // ACCOUNT_NO
return "ACCOUNT_NO";
case 6: // ACCOUNT_NAME
return "ACCOUNT_NAME";
case 7: // BILLER_CODE
return "BILLER_CODE";
case 8: // BPAY_REFERENCE
return "BPAY_REFERENCE";
case 9: // CREATION_DATE
return "CREATION_DATE";
case 10: // LW_TIME
return "LW_TIME";
case 11: // LW_DATE
return "LW_DATE";
case 12: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "ID":
return 0;
case "LEDGER":
return 1;
case "ENTITY":
return 2;
case "TRANSACTION_ID":
return 3;
case "BSB":
return 4;
case "ACCOUNT_NO":
return 5;
case "ACCOUNT_NAME":
return 6;
case "BILLER_CODE":
return 7;
case "BPAY_REFERENCE":
return 8;
case "CREATION_DATE":
return 9;
case "LW_TIME":
return 10;
case "LW_DATE":
return 11;
case "LW_USER":
return 12;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareEqualUInt64()
{
var test = new SimpleBinaryOpTest__CompareEqualUInt64();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareEqualUInt64
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(UInt64);
private const int Op2ElementCount = VectorSize / sizeof(UInt64);
private const int RetElementCount = VectorSize / sizeof(UInt64);
private static UInt64[] _data1 = new UInt64[Op1ElementCount];
private static UInt64[] _data2 = new UInt64[Op2ElementCount];
private static Vector128<UInt64> _clsVar1;
private static Vector128<UInt64> _clsVar2;
private Vector128<UInt64> _fld1;
private Vector128<UInt64> _fld2;
private SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64> _dataTable;
static SimpleBinaryOpTest__CompareEqualUInt64()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareEqualUInt64()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld1), ref Unsafe.As<UInt64, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld2), ref Unsafe.As<UInt64, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (ulong)(random.Next(0, int.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (ulong)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt64, UInt64, UInt64>(_data1, _data2, new UInt64[RetElementCount], VectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse41.CompareEqual(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse41.CompareEqual(
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse41.CompareEqual(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<UInt64>), typeof(Vector128<UInt64>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse41.CompareEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArray2Ptr);
var result = Sse41.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArray2Ptr));
var result = Sse41.CompareEqual(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareEqualUInt64();
var result = Sse41.CompareEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse41.CompareEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> left, Vector128<UInt64> right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray1 = new UInt64[Op1ElementCount];
UInt64[] inArray2 = new UInt64[Op2ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt64[] left, UInt64[] right, UInt64[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] == right[0]) ? unchecked((ulong)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] == right[i]) ? unchecked((ulong)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.CompareEqual)}<UInt64>(Vector128<UInt64>, Vector128<UInt64>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// WARNING
//
// This file has been generated automatically by Xamarin Studio from the outlets and
// actions declared in your storyboard file.
// Manual changes to this file will not be maintained.
//
using Foundation;
using System;
using System.CodeDom.Compiler;
using UIKit;
namespace Shopping.DemoApp.iOS
{
[Register ("ProfileController")]
partial class ProfileController
{
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel labelFullname { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel labelLoaitaikhoan { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbDienthoai { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbEmail { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbFullname { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbGioitinh { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbLoaitaikhoan { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbMagioithieu { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbNgaysinh { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UILabel lbNgaythamgia { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxDienthoai { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIButton uxEditProfile { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxEmail { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxFullname { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxGioitinh { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UIImageView uxImageview { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxLoaitaikhoan { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxMagioithieu { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxNgaysinh { get; set; }
[Outlet]
[GeneratedCode ("iOS Designer", "1.0")]
UIKit.UITextField uxNgaythamgia { get; set; }
[Action ("UxEditProfile_TouchUpInside:")]
[GeneratedCode ("iOS Designer", "1.0")]
partial void UxEditProfile_TouchUpInside (UIKit.UIButton sender);
void ReleaseDesignerOutlets ()
{
if (labelFullname != null) {
labelFullname.Dispose ();
labelFullname = null;
}
if (labelLoaitaikhoan != null) {
labelLoaitaikhoan.Dispose ();
labelLoaitaikhoan = null;
}
if (lbDienthoai != null) {
lbDienthoai.Dispose ();
lbDienthoai = null;
}
if (lbEmail != null) {
lbEmail.Dispose ();
lbEmail = null;
}
if (lbFullname != null) {
lbFullname.Dispose ();
lbFullname = null;
}
if (lbGioitinh != null) {
lbGioitinh.Dispose ();
lbGioitinh = null;
}
if (lbLoaitaikhoan != null) {
lbLoaitaikhoan.Dispose ();
lbLoaitaikhoan = null;
}
if (lbMagioithieu != null) {
lbMagioithieu.Dispose ();
lbMagioithieu = null;
}
if (lbNgaysinh != null) {
lbNgaysinh.Dispose ();
lbNgaysinh = null;
}
if (lbNgaythamgia != null) {
lbNgaythamgia.Dispose ();
lbNgaythamgia = null;
}
if (uxDienthoai != null) {
uxDienthoai.Dispose ();
uxDienthoai = null;
}
if (uxEditProfile != null) {
uxEditProfile.Dispose ();
uxEditProfile = null;
}
if (uxEmail != null) {
uxEmail.Dispose ();
uxEmail = null;
}
if (uxFullname != null) {
uxFullname.Dispose ();
uxFullname = null;
}
if (uxGioitinh != null) {
uxGioitinh.Dispose ();
uxGioitinh = null;
}
if (uxImageview != null) {
uxImageview.Dispose ();
uxImageview = null;
}
if (uxLoaitaikhoan != null) {
uxLoaitaikhoan.Dispose ();
uxLoaitaikhoan = null;
}
if (uxMagioithieu != null) {
uxMagioithieu.Dispose ();
uxMagioithieu = null;
}
if (uxNgaysinh != null) {
uxNgaysinh.Dispose ();
uxNgaysinh = null;
}
if (uxNgaythamgia != null) {
uxNgaythamgia.Dispose ();
uxNgaythamgia = null;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.UnitTests;
using Moq;
using Xunit;
namespace Avalonia.Styling.UnitTests
{
public class StyleTests
{
[Fact]
public void Style_With_Only_Type_Selector_Should_Update_Value()
{
Style style = new Style(x => x.OfType<Class1>())
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
};
var target = new Class1();
style.TryAttach(target, null);
Assert.Equal("Foo", target.Foo);
}
[Fact]
public void Style_With_Class_Selector_Should_Update_And_Restore_Value()
{
Style style = new Style(x => x.OfType<Class1>().Class("foo"))
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
};
var target = new Class1();
style.TryAttach(target, null);
Assert.Equal("foodefault", target.Foo);
target.Classes.Add("foo");
Assert.Equal("Foo", target.Foo);
target.Classes.Remove("foo");
Assert.Equal("foodefault", target.Foo);
}
[Fact]
public void Style_With_No_Selector_Should_Apply_To_Containing_Control()
{
Style style = new Style
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
};
var target = new Class1();
style.TryAttach(target, target);
Assert.Equal("Foo", target.Foo);
}
[Fact]
public void Style_With_No_Selector_Should_Not_Apply_To_Other_Control()
{
Style style = new Style
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
};
var target = new Class1();
var other = new Class1();
style.TryAttach(target, other);
Assert.Equal("foodefault", target.Foo);
}
[Fact]
public void LocalValue_Should_Override_Style()
{
Style style = new Style(x => x.OfType<Class1>())
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
};
var target = new Class1
{
Foo = "Original",
};
style.TryAttach(target, null);
Assert.Equal("Original", target.Foo);
}
[Fact]
public void Later_Styles_Should_Override_Earlier()
{
Styles styles = new Styles
{
new Style(x => x.OfType<Class1>().Class("foo"))
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
},
new Style(x => x.OfType<Class1>().Class("foo"))
{
Setters =
{
new Setter(Class1.FooProperty, "Bar"),
},
}
};
var target = new Class1();
List<string> values = new List<string>();
target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
styles.TryAttach(target, null);
target.Classes.Add("foo");
target.Classes.Remove("foo");
Assert.Equal(new[] { "foodefault", "Foo", "Bar", "foodefault" }, values);
}
[Fact]
public void Later_Styles_Should_Override_Earlier_2()
{
Styles styles = new Styles
{
new Style(x => x.OfType<Class1>().Class("foo"))
{
Setters =
{
new Setter(Class1.FooProperty, "Foo"),
},
},
new Style(x => x.OfType<Class1>().Class("bar"))
{
Setters =
{
new Setter(Class1.FooProperty, "Bar"),
},
}
};
var target = new Class1();
List<string> values = new List<string>();
target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
styles.TryAttach(target, null);
target.Classes.Add("bar");
target.Classes.Add("foo");
target.Classes.Remove("foo");
Assert.Equal(new[] { "foodefault", "Bar" }, values);
}
[Fact]
public void Later_Styles_Should_Override_Earlier_3()
{
Styles styles = new Styles
{
new Style(x => x.OfType<Class1>().Class("foo"))
{
Setters =
{
new Setter(Class1.FooProperty, new Binding("Foo")),
},
},
new Style(x => x.OfType<Class1>().Class("bar"))
{
Setters =
{
new Setter(Class1.FooProperty, new Binding("Bar")),
},
}
};
var target = new Class1
{
DataContext = new
{
Foo = "Foo",
Bar = "Bar",
}
};
List<string> values = new List<string>();
target.GetObservable(Class1.FooProperty).Subscribe(x => values.Add(x));
styles.TryAttach(target, null);
target.Classes.Add("bar");
target.Classes.Add("foo");
target.Classes.Remove("foo");
Assert.Equal(new[] { "foodefault", "Bar" }, values);
}
[Fact]
public void Style_Should_Detach_When_Control_Removed_From_Logical_Tree()
{
Border border;
var style = new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
};
var root = new TestRoot
{
Child = border = new Border(),
};
style.TryAttach(border, null);
Assert.Equal(new Thickness(4), border.BorderThickness);
root.Child = null;
Assert.Equal(new Thickness(0), border.BorderThickness);
}
[Fact]
public void Removing_Style_Should_Detach_From_Control()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var border = new Border();
var root = new TestRoot
{
Styles =
{
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
}
},
Child = border,
};
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(4), border.BorderThickness);
root.Styles.RemoveAt(0);
Assert.Equal(new Thickness(0), border.BorderThickness);
}
}
[Fact]
public void Adding_Style_Should_Attach_To_Control()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var border = new Border();
var root = new TestRoot
{
Styles =
{
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
}
},
Child = border,
};
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(4), border.BorderThickness);
root.Styles.Add(new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(6)),
}
});
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(6), border.BorderThickness);
}
}
[Fact]
public void Removing_Style_With_Nested_Style_Should_Detach_From_Control()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var border = new Border();
var root = new TestRoot
{
Styles =
{
new Styles
{
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
}
}
},
Child = border,
};
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(4), border.BorderThickness);
root.Styles.RemoveAt(0);
Assert.Equal(new Thickness(0), border.BorderThickness);
}
}
[Fact]
public void Adding_Nested_Style_Should_Attach_To_Control()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var border = new Border();
var root = new TestRoot
{
Styles =
{
new Styles
{
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
}
}
},
Child = border,
};
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(4), border.BorderThickness);
((Styles)root.Styles[0]).Add(new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(6)),
}
});
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(6), border.BorderThickness);
}
}
[Fact]
public void Removing_Nested_Style_Should_Detach_From_Control()
{
using (UnitTestApplication.Start(TestServices.RealStyler))
{
var border = new Border();
var root = new TestRoot
{
Styles =
{
new Styles
{
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(4)),
}
},
new Style(x => x.OfType<Border>())
{
Setters =
{
new Setter(Border.BorderThicknessProperty, new Thickness(6)),
}
},
}
},
Child = border,
};
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(6), border.BorderThickness);
((Styles)root.Styles[0]).RemoveAt(1);
root.Measure(Size.Infinity);
Assert.Equal(new Thickness(4), border.BorderThickness);
}
}
[Fact]
public void Should_Set_Owner_On_Assigned_Resources()
{
var host = new Mock<IResourceHost>();
var target = new Style();
((IResourceProvider)target).AddOwner(host.Object);
var resources = new Mock<IResourceDictionary>();
target.Resources = resources.Object;
resources.Verify(x => x.AddOwner(host.Object), Times.Once);
}
[Fact]
public void Should_Set_Owner_On_Assigned_Resources_2()
{
var host = new Mock<IResourceHost>();
var target = new Style();
var resources = new Mock<IResourceDictionary>();
target.Resources = resources.Object;
host.Invocations.Clear();
((IResourceProvider)target).AddOwner(host.Object);
resources.Verify(x => x.AddOwner(host.Object), Times.Once);
}
private class Class1 : Control
{
public static readonly StyledProperty<string> FooProperty =
AvaloniaProperty.Register<Class1, string>(nameof(Foo), "foodefault");
public string Foo
{
get { return GetValue(FooProperty); }
set { SetValue(FooProperty, value); }
}
protected override Size MeasureOverride(Size availableSize)
{
throw new NotImplementedException();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class AverageTests
{
//
// Average
//
// Get a set of ranges from 0 to each count, with an extra parameter containing the expected average.
public static IEnumerable<object[]> AverageData(int[] counts)
{
foreach (int count in counts)
{
yield return new object[] { count, (count - 1) / 2.0 };
}
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (int?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(int?)x));
}
[Fact]
[OuterLoop]
public static void Average_Int_Longrunning()
{
Average_Int(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (int?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int_AllNull(int count, double average)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (int?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (int?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (long)x).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (long?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(long)x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(long?)x));
}
[Fact]
[OuterLoop]
public static void Average_Long_Longrunning()
{
Average_Long(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Fact]
public static void Average_Long_Overflow()
{
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Select(x => x == 0 ? 1 : long.MaxValue).Average());
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Select(x => x == 0 ? (long?)1 : long.MaxValue).Average());
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Average(x => x == 0 ? -1 : long.MinValue));
AssertThrows.Wrapped<OverflowException>(() => UnorderedSources.Default(2).Average(x => x == 0 ? (long?)-1 : long.MinValue));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (long?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(long?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Long_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (long?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (long?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float(int count, float average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (float)x).Average());
Assert.Equal((float?)average, UnorderedSources.Default(count).Select(x => (float?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(float)x));
Assert.Equal(-(float?)average, UnorderedSources.Default(count).Average(x => -(float?)x));
}
[Fact]
[OuterLoop]
public static void Average_Float_Longrunning()
{
Average_Float(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0F);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float_SomeNull(int count, float average)
{
Assert.Equal((float?)Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (float?)x : null).Average());
Assert.Equal((float?)Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(float?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Float_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (float?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (float?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double(int count, double average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (double)x).Average());
Assert.Equal((double?)average, UnorderedSources.Default(count).Select(x => (double?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(double)x));
Assert.Equal(-(double?)average, UnorderedSources.Default(count).Average(x => -(double?)x));
}
[Fact]
[OuterLoop]
public static void Average_Double_Longrunning()
{
Average_Double(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double_SomeNull(int count, double average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (double?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(double?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Double_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (double?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (double?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal(int count, decimal average)
{
Assert.Equal(average, UnorderedSources.Default(count).Select(x => (decimal)x).Average());
Assert.Equal((decimal?)average, UnorderedSources.Default(count).Select(x => (decimal?)x).Average());
Assert.Equal(-average, UnorderedSources.Default(count).Average(x => -(decimal)x));
Assert.Equal(-(decimal?)average, UnorderedSources.Default(count).Average(x => -(decimal?)x));
}
[Fact]
[OuterLoop]
public static void Average_Decimal_Longrunning()
{
Average_Decimal(Sources.OuterLoopCount, (Sources.OuterLoopCount - 1) / 2.0M);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal_SomeNull(int count, decimal average)
{
Assert.Equal(Math.Truncate(average), UnorderedSources.Default(count).Select(x => (x % 2 == 0) ? (decimal?)x : null).Average());
Assert.Equal(Math.Truncate(-average), UnorderedSources.Default(count).Average(x => (x % 2 == 0) ? -(decimal?)x : null));
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(16)]
public static void Average_Decimal_AllNull(int count)
{
Assert.Null(UnorderedSources.Default(count).Select(x => (decimal?)null).Average());
Assert.Null(UnorderedSources.Default(count).Average(x => (decimal?)null));
}
[Fact]
public static void Average_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average(x => x));
// Nullables return null when empty
Assert.Null(ParallelEnumerable.Empty<int?>().Average());
Assert.Null(ParallelEnumerable.Empty<int?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<long?>().Average());
Assert.Null(ParallelEnumerable.Empty<long?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<float?>().Average());
Assert.Null(ParallelEnumerable.Empty<float?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<double?>().Average());
Assert.Null(ParallelEnumerable.Empty<double?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average());
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average(x => x));
}
[Fact]
public static void Average_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.EventuallyCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Average_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.OtherTokenCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (int?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (long)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (long?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (float)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (float?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (double)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (double?)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal)x; }));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.Average(x => { canceler(); return (decimal?)x; }));
}
[Fact]
public static void Average_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.Average(x => x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (int?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (long)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (long?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (float)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (float?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (double)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (double?)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (decimal)x));
AssertThrows.AlreadyCanceled(source => source.Average(x => (decimal?)x));
}
[Fact]
public static void Average_AggregateException()
{
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, int>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, long>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, float>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, double>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
AssertThrows.Wrapped<DeliberateTestException>(() => UnorderedSources.Default(1).Average((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Average_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat(0, 1).Average((Func<int, int>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<int?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((int?)0, 1).Average((Func<int?, int?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long)0, 1).Average((Func<long, long>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<long?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((long?)0, 1).Average((Func<long?, long?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float)0, 1).Average((Func<float, float>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<float?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((float?)0, 1).Average((Func<float?, float?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double)0, 1).Average((Func<double, double>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<double?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((double?)0, 1).Average((Func<double?, double?>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal)0, 1).Average((Func<decimal, decimal>)null));
AssertExtensions.Throws<ArgumentNullException>("source", () => ((ParallelQuery<decimal?>)null).Average());
AssertExtensions.Throws<ArgumentNullException>("selector", () => ParallelEnumerable.Repeat((decimal?)0, 1).Average((Func<decimal?, decimal?>)null));
}
}
}
| |
// 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 Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using System.Reflection.PortableExecutable;
using Microsoft.CodeAnalysis.Emit;
namespace Microsoft.Cci
{
/// <summary>
/// Represents a .NET assembly.
/// </summary>
internal interface IAssembly : IModule, IAssemblyReference
{
/// <summary>
/// A list of the files that constitute the assembly. These are not the source language files that may have been
/// used to compile the assembly, but the files that contain constituent modules of a multi-module assembly as well
/// as any external resources. It corresponds to the File table of the .NET assembly file format.
/// </summary>
IEnumerable<IFileReference> GetFiles(EmitContext context);
/// <summary>
/// A set of bits and bit ranges representing properties of the assembly. The value of <see cref="Flags"/> can be set
/// from source code via the AssemblyFlags assembly custom attribute. The interpretation of the property depends on the target platform.
/// </summary>
uint Flags { get; }
/// <summary>
/// The public part of the key used to encrypt the SHA1 hash over the persisted form of this assembly. Empty or null if not specified.
/// This value is used by the loader to decrypt an encrypted hash value stored in the assembly, which it then compares with a freshly computed hash value
/// in order to verify the integrity of the assembly.
/// </summary>
ImmutableArray<byte> PublicKey { get; }
/// <summary>
/// The contents of the AssemblySignatureKeyAttribute
/// </summary>
string SignatureKey { get; }
AssemblyHashAlgorithm HashAlgorithm { get; }
}
/// <summary>
/// A reference to a .NET assembly.
/// </summary>
internal interface IAssemblyReference : IModuleReference
{
/// <summary>
/// Identifies the culture associated with the assembly reference. Typically specified for satellite assemblies with localized resources.
/// Empty if not specified.
/// </summary>
string Culture { get; }
/// <summary>
/// True if the implementation of the referenced assembly used at runtime is not expected to match the version seen at compile time.
/// </summary>
bool IsRetargetable { get; }
/// <summary>
/// Type of code contained in an assembly. Determines assembly binding model.
/// </summary>
AssemblyContentType ContentType { get; }
/// <summary>
/// The hashed 8 bytes of the public key of the referenced assembly.
/// Empty if the referenced assembly does not have a public key.
/// </summary>
ImmutableArray<byte> PublicKeyToken { get; }
/// <summary>
/// The version of the assembly reference.
/// </summary>
Version Version { get; }
string GetDisplayName();
}
/// <summary>
/// An object that represents a .NET module.
/// </summary>
internal interface IModule : IUnit, IModuleReference
{
ModulePropertiesForSerialization Properties { get; }
/// <summary>
/// Used to distinguish which style to pick while writing native PDB information.
/// </summary>
/// <remarks>
/// The PDB content for custom debug information is different between Visual Basic and CSharp.
/// E.g. C# always includes a CustomMetadata Header (MD2) that contains the namespace scope counts, where
/// as VB only outputs namespace imports into the namespace scopes.
/// C# defines forwards in that header, VB includes them into the scopes list.
///
/// Currently the compiler doesn't allow mixing C# and VB method bodies. Thus this flag can be per module.
/// It is possible to move this flag to per-method basis but native PDB CDI forwarding would need to be adjusted accordingly.
/// </remarks>
bool GenerateVisualBasicStylePdb { get; }
/// <summary>
/// Public types defined in other modules making up this assembly and to which other assemblies may refer to via this assembly.
/// </summary>
IEnumerable<ITypeReference> GetExportedTypes(EmitContext context);
/// <summary>
/// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
/// with this assembly.
/// </summary>
IEnumerable<ICustomAttribute> AssemblyAttributes { get; }
/// <summary>
/// A list of objects representing persisted instances of pairs of security actions and sets of security permissions.
/// These apply by default to every method reachable from the module.
/// </summary>
IEnumerable<SecurityAttribute> AssemblySecurityAttributes { get; }
/// <summary>
/// A list of the assemblies that are referenced by this module.
/// </summary>
IEnumerable<IAssemblyReference> GetAssemblyReferences(EmitContext context);
/// <summary>
/// A list of named byte sequences persisted with the assembly and used during execution, typically via .NET Framework helper classes.
/// </summary>
IEnumerable<ManagedResource> GetResources(EmitContext context);
/// <summary>
/// CorLibrary assembly referenced by this module.
/// </summary>
IAssemblyReference GetCorLibrary(EmitContext context);
/// <summary>
/// The Assembly that contains this module. If this module is main module then this returns this.
/// </summary>
new IAssembly GetContainingAssembly(EmitContext context);
/// <summary>
/// The method that will be called to start execution of this executable module.
/// </summary>
IMethodReference EntryPoint
{
get;
// ^ requires this.Kind == ModuleKind.ConsoleApplication || this.Kind == ModuleKind.WindowsApplication;
}
/// <summary>
/// Returns zero or more strings used in the module. If the module is produced by reading in a CLR PE file, then this will be the contents
/// of the user string heap. If the module is produced some other way, the method may return an empty enumeration or an enumeration that is a
/// subset of the strings actually used in the module. The main purpose of this method is to provide a way to control the order of strings in a
/// prefix of the user string heap when writing out a module as a PE file.
/// </summary>
IEnumerable<string> GetStrings();
/// <summary>
/// Returns all top-level (not nested) types defined in the current module.
/// </summary>
IEnumerable<INamespaceTypeDefinition> GetTopLevelTypes(EmitContext context);
/// <summary>
/// The kind of metadata stored in this module. For example whether this module is an executable or a manifest resource file.
/// </summary>
OutputKind Kind { get; }
/// <summary>
/// A list of objects representing persisted instances of types that extend System.Attribute. Provides an extensible way to associate metadata
/// with this module.
/// </summary>
IEnumerable<ICustomAttribute> ModuleAttributes { get; }
/// <summary>
/// The name of the module.
/// </summary>
string ModuleName { get; }
/// <summary>
/// A list of the modules that are referenced by this module.
/// </summary>
IEnumerable<IModuleReference> ModuleReferences { get; }
/// <summary>
/// A list of named byte sequences persisted with the module and used during execution, typically via the Win32 API.
/// A module will define Win32 resources rather than "managed" resources mainly to present metadata to legacy tools
/// and not typically use the data in its own code.
/// </summary>
IEnumerable<IWin32Resource> Win32Resources { get; }
/// <summary>
/// An alternate form the Win32 resources may take. These represent the rsrc$01 and rsrc$02 section data and relocs
/// from a COFF object file.
/// </summary>
ResourceSection Win32ResourceSection { get; }
IAssembly AsAssembly { get; }
ITypeReference GetPlatformType(PlatformType t, EmitContext context);
bool IsPlatformType(ITypeReference typeRef, PlatformType t);
IEnumerable<IReference> ReferencesInIL(out int count);
/// <summary>
/// Builds symbol definition to location map used for emitting token -> location info
/// into PDB to be consumed by WinMdExp.exe tool (only applicable for /t:winmdobj)
/// </summary>
MultiDictionary<DebugSourceDocument, DefinitionWithLocation> GetSymbolToLocationMap();
/// <summary>
/// Assembly reference aliases (C# only).
/// </summary>
ImmutableArray<AssemblyReferenceAlias> GetAssemblyReferenceAliases(EmitContext context);
/// <summary>
/// Linked assembly names to be stored to native PDB (VB only).
/// </summary>
IEnumerable<string> LinkedAssembliesDebugInfo { get; }
/// <summary>
/// Project level imports (VB only, TODO: C# scripts).
/// </summary>
ImmutableArray<UsedNamespaceOrType> GetImports();
/// <summary>
/// Default namespace (VB only).
/// </summary>
string DefaultNamespace { get; }
// An approximate number of method definitions that can
// provide a basis for approximating the capacities of
// various databases used during Emit.
int HintNumberOfMethodDefinitions { get; }
}
internal struct DefinitionWithLocation
{
public readonly IDefinition Definition;
public readonly uint StartLine;
public readonly uint StartColumn;
public readonly uint EndLine;
public readonly uint EndColumn;
public DefinitionWithLocation(IDefinition definition,
int startLine, int startColumn, int endLine, int endColumn)
{
Debug.Assert(startLine >= 0);
Debug.Assert(startColumn >= 0);
Debug.Assert(endLine >= 0);
Debug.Assert(endColumn >= 0);
this.Definition = definition;
this.StartLine = (uint)startLine;
this.StartColumn = (uint)startColumn;
this.EndLine = (uint)endLine;
this.EndColumn = (uint)endColumn;
}
public override string ToString()
{
return string.Format(
"{0} => start:{1}/{2}, end:{3}/{4}",
this.Definition.ToString(),
this.StartLine.ToString(), this.StartColumn.ToString(),
this.EndLine.ToString(), this.EndColumn.ToString());
}
}
/// <summary>
/// A reference to a .NET module.
/// </summary>
internal interface IModuleReference : IUnitReference
{
/// <summary>
/// The Assembly that contains this module. May be null if the module is not part of an assembly.
/// </summary>
IAssemblyReference GetContainingAssembly(EmitContext context);
}
/// <summary>
/// A unit of metadata stored as a single artifact and potentially produced and revised independently from other units.
/// Examples of units include .NET assemblies and modules, as well C++ object files and compiled headers.
/// </summary>
internal interface IUnit : IUnitReference, IDefinition
{
}
/// <summary>
/// A reference to a instance of <see cref="IUnit"/>.
/// </summary>
internal interface IUnitReference : IReference, INamedEntity
{
}
}
| |
// ************************ ParseDoubleQuotes : char ************************
//
// group newline = { '\n', '\r' }
// ParseDoubleQuote : newline = decline, '"' = accept, '\\' = EscapedChar,
// default = ParseDoubleQuote;
// EscapedChar : newline = decline, default = ParseDoubleQuote;
//
//
// This file was automatically generated from a tool that converted the
// above state machine definition into this state machine class.
// Any changes to this code will be replaced the next time the code is generated.
using System;
using System.Collections.Generic;
namespace test
{
public class ParseDoubleQuotes
{
public enum States
{
ParseDoubleQuote = 0, EscapedChar = 1,
}
private States? state = null;
public States? CurrentState { get { return state; } }
private char currentCommand;
public char CurrentCommand { get { return currentCommand; } }
private bool reset = false;
private Action<char> onParseDoubleQuoteState = null;
private Action<char> onParseDoubleQuoteEnter = null;
private Action<char> onParseDoubleQuoteExit = null;
private Action<char> onEscapedCharState = null;
private Action<char> onEscapedCharEnter = null;
private Action<char> onEscapedCharExit = null;
private Action<char> onAccept = null;
private Action<char> onDecline = null;
private Action<char> onEnd = null;
public bool? Input(Queue<char> data)
{
if (reset)
state = null;
bool? result = null;
if (data == null)
return null;
Reset:
reset = false;
switch (state)
{
case null:
if (data.Count > 0)
{
state = States.ParseDoubleQuote;
goto ResumeParseDoubleQuote;
}
else
goto End;
case States.ParseDoubleQuote:
goto ResumeParseDoubleQuote;
case States.EscapedChar:
goto ResumeEscapedChar;
}
EnterParseDoubleQuote:
state = States.ParseDoubleQuote;
if (onParseDoubleQuoteEnter != null)
onParseDoubleQuoteEnter(currentCommand);
ParseDoubleQuote:
if (onParseDoubleQuoteState != null)
onParseDoubleQuoteState(currentCommand);
ResumeParseDoubleQuote:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\n':
if (onParseDoubleQuoteExit != null)
onParseDoubleQuoteExit(currentCommand);
goto Decline;
case '\r':
if (onParseDoubleQuoteExit != null)
onParseDoubleQuoteExit(currentCommand);
goto Decline;
case '"':
if (onParseDoubleQuoteExit != null)
onParseDoubleQuoteExit(currentCommand);
goto Accept;
case '\\':
if (onParseDoubleQuoteExit != null)
onParseDoubleQuoteExit(currentCommand);
goto EnterEscapedChar;
default:
goto ParseDoubleQuote;
}
EnterEscapedChar:
state = States.EscapedChar;
if (onEscapedCharEnter != null)
onEscapedCharEnter(currentCommand);
if (onEscapedCharState != null)
onEscapedCharState(currentCommand);
ResumeEscapedChar:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\n':
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto Decline;
case '\r':
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto Decline;
default:
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto EnterParseDoubleQuote;
}
Accept:
result = true;
state = null;
if (onAccept != null)
onAccept(currentCommand);
goto End;
Decline:
result = false;
state = null;
if (onDecline != null)
onDecline(currentCommand);
goto End;
End:
if (onEnd != null)
onEnd(currentCommand);
if (reset)
{
goto Reset;
}
return result;
}
public void AddOnParseDoubleQuote(Action<char> addedFunc)
{
onParseDoubleQuoteState += addedFunc;
}
public void AddOnEscapedChar(Action<char> addedFunc)
{
onEscapedCharState += addedFunc;
}
public void AddOnParseDoubleQuoteEnter(Action<char> addedFunc)
{
onParseDoubleQuoteEnter += addedFunc;
}
public void AddOnEscapedCharEnter(Action<char> addedFunc)
{
onEscapedCharEnter += addedFunc;
}
public void AddOnParseDoubleQuoteExit(Action<char> addedFunc)
{
onParseDoubleQuoteExit += addedFunc;
}
public void AddOnEscapedCharExit(Action<char> addedFunc)
{
onEscapedCharExit += addedFunc;
}
public void AddOnAccept(Action<char> addedFunc)
{
onAccept += addedFunc;
}
public void AddOnDecline(Action<char> addedFunc)
{
onDecline += addedFunc;
}
public void AddOnEnd(Action<char> addedFunc)
{
onEnd += addedFunc;
}
internal void addOnAllStates( Action<char> addedFunc )
{
onParseDoubleQuoteState += addedFunc;
onEscapedCharState += addedFunc;
}
public void ResetStateOnEnd()
{
state = null;
reset = true;
}
}
}
| |
// SET request message type.
// Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Globalization;
using Snmp.Core.Security;
namespace Snmp.Core.Messaging
{
/// <summary>
/// SET request message.
/// </summary>
public sealed class SetRequestMessage : ISnmpMessage
{
private readonly byte[] _bytes;
/// <summary>
/// Creates a <see cref="SetRequestMessage"/> with all contents.
/// </summary>
/// <param name="requestId">The request id.</param>
/// <param name="version">Protocol version</param>
/// <param name="community">Community name</param>
/// <param name="variables">Variables</param>
public SetRequestMessage(int requestId, VersionCode version, OctetString community, IList<Variable> variables)
{
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (community == null)
{
throw new ArgumentNullException("community");
}
if (version == VersionCode.V3)
{
throw new ArgumentException("only v1 and v2c are supported", "version");
}
Version = version;
Header = Header.Empty;
Parameters = SecurityParameters.Create(community);
var pdu = new SetRequestPdu(
requestId,
variables);
Scope = new Scope(pdu);
Privacy = DefaultPrivacyProvider.DefaultPair;
_bytes = this.PackMessage(null).ToBytes();
}
/// <summary>
/// Initializes a new instance of the <see cref="SetRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="report">The report.</param>
[Obsolete("Please use other overloading ones.")]
public SetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList<Variable> variables, IPrivacyProvider privacy, ISnmpMessage report)
: this(version, messageId, requestId, userName, variables, privacy, 0xFFE3, report)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SetRequestMessage"/> class.
/// </summary>
/// <param name="version">The version.</param>
/// <param name="messageId">The message id.</param>
/// <param name="requestId">The request id.</param>
/// <param name="userName">Name of the user.</param>
/// <param name="variables">The variables.</param>
/// <param name="privacy">The privacy provider.</param>
/// <param name="maxMessageSize">Size of the max message.</param>
/// <param name="report">The report.</param>
public SetRequestMessage(VersionCode version, int messageId, int requestId, OctetString userName, IList<Variable> variables, IPrivacyProvider privacy, int maxMessageSize, ISnmpMessage report)
{
if (variables == null)
{
throw new ArgumentNullException("variables");
}
if (userName == null)
{
throw new ArgumentNullException("userName");
}
if (version != VersionCode.V3)
{
throw new ArgumentException("only v3 is supported", "version");
}
if (report == null)
{
throw new ArgumentNullException("report");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Privacy = privacy;
Header = new Header(new Integer32(messageId), new Integer32(maxMessageSize), privacy.ToSecurityLevel() | Levels.Reportable);
var parameters = report.Parameters;
var authenticationProvider = Privacy.AuthenticationProvider;
Parameters = new SecurityParameters(
parameters.EngineId,
parameters.EngineBoots,
parameters.EngineTime,
userName,
authenticationProvider.CleanDigest,
Privacy.Salt);
var pdu = new SetRequestPdu(
requestId,
variables);
var scope = report.Scope;
var contextEngineId = scope.ContextEngineId == OctetString.Empty ? parameters.EngineId : scope.ContextEngineId;
Scope = new Scope(contextEngineId, scope.ContextName, pdu);
Privacy.ComputeHash(Version, Header, Parameters, Scope);
_bytes = this.PackMessage(null).ToBytes();
}
internal SetRequestMessage(VersionCode version, Header header, SecurityParameters parameters, Scope scope, IPrivacyProvider privacy, byte[] length)
{
if (scope == null)
{
throw new ArgumentNullException("scope");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (header == null)
{
throw new ArgumentNullException("header");
}
if (privacy == null)
{
throw new ArgumentNullException("privacy");
}
Version = version;
Header = header;
Parameters = parameters;
Scope = scope;
Privacy = privacy;
_bytes = this.PackMessage(length).ToBytes();
}
/// <summary>
/// Gets the header.
/// </summary>
public Header Header { get; private set; }
/// <summary>
/// Gets the privacy provider.
/// </summary>
/// <value>The privacy provider.</value>
public IPrivacyProvider Privacy { get; private set; }
/// <summary>
/// Returns a <see cref="string"/> that represents this <see cref="SetRequestMessage"/>.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "SET request message: version: {0}; {1}; {2}", Version, Parameters.UserName, Scope.Pdu);
}
/// <summary>
/// Converts to byte format.
/// </summary>
/// <returns></returns>
public byte[] ToBytes()
{
return _bytes;
}
/// <summary>
/// Gets the parameters.
/// </summary>
/// <value>The parameters.</value>
public SecurityParameters Parameters { get; private set; }
/// <summary>
/// Gets the scope.
/// </summary>
/// <value>The scope.</value>
public Scope Scope { get; private set; }
/// <summary>
/// Gets the version.
/// </summary>
/// <value>The version.</value>
public VersionCode Version { get; private set; }
}
}
| |
// ============================================================================
// FileName: NATKeepAliveRelay.cs
//
// Description:
// A socket that listens for agents that wish to send NAT keepalives to clients and relays the
// request from a specified socket.
//
// Author(s):
// Aaron Clauson
//
// License:
// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php
//
// Copyright (c) 2007 Aaron Clauson ([email protected]), Blue Face Ltd, Dublin, Ireland (www.blueface.ie)
// 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 Blue Face Ltd.
// nor the names of its contributors may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using log4net;
using SIPSorcery.SIP;
using SIPSorcery.SIP.App;
#if UNITTEST
using NUnit.Framework;
#endif
namespace SIPSorcery.Servers
{
public delegate void SendNATKeepAliveDelegate(NATKeepAliveMessage keepAliveMessage);
public class NATKeepAliveMessage
{
public SIPEndPoint LocalSIPEndPoint;
public IPEndPoint RemoteEndPoint;
private NATKeepAliveMessage()
{ }
public NATKeepAliveMessage(SIPEndPoint localSIPEndPoint, IPEndPoint remoteEndPoint)
{
LocalSIPEndPoint = localSIPEndPoint;
RemoteEndPoint = remoteEndPoint;
}
public static NATKeepAliveMessage ParseNATKeepAliveMessage(byte[] buffer)
{
if (buffer != null && buffer.Length == 20)
{
byte[] sendToAddrBuffer = new byte[4];
Buffer.BlockCopy(buffer, 0, sendToAddrBuffer, 0, 4);
IPAddress sendToAddress = new IPAddress(sendToAddrBuffer);
int sendToPort = BitConverter.ToInt32(buffer, 4);
int proxyProtocol = BitConverter.ToInt32(buffer, 8);
byte[] proxyFromAddrBuffer = new byte[4];
Buffer.BlockCopy(buffer, 12, proxyFromAddrBuffer, 0, 4);
int sendFromPort = BitConverter.ToInt32(buffer, 16);
SIPEndPoint proxySendFrom = new SIPEndPoint((SIPProtocolsEnum)proxyProtocol, new IPEndPoint(new IPAddress(proxyFromAddrBuffer), sendFromPort));
//SIPProtocolsEnum protocol = SIPProtocolsType.GetProtocolTypeFromId(BitConverter.ToInt32(buffer, 16));
//SIPProtocolsEnum protocol = SIPProtocolsEnum.udp;
NATKeepAliveMessage natKeepAliveMsg = new NATKeepAliveMessage(proxySendFrom, new IPEndPoint(sendToAddress, sendToPort));
return natKeepAliveMsg;
}
else
{
return null;
}
}
public byte[] ToBuffer()
{
if (RemoteEndPoint != null && LocalSIPEndPoint != null)
{
//byte[] buffer = new byte[20];
byte[] buffer = new byte[20];
Buffer.BlockCopy(RemoteEndPoint.Address.GetAddressBytes(), 0, buffer, 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(RemoteEndPoint.Port), 0, buffer, 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes((int)LocalSIPEndPoint.Protocol), 0, buffer, 8, 4);
Buffer.BlockCopy(LocalSIPEndPoint.Address.GetAddressBytes(), 0, buffer, 12, 4);
Buffer.BlockCopy(BitConverter.GetBytes(LocalSIPEndPoint.Port), 0, buffer, 16, 4);
return buffer;
}
else
{
return null;
}
}
#region Unit testing.
#if UNITTEST
[TestFixture]
public class NATKeepAliveMessageUnitTest
{
[TestFixtureSetUp]
public void Init()
{
}
[TestFixtureTearDown]
public void Dispose()
{
}
[Test]
public void SampleTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
Assert.IsTrue(true, "True was false.");
}
[Test]
public void ReverseMessageTest()
{
Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name);
string sendToAddress = "192.168.1.1";
int sendToPort = 3455;
string sendFromAddress = "192.168.1.2";
int sendFromPort = 3244;
NATKeepAliveMessage keepAliveMsg = new NATKeepAliveMessage(SIPEndPoint.ParseSIPEndPoint(sendToAddress + ":" + sendToPort), new IPEndPoint(IPAddress.Parse(sendFromAddress), sendFromPort));
byte[] buffer = keepAliveMsg.ToBuffer();
Assert.IsTrue(buffer != null && buffer.Length == 20, "The byte buffer produced for the NATKeepAliveMessage is invalid.");
NATKeepAliveMessage rtnMsg = NATKeepAliveMessage.ParseNATKeepAliveMessage(buffer);
Assert.IsNotNull(rtnMsg, "The NATKeepAliveMessage could not be parsed from the buffer.");
Assert.IsTrue(rtnMsg.RemoteEndPoint.ToString() == keepAliveMsg.RemoteEndPoint.ToString(), "The sent and returned sendto sockets were different.");
Assert.IsTrue(rtnMsg.LocalSIPEndPoint.ToString() == keepAliveMsg.LocalSIPEndPoint.ToString(), "The sent and returned sendfrom sockets were different.");
}
}
#endif
#endregion
}
/// <summary>
/// Listens for NATKeepAlive messages on a loopback or private socket and when received actions the received messages by sending a 4 byte null payload
/// to the requested end point from the requested SIP socket. The SIP socket will be one of the sockets the application running this object owns and
/// the idea is to multiplex the zero byte payloads onto the same signalling socket to keep user end NAT's open.
/// </summary>
public class NATKeepAliveRelay
{
private ILog logger = log4net.LogManager.GetLogger("natkeepalive");
private SIPTransport m_sipTransport;
private SIPChannel m_natKeepAliveChannel; // Can use a SIP Channel for this since it's essentially just a TCP or UDP listener anyway.
private SIPMonitorLogDelegate SIPMonitorLog_External;
private byte[] m_sendBuffer = new byte[] { 0x0, 0x0, 0x0, 0x0 }; // Doesn't matter what is sent since it's just to keep the NAT connection alive.
/// <param name="listenerSocket">Socket to listen for NAT keepalive relay requests on.</param>
public NATKeepAliveRelay(SIPTransport sipTransport, IPEndPoint listenerSocket, SIPMonitorLogDelegate sipMonitorLogDelegate)
{
m_sipTransport = sipTransport;
m_natKeepAliveChannel = new SIPUDPChannel(listenerSocket);
m_natKeepAliveChannel.SIPMessageReceived += NatKeepAliveChannelMessageReceived;
SIPMonitorLog_External = sipMonitorLogDelegate;
logger.Debug("NATKeepAlive Relay instantiated on " + listenerSocket + ".");
}
public void Shutdown()
{
m_natKeepAliveChannel.Close();
}
private void NatKeepAliveChannelMessageReceived(SIPChannel sipChannel, SIPEndPoint remoteEndPoint, byte[] buffer)
{
try
{
NATKeepAliveMessage keepAliveMessage = NATKeepAliveMessage.ParseNATKeepAliveMessage(buffer);
if (keepAliveMessage != null)
{
if (keepAliveMessage.LocalSIPEndPoint.Protocol == SIPProtocolsEnum.udp)
{
FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NATKeepAlive, SIPMonitorEventTypesEnum.NATKeepAliveRelay, "Relaying NAT keep-alive from proxy socket " + keepAliveMessage.LocalSIPEndPoint + " to " + keepAliveMessage.RemoteEndPoint + ".", null));
m_sipTransport.SendRaw(keepAliveMessage.LocalSIPEndPoint, new SIPEndPoint(keepAliveMessage.RemoteEndPoint), m_sendBuffer);
}
else
{
// For connection oriented protocols check whether a connection exists. NAT keep alives shouldn't cause a connection to be initiated.
SIPChannel sendFromChannel = m_sipTransport.FindSIPChannel(keepAliveMessage.LocalSIPEndPoint);
if (sendFromChannel != null && sendFromChannel.IsConnectionEstablished(keepAliveMessage.RemoteEndPoint))
{
FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NATKeepAlive, SIPMonitorEventTypesEnum.NATKeepAliveRelay, "Relaying NAT keep-alive from proxy socket " + keepAliveMessage.LocalSIPEndPoint + " to " + keepAliveMessage.RemoteEndPoint + ".", null));
m_sipTransport.SendRaw(keepAliveMessage.LocalSIPEndPoint, new SIPEndPoint(keepAliveMessage.RemoteEndPoint), m_sendBuffer);
}
else
{
FireSIPMonitorLogEvent(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.NATKeepAlive, SIPMonitorEventTypesEnum.NATKeepAliveRelay, "No established connection was found to relay NAT keep-alive from proxy socket " + keepAliveMessage.LocalSIPEndPoint + " to " + keepAliveMessage.RemoteEndPoint + ".", null));
}
}
}
}
catch (Exception excp)
{
logger.Error("Exception NatKeepAliveChannelMessageReceived. " + excp.Message);
}
}
private void FireSIPMonitorLogEvent(SIPMonitorEvent monitorEvent)
{
if (SIPMonitorLog_External != null)
{
try
{
SIPMonitorLog_External(monitorEvent);
}
catch (Exception excp)
{
logger.Error("Exception FireProxyLogEvent NATKeepAliveRelay. " + excp.Message);
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
using osu.Game.Graphics.UserInterface;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Screens.Edit.Compose.Components.Timeline
{
public class TimelineHitObjectBlueprint : SelectionBlueprint
{
private readonly Circle circle;
[UsedImplicitly]
private readonly Bindable<double> startTime;
public Action<DragEvent> OnDragHandled;
private readonly DragBar dragBar;
private readonly List<Container> shadowComponents = new List<Container>();
private const float thickness = 5;
private const float shadow_radius = 5;
private const float circle_size = 16;
public TimelineHitObjectBlueprint(HitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
startTime = hitObject.StartTimeBindable.GetBoundCopy();
startTime.BindValueChanged(time => X = (float)time.NewValue, true);
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
circle = new Circle
{
Size = new Vector2(circle_size),
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativePositionAxes = Axes.X,
AlwaysPresent = true,
Colour = Color4.White,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = shadow_radius,
Colour = Color4.Black
},
};
shadowComponents.Add(circle);
if (hitObject is IHasEndTime)
{
DragBar dragBarUnderlay;
Container extensionBar;
AddRangeInternal(new Drawable[]
{
extensionBar = new Container
{
Masking = true,
Size = new Vector2(1, thickness),
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RelativePositionAxes = Axes.X,
RelativeSizeAxes = Axes.X,
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = shadow_radius,
Colour = Color4.Black
},
Child = new Box
{
RelativeSizeAxes = Axes.Both,
}
},
circle,
// only used for drawing the shadow
dragBarUnderlay = new DragBar(null),
// cover up the shadow on the join
new Box
{
Height = thickness,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
RelativeSizeAxes = Axes.X,
},
dragBar = new DragBar(hitObject) { OnDragHandled = e => OnDragHandled?.Invoke(e) },
});
shadowComponents.Add(dragBarUnderlay);
shadowComponents.Add(extensionBar);
}
else
{
AddInternal(circle);
}
updateShadows();
}
protected override void Update()
{
base.Update();
// no bindable so we perform this every update
Width = (float)(HitObject.GetEndTime() - HitObject.StartTime);
}
protected override bool ShouldBeConsideredForInput(Drawable child) => true;
public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) =>
base.ReceivePositionalInputAt(screenSpacePos) ||
circle.ReceivePositionalInputAt(screenSpacePos) ||
dragBar?.ReceivePositionalInputAt(screenSpacePos) == true;
protected override void OnSelected()
{
updateShadows();
}
private void updateShadows()
{
foreach (var s in shadowComponents)
{
if (State == SelectionState.Selected)
{
s.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = shadow_radius / 2,
Colour = Color4.Orange,
};
}
else
{
s.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Radius = shadow_radius,
Colour = State == SelectionState.Selected ? Color4.Orange : Color4.Black
};
}
}
}
protected override void OnDeselected()
{
updateShadows();
}
public override Quad SelectionQuad
{
get
{
// correctly include the circle in the selection quad region, as it is usually outside the blueprint itself.
var leftQuad = circle.ScreenSpaceDrawQuad;
var rightQuad = dragBar?.ScreenSpaceDrawQuad ?? ScreenSpaceDrawQuad;
return new Quad(leftQuad.TopLeft, Vector2.ComponentMax(rightQuad.TopRight, leftQuad.TopRight),
leftQuad.BottomLeft, Vector2.ComponentMax(rightQuad.BottomRight, leftQuad.BottomRight));
}
}
public override Vector2 SelectionPoint => ScreenSpaceDrawQuad.TopLeft;
public class DragBar : Container
{
private readonly HitObject hitObject;
[Resolved]
private Timeline timeline { get; set; }
public Action<DragEvent> OnDragHandled;
public override bool HandlePositionalInput => hitObject != null;
public DragBar(HitObject hitObject)
{
this.hitObject = hitObject;
CornerRadius = 2;
Masking = true;
Size = new Vector2(5, 1);
Anchor = Anchor.CentreRight;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.Y;
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
}
};
}
protected override bool OnHover(HoverEvent e)
{
updateState();
return base.OnHover(e);
}
protected override void OnHoverLost(HoverLostEvent e)
{
updateState();
base.OnHoverLost(e);
}
private bool hasMouseDown;
protected override bool OnMouseDown(MouseDownEvent e)
{
hasMouseDown = true;
updateState();
return true;
}
protected override void OnMouseUp(MouseUpEvent e)
{
hasMouseDown = false;
updateState();
base.OnMouseUp(e);
}
private void updateState()
{
Colour = IsHovered || hasMouseDown ? Color4.OrangeRed : Color4.White;
}
protected override bool OnDragStart(DragStartEvent e) => true;
[Resolved]
private EditorBeatmap beatmap { get; set; }
[Resolved]
private IBeatSnapProvider beatSnapProvider { get; set; }
protected override void OnDrag(DragEvent e)
{
base.OnDrag(e);
OnDragHandled?.Invoke(e);
var time = timeline.GetTimeFromScreenSpacePosition(e.ScreenSpaceMousePosition);
switch (hitObject)
{
case IHasRepeats repeatHitObject:
// find the number of repeats which can fit in the requested time.
var lengthOfOneRepeat = repeatHitObject.Duration / (repeatHitObject.RepeatCount + 1);
var proposedCount = Math.Max(0, (int)((time - hitObject.StartTime) / lengthOfOneRepeat) - 1);
if (proposedCount == repeatHitObject.RepeatCount)
return;
repeatHitObject.RepeatCount = proposedCount;
break;
case IHasEndTime endTimeHitObject:
var snappedTime = Math.Max(hitObject.StartTime, beatSnapProvider.SnapTime(time));
if (endTimeHitObject.EndTime == snappedTime)
return;
endTimeHitObject.EndTime = snappedTime;
break;
}
beatmap.UpdateHitObject(hitObject);
}
protected override void OnDragEnd(DragEndEvent e)
{
base.OnDragEnd(e);
OnDragHandled?.Invoke(null);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="AnonymousIdentificationModule.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* AnonymousIdentificationModule class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System.Web;
using System.Text;
using System.Web.Configuration;
using System.Web.Caching;
using System.Web.Handlers;
using System.Collections;
using System.Configuration.Provider;
using System.Web.Util;
using System.Security.Principal;
using System.Security.Permissions;
using System.Globalization;
using System.Web.Management;
using System.Web.Hosting;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Web.Security.Cryptography;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public sealed class AnonymousIdentificationModule : IHttpModule {
private const int MAX_ENCODED_COOKIE_STRING = 512;
private const int MAX_ID_LENGTH = 128;
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Web.Security.AnonymousIdentificationModule'/>
/// class.
/// </para>
/// </devdoc>
[SecurityPermission(SecurityAction.Demand, Unrestricted=true)]
public AnonymousIdentificationModule() {
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Events
private AnonymousIdentificationEventHandler _CreateNewIdEventHandler;
public event AnonymousIdentificationEventHandler Creating {
add { _CreateNewIdEventHandler += value; }
remove { _CreateNewIdEventHandler -= value; }
}
public static void ClearAnonymousIdentifier()
{
if (!s_Initialized)
Initialize();
HttpContext context = HttpContext.Current;
if (context == null)
return;
// VSWhidbey 418835: When this feature is enabled, prevent infinite loop when cookieless
// mode != Cookies and there was no cookie, also we cannot clear when current user is anonymous.
if (!s_Enabled || !context.Request.IsAuthenticated) {
throw new NotSupportedException(SR.GetString(SR.Anonymous_ClearAnonymousIdentifierNotSupported));
}
////////////////////////////////////////////////////////////
// Check if we need to clear the ticket stored in the URI
bool clearUri = false;
if (context.CookielessHelper.GetCookieValue('A') != null) {
context.CookielessHelper.SetCookieValue('A', null); // Always clear the uri-cookie
clearUri = true;
}
////////////////////////////////////////////////////////////
// Clear cookie if cookies are supported by the browser
if (!CookielessHelperClass.UseCookieless(context, false, s_CookieMode) || context.Request.Browser.Cookies)
{ // clear cookie if required
string cookieValue = String.Empty;
if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
cookieValue = "NoCookie";
HttpCookie cookie = new HttpCookie(s_CookieName, cookieValue);
cookie.HttpOnly = true;
cookie.Path = s_CookiePath;
cookie.Secure = s_RequireSSL;
if (s_Domain != null)
cookie.Domain = s_Domain;
cookie.Expires = new System.DateTime(1999, 10, 12);
context.Response.Cookies.RemoveCookie(s_CookieName);
context.Response.Cookies.Add(cookie);
}
////////////////////////////////////////////////////////////
// Redirect back to this page if we removed a URI ticket
if (clearUri) {
context.Response.Redirect(context.Request.RawUrl, false);
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Public functions
public void Dispose() { }
public void Init(HttpApplication app) {
// for IIS 7, skip event wireup altogether if this feature isn't
// enabled
if (!s_Initialized) {
Initialize();
}
if (s_Enabled) {
app.PostAuthenticateRequest += new EventHandler(this.OnEnter);
}
}
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
private void OnEnter(Object source, EventArgs eventArgs) {
if (!s_Initialized)
Initialize();
if (!s_Enabled)
return;
HttpApplication app;
HttpContext context;
HttpCookie cookie = null;
bool createCookie = false;
AnonymousIdData decodedValue = null;
bool cookieLess;
string encValue = null;
bool isAuthenticated = false;
app = (HttpApplication)source;
context = app.Context;
isAuthenticated = context.Request.IsAuthenticated;
if (isAuthenticated) {
cookieLess = CookielessHelperClass.UseCookieless(context, false /* no redirect */, s_CookieMode);
} else {
cookieLess = CookielessHelperClass.UseCookieless(context, true /* do redirect */, s_CookieMode);
//if (!cookieLess && s_RequireSSL && !context.Request.IsSecureConnection)
// throw new HttpException(SR.GetString(SR.Connection_not_secure_creating_secure_cookie));
}
////////////////////////////////////////////////////////////////////////
// Handle secure-cookies over non SSL
if (s_RequireSSL && !context.Request.IsSecureConnection)
{
if (!cookieLess)
{
cookie = context.Request.Cookies[s_CookieName];
if (cookie != null)
{
cookie = new HttpCookie(s_CookieName, String.Empty);
cookie.HttpOnly = true;
cookie.Path = s_CookiePath;
cookie.Secure = s_RequireSSL;
if (s_Domain != null)
cookie.Domain = s_Domain;
cookie.Expires = new System.DateTime(1999, 10, 12);
if (context.Request.Browser["supportsEmptyStringInCookieValue"] == "false")
cookie.Value = "NoCookie";
context.Response.Cookies.Add(cookie);
}
return;
}
}
////////////////////////////////////////////////////////////
// Step 2: See if cookie, or cookie-header has the value
if (!cookieLess)
{
cookie = context.Request.Cookies[s_CookieName];
if (cookie != null)
{
encValue = cookie.Value;
cookie.Path = s_CookiePath;
if (s_Domain != null)
cookie.Domain = s_Domain;
}
}
else
{
encValue = context.CookielessHelper.GetCookieValue('A');
}
decodedValue = GetDecodedValue(encValue);
if (decodedValue != null && decodedValue.AnonymousId != null) {
// Copy existing value in Request
context.Request.AnonymousID = decodedValue.AnonymousId;
}
if (isAuthenticated) // For the authenticated case, we are done
return;
if (context.Request.AnonymousID == null) {
////////////////////////////////////////////////////////////
// Step 3: Create new Identity
// Raise event
if (_CreateNewIdEventHandler != null) {
AnonymousIdentificationEventArgs e = new AnonymousIdentificationEventArgs(context);
_CreateNewIdEventHandler(this, e);
context.Request.AnonymousID = e.AnonymousID;
}
// Create from GUID
if (string.IsNullOrEmpty(context.Request.AnonymousID)) {
context.Request.AnonymousID = Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture);
} else {
if (context.Request.AnonymousID.Length > MAX_ID_LENGTH)
throw new HttpException(SR.GetString(SR.Anonymous_id_too_long));
}
if (s_RequireSSL && !context.Request.IsSecureConnection && !cookieLess)
return; // Don't create secure-cookie in un-secured connection
createCookie = true;
}
////////////////////////////////////////////////////////////
// Step 4: Check if cookie has to be created
DateTime dtNow = DateTime.UtcNow;
if (!createCookie) {
if (s_SlidingExpiration) {
if (decodedValue == null || decodedValue.ExpireDate < dtNow) {
createCookie = true;
} else {
double secondsLeft = (decodedValue.ExpireDate - dtNow).TotalSeconds;
if (secondsLeft < (double) ((s_CookieTimeout*60)/2)) {
createCookie = true;
}
}
}
}
////////////////////////////////////////////////////////////
// Step 4: Create new cookie or cookieless header
if (createCookie) {
DateTime dtExpireTime = dtNow.AddMinutes(s_CookieTimeout);
encValue = GetEncodedValue(new AnonymousIdData(context.Request.AnonymousID, dtExpireTime));
if (encValue.Length > MAX_ENCODED_COOKIE_STRING)
throw new HttpException(SR.GetString(SR.Anonymous_id_too_long_2));
if (!cookieLess) {
cookie = new HttpCookie(s_CookieName, encValue);
cookie.HttpOnly = true;
cookie.Expires = dtExpireTime;
cookie.Path = s_CookiePath;
cookie.Secure = s_RequireSSL;
if (s_Domain != null)
cookie.Domain = s_Domain;
context.Response.Cookies.Add(cookie);
} else {
context.CookielessHelper.SetCookieValue('A', encValue);
context.Response.Redirect(context.Request.RawUrl);
}
}
}
public static bool Enabled {
get {
if (!s_Initialized) {
Initialize();
}
return s_Enabled;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Static config settings
private static bool s_Initialized = false;
private static bool s_Enabled = false;
private static string s_CookieName = ".ASPXANONYMOUS";
private static string s_CookiePath = "/";
private static int s_CookieTimeout = 100000;
private static bool s_RequireSSL = false;
private static string s_Domain = null;
private static bool s_SlidingExpiration = true;
private static byte [] s_Modifier = null;
private static object s_InitLock = new object();
private static HttpCookieMode s_CookieMode = HttpCookieMode.UseDeviceProfile;
private static CookieProtection s_Protection = CookieProtection.None;
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
// Static functions
private static void Initialize() {
if (s_Initialized)
return;
lock(s_InitLock) {
if (s_Initialized)
return;
AnonymousIdentificationSection settings = RuntimeConfig.GetAppConfig().AnonymousIdentification;
s_Enabled = settings.Enabled;
s_CookieName = settings.CookieName;
s_CookiePath = settings.CookiePath;
s_CookieTimeout = (int) settings.CookieTimeout.TotalMinutes;
s_RequireSSL = settings.CookieRequireSSL;
s_SlidingExpiration = settings.CookieSlidingExpiration;
s_Protection = settings.CookieProtection;
s_CookieMode = settings.Cookieless;
s_Domain = settings.Domain;
s_Modifier = Encoding.UTF8.GetBytes("AnonymousIdentification");
if (s_CookieTimeout < 1)
s_CookieTimeout = 1;
if (s_CookieTimeout > 60 * 24 * 365 * 2)
s_CookieTimeout = 60 * 24 * 365 * 2; // 2 years
s_Initialized = true;
}
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static string GetEncodedValue(AnonymousIdData data){
if (data == null)
return null;
byte [] bufId = Encoding.UTF8.GetBytes(data.AnonymousId);
byte [] bufIdLen = BitConverter.GetBytes(bufId.Length);
byte [] bufDate = BitConverter.GetBytes(data.ExpireDate.ToFileTimeUtc());
byte [] buffer = new byte[12 + bufId.Length];
Buffer.BlockCopy(bufDate, 0, buffer, 0, 8);
Buffer.BlockCopy(bufIdLen, 0, buffer, 8, 4);
Buffer.BlockCopy(bufId, 0, buffer, 12, bufId.Length);
return CookieProtectionHelper.Encode(s_Protection, buffer, Purpose.AnonymousIdentificationModule_Ticket);
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
private static AnonymousIdData GetDecodedValue(string data){
if (data == null || data.Length < 1 || data.Length > MAX_ENCODED_COOKIE_STRING)
return null;
try {
byte [] bBlob = CookieProtectionHelper.Decode(s_Protection, data, Purpose.AnonymousIdentificationModule_Ticket);
if (bBlob == null || bBlob.Length < 13)
return null;
DateTime expireDate = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bBlob, 0));
if (expireDate < DateTime.UtcNow)
return null;
int len = BitConverter.ToInt32(bBlob, 8);
if (len < 0 || len > bBlob.Length - 12)
return null;
string id = Encoding.UTF8.GetString(bBlob, 12, len);
if (id.Length > MAX_ID_LENGTH)
return null;
return new AnonymousIdData(id, expireDate);
}
catch {}
return null;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
[Serializable]
internal class AnonymousIdData
{
internal AnonymousIdData(string id, DateTime dt) {
ExpireDate = dt;
AnonymousId = (dt > DateTime.UtcNow) ? id : null; // Ignore expired data
}
internal string AnonymousId;
internal DateTime ExpireDate;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
public delegate void AnonymousIdentificationEventHandler(object sender, AnonymousIdentificationEventArgs e);
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
public sealed class AnonymousIdentificationEventArgs : EventArgs {
public string AnonymousID { get { return _AnonymousId;} set { _AnonymousId = value;}}
public HttpContext Context { get { return _Context; }}
private string _AnonymousId;
private HttpContext _Context;
public AnonymousIdentificationEventArgs(HttpContext context) {
_Context = context;
}
}
}
| |
// Copyright 2006 Herre Kuijpers - <[email protected]>
//
// This source file(s) may be redistributed, altered and customized
// by any means PROVIDING the authors name and all copyright
// notices remain intact.
// THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED. USE IT AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO
// LIABILITY FOR ANY DATA DAMAGE/LOSS THAT THIS PRODUCT MAY CAUSE.
//-----------------------------------------------------------------------
/*
Copyright (c) 2014, Lars Brubaker
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 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using MatterHackers.Agg;
using MatterHackers.Agg.Image;
using MatterHackers.RayTracer.Light;
using MatterHackers.VectorMath;
namespace MatterHackers.RayTracer
{
public enum AntiAliasing
{
None = 0,
Low = 4,
Medium = 8,
High = 16,
VeryHigh = 32
}
public class RayTracer
{
public RayTracer()
{
}
public AntiAliasing AntiAliasing { get; set; } = AntiAliasing.Medium;
public ColorF[][] ColorBuffer { get; set; }
public double[][] DepthBuffer { get; set; }
public bool MultiThreaded { get; set; } = true;
public Vector3[][] NormalBuffer { get; set; }
public bool RenderDiffuse { get; set; } = true;
public bool RenderHighlights { get; set; } = true;
public bool RenderReflection { get; set; } = true;
public bool RenderRefraction { get; set; } = true;
public bool RenderShadow { get; set; } = true;
public bool TraceWithRayBundles { get; set; } = false;
public void AntiAliasScene(RectangleInt viewport, Scene scene, ColorF[][] imageBufferAsDoubles, int maxSamples)
{
if (MultiThreaded)
{
System.Threading.Tasks.Parallel.For(1, viewport.Height - 1, y => //
{
AntiAliasXSpan(viewport, scene, imageBufferAsDoubles, maxSamples, y);
});
}
else
{
for (int y = 1; y < viewport.Height - 1; y++)
{
AntiAliasXSpan(viewport, scene, imageBufferAsDoubles, maxSamples, y);
}
}
}
public void CopyColorBufferToImage(ImageBuffer destImage, RectangleInt viewport)
{
if (destImage.BitDepth != 32)
{
throw new Exception("We can only render to 32 bit dest at the moment.");
}
Byte[] destBuffer = destImage.GetBuffer();
viewport.Bottom = Math.Max(0, Math.Min(destImage.Height, viewport.Bottom));
viewport.Top = Math.Max(0, Math.Min(destImage.Height, viewport.Top));
if (MultiThreaded)
{
System.Threading.Tasks.Parallel.For(viewport.Bottom, viewport.Height, y =>
{
CopyColorXSpan(destImage, viewport, y, destBuffer);
});
}
else
{
for (int y = viewport.Bottom; y < viewport.Height; y++)
{
CopyColorXSpan(destImage, viewport, y, destBuffer);
}
}
destImage.MarkImageChanged();
}
public void CopyDepthBufferToImage(ImageBuffer destImage, RectangleInt viewport)
{
if (destImage.BitDepth != 32)
{
throw new Exception("We can only render to 32 bit dest at the moment.");
}
Byte[] destBuffer = destImage.GetBuffer();
viewport.Bottom = Math.Max(0, Math.Min(destImage.Height, viewport.Bottom));
viewport.Top = Math.Max(0, Math.Min(destImage.Height, viewport.Top));
double minZ = 5000;
double maxZ = 0;
for (int y = viewport.Bottom; y < viewport.Height; y++)
{
for (int x = viewport.Left; x < viewport.Right; x++)
{
double depthAtXY = DepthBuffer[x][y];
if (depthAtXY < 5000)
{
minZ = Math.Min(minZ, depthAtXY);
maxZ = Math.Max(maxZ, depthAtXY);
}
}
}
double divisor = maxZ - minZ;
if (MultiThreaded)
{
System.Threading.Tasks.Parallel.For(viewport.Bottom, viewport.Height, y => //
{
CopyDepthXSpan(destImage, viewport, y, destBuffer, minZ, divisor);
});
}
else
{
for (int y = viewport.Bottom; y < viewport.Height; y++)
{
CopyDepthXSpan(destImage, viewport, y, destBuffer, minZ, divisor);
}
destImage.MarkImageChanged();
}
}
public void CopyNoramlBufferToImage(ImageBuffer destImage, RectangleInt viewport)
{
if (destImage.BitDepth != 32)
{
throw new Exception("We can only render to 32 bit dest at the moment.");
}
Byte[] destBuffer = destImage.GetBuffer();
viewport.Bottom = Math.Max(0, Math.Min(destImage.Height, viewport.Bottom));
viewport.Top = Math.Max(0, Math.Min(destImage.Height, viewport.Top));
for (int y = viewport.Bottom; y < viewport.Height; y++)
{
for (int x = viewport.Left; x < viewport.Right; x++)
{
int bufferOffset = destImage.GetBufferOffsetY(y);
// we don't need to set this if we are anti-aliased
int totalOffset = bufferOffset + x * 4;
destBuffer[totalOffset++] = (byte)((NormalBuffer[x][y].X + 1) * 128);
destBuffer[totalOffset++] = (byte)((NormalBuffer[x][y].Y + 1) * 128);
destBuffer[totalOffset++] = (byte)((NormalBuffer[x][y].Z + 1) * 128);
destBuffer[totalOffset] = 255;
}
}
destImage.MarkImageChanged();
}
public ColorF CreateAndTraceSecondaryRays(IntersectInfo info, Ray ray, Scene scene, int depth)
{
// calculate ambient light
ColorF infoColorAtHit = info.closestHitObject.GetColor(info);
ColorF color = infoColorAtHit * scene.background.Ambience;
color.alpha = infoColorAtHit.alpha;
double shininess = Math.Pow(10, info.closestHitObject.Material.Gloss + 1);
foreach (ILight light in scene.lights)
{
// calculate diffuse lighting
Vector3 directiorFromHitToLight = light.Origin - info.HitPosition;
double distanceToLight = directiorFromHitToLight.Length;
Vector3 directiorFromHitToLightNormalized = directiorFromHitToLight.GetNormal();
if (RenderDiffuse)
{
double L = Vector3Ex.Dot(directiorFromHitToLightNormalized, info.normalAtHit);
if (L > 0.0f)
{
color += infoColorAtHit * light.Illumination() * L;
}
}
// this is the max depth of raytracing.
// increasing depth will calculate more accurate color, however it will
// also take longer (exponentially)
if (depth < 3)
{
// calculate reflection ray
if (RenderReflection && info.closestHitObject.Material.Reflection > 0)
{
Ray reflectionRay = GetReflectionRay(info.HitPosition, info.normalAtHit, ray.directionNormal);
IntersectInfo reflectionInfo = TracePrimaryRay(reflectionRay, scene);
ColorF reflectionColorAtHit;// = reflectionInfo.closestHitObject.GetColor(reflectionInfo);
if (reflectionInfo.hitType != IntersectionType.None && reflectionInfo.distanceToHit > 0)
{
// recursive call, this makes reflections expensive
reflectionColorAtHit = CreateAndTraceSecondaryRays(reflectionInfo, reflectionRay, scene, depth + 1);
}
else // does not reflect an object, then reflect background color
{
reflectionColorAtHit = scene.background.Color;
reflectionColorAtHit.Alpha0To1 = infoColorAtHit.alpha;
}
color = color.Blend(reflectionColorAtHit, info.closestHitObject.Material.Reflection);
}
//calculate refraction ray
if (RenderRefraction && info.closestHitObject.Material.Transparency > 0)
{
Ray refractionRay = new Ray(info.HitPosition, ray.directionNormal, Ray.sameSurfaceOffset, double.MaxValue); // GetRefractionRay(info.hitPosition, info.normalAtHit, ray.direction, info.closestHit.Material.Refraction);
IntersectInfo refractionInfo = TracePrimaryRay(refractionRay, scene);
ColorF refractionColorAtHit = refractionInfo.closestHitObject.GetColor(refractionInfo);
if (refractionInfo.hitType != IntersectionType.None && refractionInfo.distanceToHit > 0)
{
// recursive call, this makes refractions expensive
refractionColorAtHit = CreateAndTraceSecondaryRays(refractionInfo, refractionRay, scene, depth + 1);
}
else
{
refractionColorAtHit = scene.background.Color;
refractionColorAtHit.Alpha0To1 = infoColorAtHit.alpha;
}
color = refractionColorAtHit.Blend(color, info.closestHitObject.Material.Transparency);
}
}
IntersectInfo shadow = new IntersectInfo();
if (RenderShadow)
{
// calculate shadow, create ray from intersection point to light
Ray shadowRay = new Ray(info.HitPosition, directiorFromHitToLightNormalized, Ray.sameSurfaceOffset, double.MaxValue); // it may be useful to limit the length to the dist to the camera (but I doubt it LBB).
shadowRay.isShadowRay = true;
// if the normal at the closest hit is away from the shadow it is already it it's own shadow.
if (Vector3Ex.Dot(info.normalAtHit, directiorFromHitToLightNormalized) < 0)
{
shadow.hitType = IntersectionType.FrontFace;
color *= 0.5;// +0.5 * Math.Pow(shadow.closestHit.Material.Transparency, 0.5); // Math.Pow(.5, shadow.HitCount);
color.Alpha0To1 = infoColorAtHit.alpha;
}
else
{
// find any element in between intersection point and light
shadow = TracePrimaryRay(shadowRay, scene);
if (shadow.hitType != IntersectionType.None && shadow.closestHitObject != info.closestHitObject && shadow.distanceToHit < distanceToLight)
{
// only cast shadow if the found intersection is another
// element than the current element
color *= 0.5;// +0.5 * Math.Pow(shadow.closestHit.Material.Transparency, 0.5); // Math.Pow(.5, shadow.HitCount);
color.Alpha0To1 = infoColorAtHit.alpha;
}
}
}
// only show highlights if it is not in the shadow of another object
if (RenderHighlights && shadow.hitType == IntersectionType.None && info.closestHitObject.Material.Gloss > 0)
{
// only show Gloss light if it is not in a shadow of another element.
// calculate Gloss lighting (Phong)
Vector3 Lv = (info.HitPosition - light.Origin).GetNormal();
Vector3 E = (ray.origin - info.HitPosition).GetNormal();
Vector3 H = (E - Lv).GetNormal();
double Glossweight = 0.0;
Glossweight = Math.Pow(Math.Max(Vector3Ex.Dot(info.normalAtHit, H), 0), shininess);
color += light.Illumination() * (Glossweight);
}
}
color.Clamp0To1();
return color;
}
public ColorF FullyTraceRay(Ray ray, Scene scene, out IntersectInfo primaryInfo)
{
primaryInfo = TracePrimaryRay(ray, scene);
if (primaryInfo.hitType != IntersectionType.None)
{
ColorF totalColor = CreateAndTraceSecondaryRays(primaryInfo, ray, scene, 0);
return totalColor;
}
return scene.background.Color;
}
public void FullyTraceRayBundle(RayBundle rayBundle, IntersectInfo[] intersectionsForBundle, Scene scene)
{
TracePrimaryRayBundle(rayBundle, intersectionsForBundle, scene);
for (int i = 0; i < rayBundle.rayArray.Length; i++)
{
try
{
IntersectInfo primaryInfo = TracePrimaryRay(rayBundle.rayArray[i], scene);
if (intersectionsForBundle[i].hitType != IntersectionType.None)
{
intersectionsForBundle[i].totalColor = CreateAndTraceSecondaryRays(primaryInfo, rayBundle.rayArray[i], scene, 0);
}
else
{
intersectionsForBundle[i].totalColor = scene.background.Color;
}
}
catch
{
}
}
}
public void RayTraceScene(RectangleInt viewport, Scene scene)
{
int maxsamples = (int)AntiAliasing;
//graphics2D.FillRectangle(viewport, RGBA_Floats.Black);
if (ColorBuffer == null || ColorBuffer.Length < viewport.Width || ColorBuffer[0].Length < viewport.Height)
{
ColorBuffer = new ColorF[viewport.Width][];
for (int i = 0; i < viewport.Width; i++)
{
ColorBuffer[i] = new ColorF[viewport.Height];
}
NormalBuffer = new Vector3[viewport.Width][];
for (int i = 0; i < viewport.Width; i++)
{
NormalBuffer[i] = new Vector3[viewport.Height];
}
DepthBuffer = new double[viewport.Width][];
for (int i = 0; i < viewport.Width; i++)
{
DepthBuffer[i] = new double[viewport.Height];
}
}
if (TraceWithRayBundles)
{
int yStep = 8;
int xStep = 8;
for (int y = viewport.Bottom; y < viewport.Height; y += yStep)
{
for (int x = viewport.Left; x < viewport.Right; x += xStep)
{
try {
int bundleWidth = Math.Min(xStep, viewport.Right - x);
int bundleHeight = Math.Min(yStep, viewport.Top - y);
FrustumRayBundle rayBundle = new FrustumRayBundle(bundleWidth * bundleHeight);
IntersectInfo[] intersectionsForBundle = new IntersectInfo[bundleWidth * bundleHeight];
// Calculate all the initial rays
for (int rayY = 0; rayY < bundleHeight; rayY++)
{
for (int rayX = 0; rayX < bundleWidth; rayX++)
{
rayBundle.rayArray[rayX + rayY * bundleWidth] = scene.camera.GetRay(x + rayX, y + rayY);
intersectionsForBundle[rayX + rayY * bundleWidth] = new IntersectInfo();
}
}
// get a ray to find the origin (every ray comes from the camera and should have the same origin)
rayBundle.CalculateFrustum(bundleWidth, bundleHeight, rayBundle.rayArray[0].origin);
FullyTraceRayBundle(rayBundle, intersectionsForBundle, scene);
// get the color data out of the traced rays
for (int rayY = 0; rayY < bundleHeight; rayY++)
{
for (int rayX = 0; rayX < bundleWidth; rayX++)
{
ColorBuffer[x + rayX][y + rayY] = intersectionsForBundle[rayX + rayY * bundleWidth].totalColor;
}
}
}
catch
{
}
}
}
}
else
{
if (MultiThreaded)
{
System.Threading.Tasks.Parallel.For(viewport.Bottom, viewport.Height, y =>
{
TraceXSpan(viewport, scene, y);
});
}
else
{
for (int y = viewport.Bottom; y < viewport.Height; y++)
{
TraceXSpan(viewport, scene, y);
}
}
}
if (AntiAliasing != AntiAliasing.None)
{
AntiAliasScene(viewport, scene, ColorBuffer, (int)AntiAliasing);
}
}
public IntersectInfo TracePrimaryRay(Ray ray, Scene scene)
{
IntersectInfo primaryRayIntersection = new IntersectInfo();
foreach (IPrimitive shapeToTest in scene.shapes)
{
IntersectInfo info = shapeToTest.GetClosestIntersection(ray);
if (info != null && info.hitType != IntersectionType.None && info.distanceToHit < primaryRayIntersection.distanceToHit && info.distanceToHit >= 0)
{
primaryRayIntersection = info;
}
}
return primaryRayIntersection;
}
public void TracePrimaryRayBundle(RayBundle rayBundle, IntersectInfo[] intersectionsForBundle, Scene scene)
{
if (scene.shapes.Count != 1)
{
throw new Exception("You can only trace a ray bundle into a single shape, usually a BoundingVolumeHierachy.");
}
scene.shapes[0].GetClosestIntersections(rayBundle, 0, intersectionsForBundle);
}
private void AntiAliasXSpan(RectangleInt viewport, Scene scene, ColorF[][] imageBufferAsDoubles, int maxSamples, int y)
{
int fillY = viewport.Top - (viewport.Bottom + y);
for (int x = 1; x < viewport.Width - 1; x++)
{
ColorF avg = (imageBufferAsDoubles[x - 1][y - 1] + imageBufferAsDoubles[x][y - 1] + imageBufferAsDoubles[x + 1][y - 1] +
imageBufferAsDoubles[x - 1][y] + imageBufferAsDoubles[x][y] + imageBufferAsDoubles[x + 1][y] +
imageBufferAsDoubles[x - 1][y + 1] + imageBufferAsDoubles[x][y + 1] + imageBufferAsDoubles[x + 1][y + 1]) / 9;
// use a more accurate anti-aliasing method (MonteCarlo implementation)
// this will fire multiple rays per pixel
double sumOfDifferencesThreshold = .05; // TODO: figure out a good way to determine this.
if (avg.SumOfDistances(imageBufferAsDoubles[x][y]) > sumOfDifferencesThreshold)
{
ColorF accumulatedColor = imageBufferAsDoubles[x][y];
for (int i = 0; i < maxSamples; i++)
{
// get some 'random' samples
double rx = Math.Sign(i % 4 - 1.5) * (IntNoise(x + y * viewport.Width * maxSamples * 2 + i) + 1) / 4;
double ry = Math.Sign(i % 2 - 0.5) * (IntNoise(x + y * viewport.Width * maxSamples * 2 + 1 + i) + 1) / 4;
double xp = x + rx;
double yp = y + ry;
Ray ray = scene.camera.GetRay(xp, yp);
IntersectInfo primaryInfo;
accumulatedColor += FullyTraceRay(ray, scene, out primaryInfo);
}
imageBufferAsDoubles[x][y] = accumulatedColor / (maxSamples + 1);
}
}
}
private void CopyColorXSpan(ImageBuffer destImage, RectangleInt viewport, int y, byte[] destBuffer)
{
for (int x = viewport.Left; x < viewport.Right; x++)
{
int bufferOffset = destImage.GetBufferOffsetY(y);
// we don't need to set this if we are anti-aliased
int totalOffset = bufferOffset + x * 4;
destBuffer[totalOffset++] = (byte)ColorBuffer[x][y].Blue0To255;
destBuffer[totalOffset++] = (byte)ColorBuffer[x][y].Green0To255;
destBuffer[totalOffset++] = (byte)ColorBuffer[x][y].Red0To255;
destBuffer[totalOffset] = (byte)ColorBuffer[x][y].Alpha0To255;
}
}
private void CopyDepthXSpan(ImageBuffer destImage, RectangleInt viewport, int y, byte[] destBuffer, double minZ, double divisor)
{
for (int x = viewport.Left; x < viewport.Right; x++)
{
int bufferOffset = destImage.GetBufferOffsetY(y);
// we don't need to set this if we are anti-aliased
int totalOffset = bufferOffset + x * 4;
double depthXY = DepthBuffer[x][y];
double rangedDepth = (depthXY - minZ) / divisor;
double clampedDepth = Math.Max(0, Math.Min(255, rangedDepth * 255));
byte depthColor = (byte)(clampedDepth);
destBuffer[totalOffset++] = depthColor;
destBuffer[totalOffset++] = depthColor;
destBuffer[totalOffset++] = depthColor;
destBuffer[totalOffset] = 255;
}
}
private Ray GetReflectionRay(Vector3 P, Vector3 N, Vector3 V)
{
double c1 = -Vector3Ex.Dot(N, V);
Vector3 Rl = V + (N * 2 * c1);
return new Ray(P, Rl, Ray.sameSurfaceOffset, double.MaxValue);
}
private Ray GetRefractionRay(Vector3 P, Vector3 N, Vector3 V, double refraction)
{
int method = 0;
switch (method)
{
case 0:
return new Ray(P, V, Ray.sameSurfaceOffset, double.MaxValue);
case 1:
V = V * -1;
double n = -0.55; // refraction constant for now
if (n < 0 || n > 1)
{
return new Ray(P, V); // no refraction
}
break;
case 2:
double c1 = Vector3Ex.Dot(N, V);
double c2 = 1 - refraction * refraction * (1 - c1 * c1);
if (c2 < 0)
c2 = Math.Sqrt(c2);
Vector3 T = (N * (refraction * c1 - c2) - V * refraction) * -1;
T.Normalize();
return new Ray(P, T); // no refraction
}
return new Ray(P, V, Ray.sameSurfaceOffset, double.MaxValue);
}
private double IntNoise(int x)
{
x = (x << 13) ^ x;
return (1.0 - ((x * (x * x * 15731 + 789221) + 1376312589) & 0x7fffffff) / (int.MaxValue / 2.0));
}
private void TraceXSpan(RectangleInt viewport, Scene scene, int y)
{
for (int x = viewport.Left; x < viewport.Right; x++)
{
Ray ray = scene.camera.GetRay(x, y);
IntersectInfo primaryInfo;
ColorBuffer[x][y] = FullyTraceRay(ray, scene, out primaryInfo);
if (false)
{
if (primaryInfo != null)
{
NormalBuffer[x][y] = primaryInfo.normalAtHit;
DepthBuffer[x][y] = primaryInfo.distanceToHit;
}
else
{
NormalBuffer[x][y] = Vector3.UnitZ;
DepthBuffer[x][y] = double.PositiveInfinity;
}
}
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class UShortKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Foo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterStackAlloc()
{
await VerifyKeywordAsync(
@"class C {
int* foo = stackalloc $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFixedStatement()
{
await VerifyKeywordAsync(
@"fixed ($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDelegateReturnType()
{
await VerifyKeywordAsync(
@"public delegate $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCastType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var str = (($$)items) as string;"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOuterConst()
{
await VerifyKeywordAsync(
@"class C {
const $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInnerConst()
{
await VerifyKeywordAsync(AddInsideMethod(
@"const $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestEnumBaseTypes()
{
await VerifyKeywordAsync(
@"enum E : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType1()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType2()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType3()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<int[],$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType4()
{
await VerifyKeywordAsync(AddInsideMethod(
@"IList<IFoo<int?,byte*>,$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInBaseList()
{
await VerifyAbsenceAsync(
@"class C : $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInGenericType_InBaseList()
{
await VerifyKeywordAsync(
@"class C : IList<$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo is $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAs()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var v = foo as $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethod()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterField()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterProperty()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[foo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(
@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
{
await VerifyAbsenceAsync(@"partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterNestedPartial()
{
await VerifyAbsenceAsync(
@"class C {
partial $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAbstract()
{
await VerifyKeywordAsync(
@"class C {
abstract $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticPublic()
{
await VerifyKeywordAsync(
@"class C {
static public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublicStatic()
{
await VerifyKeywordAsync(
@"class C {
public static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterVirtualPublic()
{
await VerifyKeywordAsync(
@"class C {
virtual public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPublic()
{
await VerifyKeywordAsync(
@"class C {
public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedPrivate()
{
await VerifyKeywordAsync(
@"class C {
private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedProtected()
{
await VerifyKeywordAsync(
@"class C {
protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedSealed()
{
await VerifyKeywordAsync(
@"class C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStatic()
{
await VerifyKeywordAsync(
@"class C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInLocalVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"for ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInForeachVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"foreach ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInUsingVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"using ($$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInFromVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInJoinVariableDeclaration()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = from a in b
join $$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodOpenParen()
{
await VerifyKeywordAsync(
@"class C {
void Foo($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodComma()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodAttribute()
{
await VerifyKeywordAsync(
@"class C {
void Foo(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorOpenParen()
{
await VerifyKeywordAsync(
@"class C {
public C($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorComma()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterConstructorAttribute()
{
await VerifyKeywordAsync(
@"class C {
public C(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateOpenParen()
{
await VerifyKeywordAsync(
@"delegate void D($$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateComma()
{
await VerifyKeywordAsync(
@"delegate void D(int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateAttribute()
{
await VerifyKeywordAsync(
@"delegate void D(int i, [Foo]$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterThis()
{
await VerifyKeywordAsync(
@"static class C {
public static void Foo(this $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo(ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo(out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaRef()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (ref $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterLambdaOut()
{
await VerifyKeywordAsync(
@"class C {
void Foo() {
System.Func<int, int> f = (out $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterParams()
{
await VerifyKeywordAsync(
@"class C {
void Foo(params $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInImplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static implicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExplicitOperator()
{
await VerifyKeywordAsync(
@"class C {
public static explicit operator $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracket()
{
await VerifyKeywordAsync(
@"class C {
int this[$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterIndexerBracketComma()
{
await VerifyKeywordAsync(
@"class C {
int this[int i, $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNewInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"new $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInTypeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInDefault()
{
await VerifyKeywordAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInSizeOf()
{
await VerifyKeywordAsync(AddInsideMethod(
@"sizeof($$"));
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInObjectInitializerMemberContext()
{
await VerifyAbsenceAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$");
}
[WorkItem(546938, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546938")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContext()
{
await VerifyKeywordAsync(@"
class Program
{
/// <see cref=""$$"">
static void Main(string[] args)
{
}
}");
}
[WorkItem(546955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546955")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCrefContextNotAfterDot()
{
await VerifyAbsenceAsync(@"
/// <see cref=""System.$$"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAsync()
{
await VerifyKeywordAsync(@"class c { async $$ }");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAsyncAsType()
{
await VerifyAbsenceAsync(@"class c { async async $$ }");
}
[WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInCrefTypeParameter()
{
await VerifyAbsenceAsync(@"
using System;
/// <see cref=""List{$$}"" />
class C { }
");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task Preselection()
{
await VerifyKeywordAsync(@"
class Program
{
static void Main(string[] args)
{
Helper($$)
}
static void Helper(ushort x) { }
}
", matchPriority: SymbolMatchPriority.Keyword);
}
}
}
| |
namespace Antlr.Runtime.Tree
{
using System;
using System.Collections.Generic;
using StringBuilder = System.Text.StringBuilder;
#if !SILVERLIGHT
[System.Serializable]
#endif
[System.Diagnostics.DebuggerTypeProxy(typeof(AntlrRuntime_BaseTreeDebugView))]
internal abstract class BaseTree : ITree
{
private IList<ITree> _children;
public BaseTree()
{
}
public BaseTree( ITree node )
{
}
public virtual IList<ITree> Children
{
get
{
return _children;
}
private set
{
_children = value;
}
}
#region ITree Members
public virtual int ChildCount
{
get
{
if ( Children == null )
return 0;
return Children.Count;
}
}
public virtual ITree Parent
{
get
{
return null;
}
set
{
}
}
public virtual int ChildIndex
{
get
{
return 0;
}
set
{
}
}
public virtual bool IsNil
{
get
{
return false;
}
}
public abstract int TokenStartIndex
{
get;
set;
}
public abstract int TokenStopIndex
{
get;
set;
}
public abstract int Type
{
get;
set;
}
public abstract string Text
{
get;
set;
}
public virtual int Line
{
get;
set;
}
public virtual int CharPositionInLine
{
get;
set;
}
#endregion
public virtual ITree GetChild( int i )
{
if (i < 0)
throw new ArgumentOutOfRangeException();
if ( Children == null || i >= Children.Count )
return null;
return Children[i];
}
public virtual ITree GetFirstChildWithType( int type )
{
foreach ( ITree child in Children )
{
if ( child.Type == type )
return child;
}
return null;
}
public virtual void AddChild( ITree t )
{
//System.out.println("add child "+t.toStringTree()+" "+this.toStringTree());
//System.out.println("existing children: "+children);
if ( t == null )
{
return; // do nothing upon addChild(null)
}
if ( t.IsNil )
{
// t is an empty node possibly with children
BaseTree childTree = t as BaseTree;
if ( childTree != null && this.Children != null && this.Children == childTree.Children )
{
throw new Exception( "attempt to add child list to itself" );
}
// just add all of childTree's children to this
if ( t.ChildCount > 0 )
{
if ( this.Children != null || childTree == null )
{
if ( this.Children == null )
this.Children = CreateChildrenList();
// must copy, this has children already
int n = t.ChildCount;
for ( int i = 0; i < n; i++ )
{
ITree c = t.GetChild( i );
this.Children.Add( c );
// handle double-link stuff for each child of nil root
c.Parent = this;
c.ChildIndex = Children.Count - 1;
}
}
else
{
// no children for this but t is a BaseTree with children;
// just set pointer call general freshener routine
this.Children = childTree.Children;
this.FreshenParentAndChildIndexes();
}
}
}
else
{
// child is not nil (don't care about children)
if ( Children == null )
{
Children = CreateChildrenList(); // create children list on demand
}
Children.Add( t );
t.Parent = this;
t.ChildIndex = Children.Count - 1;
}
// System.out.println("now children are: "+children);
}
public virtual void AddChildren( IEnumerable<ITree> kids )
{
if (kids == null)
throw new ArgumentNullException("kids");
foreach ( ITree t in kids )
AddChild( t );
}
public virtual void SetChild( int i, ITree t )
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if ( t == null )
{
return;
}
if ( t.IsNil )
{
throw new ArgumentException( "Can't set single child to a list" );
}
if ( Children == null )
{
Children = CreateChildrenList();
}
Children[i] = t;
t.Parent = this;
t.ChildIndex = i;
}
public virtual void InsertChild(int i, ITree t)
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if (i > ChildCount)
throw new ArgumentException();
if (i == ChildCount)
{
AddChild(t);
return;
}
Children.Insert(i, t);
// walk others to increment their child indexes
// set index, parent of this one too
this.FreshenParentAndChildIndexes(i);
}
public virtual object DeleteChild( int i )
{
if (i < 0)
throw new ArgumentOutOfRangeException("i");
if (i >= ChildCount)
throw new ArgumentException();
if ( Children == null )
return null;
ITree killed = Children[i];
Children.RemoveAt( i );
// walk rest and decrement their child indexes
this.FreshenParentAndChildIndexes( i );
return killed;
}
public virtual void ReplaceChildren( int startChildIndex, int stopChildIndex, object t )
{
if (startChildIndex < 0)
throw new ArgumentOutOfRangeException();
if (stopChildIndex < 0)
throw new ArgumentOutOfRangeException();
if (t == null)
throw new ArgumentNullException("t");
if (stopChildIndex < startChildIndex)
throw new ArgumentException();
if ( Children == null )
{
throw new ArgumentException( "indexes invalid; no children in list" );
}
int replacingHowMany = stopChildIndex - startChildIndex + 1;
int replacingWithHowMany;
ITree newTree = (ITree)t;
IList<ITree> newChildren = null;
// normalize to a list of children to add: newChildren
if ( newTree.IsNil )
{
BaseTree baseTree = newTree as BaseTree;
if ( baseTree != null && baseTree.Children != null )
{
newChildren = baseTree.Children;
}
else
{
newChildren = CreateChildrenList();
int n = newTree.ChildCount;
for ( int i = 0; i < n; i++ )
newChildren.Add( newTree.GetChild( i ) );
}
}
else
{
newChildren = new List<ITree>( 1 );
newChildren.Add( newTree );
}
replacingWithHowMany = newChildren.Count;
int numNewChildren = newChildren.Count;
int delta = replacingHowMany - replacingWithHowMany;
// if same number of nodes, do direct replace
if ( delta == 0 )
{
int j = 0; // index into new children
for ( int i = startChildIndex; i <= stopChildIndex; i++ )
{
ITree child = newChildren[j];
Children[i] = child;
child.Parent = this;
child.ChildIndex = i;
j++;
}
}
else if ( delta > 0 )
{
// fewer new nodes than there were
// set children and then delete extra
for ( int j = 0; j < numNewChildren; j++ )
{
Children[startChildIndex + j] = newChildren[j];
}
int indexToDelete = startChildIndex + numNewChildren;
for ( int c = indexToDelete; c <= stopChildIndex; c++ )
{
// delete same index, shifting everybody down each time
Children.RemoveAt( indexToDelete );
}
FreshenParentAndChildIndexes( startChildIndex );
}
else
{
// more new nodes than were there before
// fill in as many children as we can (replacingHowMany) w/o moving data
for ( int j = 0; j < replacingHowMany; j++ )
{
Children[startChildIndex + j] = newChildren[j];
}
int numToInsert = replacingWithHowMany - replacingHowMany;
for ( int j = replacingHowMany; j < replacingWithHowMany; j++ )
{
Children.Insert( startChildIndex + j, newChildren[j] );
}
FreshenParentAndChildIndexes( startChildIndex );
}
//System.out.println("out="+toStringTree());
}
protected virtual IList<ITree> CreateChildrenList()
{
return new List<ITree>();
}
public virtual void FreshenParentAndChildIndexes()
{
FreshenParentAndChildIndexes( 0 );
}
public virtual void FreshenParentAndChildIndexes( int offset )
{
int n = ChildCount;
for ( int c = offset; c < n; c++ )
{
ITree child = GetChild( c );
child.ChildIndex = c;
child.Parent = this;
}
}
public virtual void FreshenParentAndChildIndexesDeeply()
{
FreshenParentAndChildIndexesDeeply(0);
}
public virtual void FreshenParentAndChildIndexesDeeply(int offset)
{
int n = ChildCount;
for (int c = offset; c < n; c++)
{
ITree child = GetChild(c);
child.ChildIndex = c;
child.Parent = this;
BaseTree baseTree = child as BaseTree;
if (baseTree != null)
baseTree.FreshenParentAndChildIndexesDeeply();
}
}
public virtual void SanityCheckParentAndChildIndexes()
{
SanityCheckParentAndChildIndexes( null, -1 );
}
public virtual void SanityCheckParentAndChildIndexes( ITree parent, int i )
{
if ( parent != this.Parent )
{
throw new InvalidOperationException( "parents don't match; expected " + parent + " found " + this.Parent );
}
if ( i != this.ChildIndex )
{
throw new InvalidOperationException( "child indexes don't match; expected " + i + " found " + this.ChildIndex );
}
int n = this.ChildCount;
for ( int c = 0; c < n; c++ )
{
BaseTree child = (BaseTree)this.GetChild( c );
child.SanityCheckParentAndChildIndexes( this, c );
}
}
public virtual bool HasAncestor( int ttype )
{
return GetAncestor( ttype ) != null;
}
public virtual ITree GetAncestor( int ttype )
{
ITree t = this;
t = t.Parent;
while ( t != null )
{
if ( t.Type == ttype )
return t;
t = t.Parent;
}
return null;
}
public virtual IList<ITree> GetAncestors()
{
if ( Parent == null )
return null;
List<ITree> ancestors = new List<ITree>();
ITree t = this;
t = t.Parent;
while ( t != null )
{
ancestors.Insert( 0, t ); // insert at start
t = t.Parent;
}
return ancestors;
}
public virtual string ToStringTree()
{
if ( Children == null || Children.Count == 0 )
{
return this.ToString();
}
StringBuilder buf = new StringBuilder();
if ( !IsNil )
{
buf.Append( "(" );
buf.Append( this.ToString() );
buf.Append( ' ' );
}
for ( int i = 0; Children != null && i < Children.Count; i++ )
{
ITree t = Children[i];
if ( i > 0 )
{
buf.Append( ' ' );
}
buf.Append( t.ToStringTree() );
}
if ( !IsNil )
{
buf.Append( ")" );
}
return buf.ToString();
}
public override abstract string ToString();
#region Tree Members
public abstract ITree DupNode();
#endregion
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
public class Pathfinder2D : MonoBehaviour
{
//Singleton
private static Pathfinder2D instance;
public static Pathfinder2D Instance { get { return instance; } private set { } }
//Variables
private Node[,] Map = null;
public float Tilesize = 1;
public int HeuristicAggression;
public float zStart = -10F;
public float zEnd = 10F;
public Vector2 MapStartPosition;
public Vector2 MapEndPosition;
public List<string> DisallowedTags;
public List<string> IgnoreTags;
public bool MoveDiagonal = true;
public bool DrawMapInEditor = false;
//FPS
private float updateinterval = 1F;
private int frames = 0;
private float timeleft = 1F;
private int FPS = 60;
private int times = 0;
private int averageFPS = 0;
int maxSearchRounds = 0;
//Queue path finding to not bottleneck it
private List<QueuePath> queue = new List<QueuePath>();
//Set singleton!
void Awake()
{
instance = this;
}
void Start()
{
if (Tilesize <= 0)
{
Tilesize = 1;
}
Pathfinder2D.Instance.Create2DMap();
}
float overalltimer = 0;
int iterations = 0;
//Go through one
void Update()
{
timeleft -= Time.deltaTime;
frames++;
if (timeleft <= 0F)
{
FPS = frames;
averageFPS += frames;
times++;
timeleft = updateinterval;
frames = 0;
}
float timer = 0F;
float maxtime = 1000 / FPS;
//Bottleneck prevention
while (queue.Count > 0 && timer < maxtime)
{
Stopwatch sw = new Stopwatch();
sw.Start();
StartCoroutine(PathHandler(queue[0].startPos, queue[0].endPos, queue[0].storeRef));
//queue[0].storeRef.Invoke(FindPath(queue[0].startPos, queue[0].endPos));
queue.RemoveAt(0);
sw.Stop();
//print("Timer: " + sw.ElapsedMilliseconds);
timer += sw.ElapsedMilliseconds;
overalltimer += sw.ElapsedMilliseconds;
iterations++;
}
DrawMapLines();
}
#region map
//-------------------------------------------------INSTANIATE MAP-----------------------------------------------//
private void Create2DMap()
{
//Find positions for start and end of map
int startX = (int)MapStartPosition.x;
int startY = (int)MapStartPosition.y;
int endX = (int)MapEndPosition.x;
int endY = (int)MapEndPosition.y;
//Find tile width and height
int width = (int)((endX - startX) / Tilesize);
int height = (int)((endY - startY) / Tilesize);
//Set map up
Map = new Node[width, height];
int size = width * height;
SetListsSize(size);
//Fill up Map
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
float x = startX + (j * Tilesize) + (Tilesize / 2); //Position from where we raycast - X
float y = startY + (i * Tilesize) + (Tilesize / 2); //Position from where we raycast - Z
int ID = (i * width) + j; //ID we give to our Node!
float dist = 20;
RaycastHit[] hit = Physics.SphereCastAll(new Vector3(x, y, zStart), Tilesize / 4, Vector3.forward, dist);
bool free = true;
float maxZ = Mathf.Infinity;
foreach (RaycastHit h in hit)
{
if (DisallowedTags.Contains(h.transform.tag))
{
if (h.point.z < maxZ)
{
//It is a disallowed walking tile, make it false
Map[j, i] = new Node(j, i, y, ID, x, 0, false); //Non walkable tile!
free = false;
maxZ = h.point.z;
}
}
else if (IgnoreTags.Contains(h.transform.tag))
{
//Do nothing we ignore these tags
}
else
{
if (h.point.z < maxZ)
{
//It is allowed to walk on this tile, make it walkable!
Map[j, i] = new Node(j, i, y, ID, x, h.point.z, true); //walkable tile!
free = false;
maxZ = h.point.z;
}
}
}
//We hit nothing set tile to false
if (free == true)
{
Map[j, i] = new Node(j, i, y, ID, x, 0, false);//Non walkable tile!
}
}
}
}
#endregion //End map
//---------------------------------------SETUP PATH QUEUE---------------------------------------//
public void InsertInQueue(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod)
{
QueuePath q = new QueuePath(startPos, endPos, listMethod);
queue.Add(q);
}
#region astar
//---------------------------------------FIND PATH: A*------------------------------------------//
private Node[] openList;
private Node[] closedList;
private Node startNode;
private Node endNode;
private Node currentNode;
//Use it with KEY: F-value, VALUE: ID. ID's might be looked up in open and closed list then
private List<NodeSearch> sortedOpenList = new List<NodeSearch>();
private void SetListsSize(int size)
{
openList = new Node[size];
closedList = new Node[size];
}
IEnumerator PathHandler(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod)
{
yield return StartCoroutine(SinglePath(startPos, endPos, listMethod));
}
IEnumerator SinglePath(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod)
{
FindPath(startPos, endPos, listMethod);
yield return null;
}
public void FindPath(Vector3 startPos, Vector3 endPos, Action<List<Vector3>> listMethod)
{
//The list we returns when path is found
List<Vector3> returnPath = new List<Vector3>();
bool endPosValid = true;
//Find start and end nodes, if we cant return null and stop!
SetStartAndEndNode(startPos, endPos);
if (startNode != null)
{
if (endNode == null)
{
endPosValid = false;
FindEndNode(endPos);
if (endNode == null)
{
//still no end node - we leave and sends an empty list
maxSearchRounds = 0;
listMethod.Invoke(new List<Vector3>());
return;
}
}
//Clear lists if they are filled
Array.Clear(openList, 0, openList.Length);
Array.Clear(closedList, 0, openList.Length);
if (sortedOpenList.Count > 0) { sortedOpenList.Clear(); }
//Insert start node
openList[startNode.ID] = startNode;
//sortedOpenList.Add(new NodeSearch(startNode.ID, startNode.F));
BHInsertNode(new NodeSearch(startNode.ID, startNode.F));
bool endLoop = false;
while (!endLoop)
{
//If we have no nodes on the open list AND we are not at the end, then we got stucked! return empty list then.
if (sortedOpenList.Count == 0)
{
print("Empty Openlist, closedList");
listMethod.Invoke(new List<Vector3>());
return;
}
//Get lowest node and insert it into the closed list
int id = BHGetLowest();
//sortedOpenList.Sort(sort);
//int id = sortedOpenList[0].ID;
currentNode = openList[id];
closedList[currentNode.ID] = currentNode;
openList[id] = null;
//sortedOpenList.RemoveAt(0);
if (currentNode.ID == endNode.ID)
{
endLoop = true;
continue;
}
//Now look at neighbours, check for unwalkable tiles, bounderies, open and closed listed nodes.
if (MoveDiagonal)
{
NeighbourCheck();
}
else
{
NonDiagonalNeighborCheck();
}
}
while (currentNode.parent != null)
{
returnPath.Add(new Vector3(currentNode.xCoord, currentNode.yCoord, currentNode.zCoord));
currentNode = currentNode.parent;
}
returnPath.Add(startPos);
returnPath.Reverse();
if (endPosValid)
{
returnPath.Add(endPos);
}
if (returnPath.Count > 2 && endPosValid)
{
//Now make sure we do not go backwards or go to long
if (Vector3.Distance(returnPath[returnPath.Count - 1], returnPath[returnPath.Count - 3]) < Vector3.Distance(returnPath[returnPath.Count - 3], returnPath[returnPath.Count - 2]))
{
returnPath.RemoveAt(returnPath.Count - 2);
}
if (Vector3.Distance(returnPath[1], startPos) < Vector3.Distance(returnPath[0], returnPath[1]))
{
returnPath.RemoveAt(0);
}
}
maxSearchRounds = 0;
listMethod.Invoke(returnPath);
}
else
{
maxSearchRounds = 0;
listMethod.Invoke(new List<Vector3>());
}
}
// Find start and end Node
private void SetStartAndEndNode(Vector3 start, Vector3 end)
{
startNode = FindClosestNode(start);
endNode = FindClosestNode(end);
}
private Node FindClosestNode(Vector3 pos)
{
int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize);
int y = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.y + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.y - MapStartPosition.y) / Tilesize);
Node n = Map[x, y];
if (n.walkable)
{
return new Node(x, y, n.yCoord, n.ID, n.xCoord, n.zCoord, n.walkable);
}
else
{
//If we get a non walkable tile, then look around its neightbours
for (int i = y - 1; i < y + 2; i++)
{
for (int j = x - 1; j < x + 2; j++)
{
//Check they are within bounderies
if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0))
{
if (Map[j, i].walkable)
{
return new Node(j, i, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable);
}
}
}
}
return null;
}
}
private void FindEndNode(Vector3 pos)
{
int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize);
int y = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.y + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.y - MapStartPosition.y) / Tilesize);
Node closestNode = Map[x, y];
List<Node> walkableNodes = new List<Node>();
int turns = 1;
while (walkableNodes.Count < 1 && maxSearchRounds < (int)10 / Tilesize)
{
walkableNodes = EndNodeNeighbourCheck(x, y, turns);
turns++;
maxSearchRounds++;
}
if (walkableNodes.Count > 0) //If we found some walkable tiles we will then return the nearest
{
int lowestDist = 99999999;
Node n = null;
foreach (Node node in walkableNodes)
{
int i = GetHeuristics(closestNode, node);
if (i < lowestDist)
{
lowestDist = i;
n = node;
}
}
endNode = new Node(n.x, n.y, n.yCoord, n.ID, n.xCoord, n.zCoord, n.walkable);
}
}
private List<Node> EndNodeNeighbourCheck(int x, int z, int r)
{
List<Node> nodes = new List<Node>();
for (int i = z - r; i < z + r + 1; i++)
{
for (int j = x - r; j < x + r + 1; j++)
{
//Check that we are within bounderis, and goes in ring around our end pos
if (i > -1 && j > -1 && i < Map.GetLength(0) && j < Map.GetLength(1) && ((i < z - r + 1 || i > z + r - 1) || (j < x - r + 1 || j > x + r - 1)))
{
//if it is walkable put it on the right list
if (Map[j, i].walkable)
{
nodes.Add(Map[j, i]);
}
}
}
}
return nodes;
}
private void NeighbourCheck()
{
int x = currentNode.x;
int y = currentNode.y;
for (int i = y - 1; i < y + 2; i++)
{
for (int j = x - 1; j < x + 2; j++)
{
//Check it is within the bounderies
if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0))
{
//Dont check for the current node.
if (i != y || j != x)
{
//Check the node is walkable
if (Map[j, i].walkable)
{
//We do not recheck anything on the closed list
if (!OnClosedList(Map[j, i].ID))
{
//If it is not on the open list then add it to
if (!OnOpenList(Map[j, i].ID))
{
Node addNode = new Node(Map[j, i].x, Map[j, i].y, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable, currentNode);
addNode.H = GetHeuristics(Map[j, i].x, Map[j, i].y);
addNode.G = GetMovementCost(x, y, j, i) + currentNode.G;
addNode.F = addNode.H + addNode.G;
//Insert on open list
openList[addNode.ID] = addNode;
//Insert on sorted list
BHInsertNode(new NodeSearch(addNode.ID, addNode.F));
//sortedOpenList.Add(new NodeSearch(addNode.ID, addNode.F));
}
else
{
///If it is on openlist then check if the new paths movement cost is lower
Node n = GetNodeFromOpenList(Map[j, i].ID);
if (currentNode.G + GetMovementCost(x, y, j, i) < openList[Map[j, i].ID].G)
{
n.parent = currentNode;
n.G = currentNode.G + GetMovementCost(x, y, j, i);
n.F = n.G + n.H;
BHSortNode(n.ID, n.F);
//ChangeFValue(n.ID, n.F);
}
}
}
}
}
}
}
}
}
private void NonDiagonalNeighborCheck()
{
int x = currentNode.x;
int y = currentNode.y;
for (int i = y - 1; i < y + 2; i++)
{
for (int j = x - 1; j < x + 2; j++)
{
//Check it is within the bounderies
if (i > -1 && i < Map.GetLength(1) && j > -1 && j < Map.GetLength(0))
{
//Dont check for the current node.
if (i != y || j != x)
{
//Check that we are not moving diagonal
if (GetMovementCost(x, y, j, i) < 14)
{
//Check the node is walkable
if (Map[j, i].walkable)
{
//We do not recheck anything on the closed list
if (!OnClosedList(Map[j, i].ID))
{
//If it is not on the open list then add it to
if (!OnOpenList(Map[j, i].ID))
{
Node addNode = new Node(Map[j, i].x, Map[j, i].y, Map[j, i].yCoord, Map[j, i].ID, Map[j, i].xCoord, Map[j, i].zCoord, Map[j, i].walkable, currentNode);
addNode.H = GetHeuristics(Map[j, i].x, Map[j, i].y);
addNode.G = GetMovementCost(x, y, j, i) + currentNode.G;
addNode.F = addNode.H + addNode.G;
//Insert on open list
openList[addNode.ID] = addNode;
//Insert on sorted list
BHInsertNode(new NodeSearch(addNode.ID, addNode.F));
//sortedOpenList.Add(new NodeSearch(addNode.ID, addNode.F));
}
else
{
///If it is on openlist then check if the new paths movement cost is lower
Node n = GetNodeFromOpenList(Map[j, i].ID);
if (currentNode.G + GetMovementCost(x, y, j, i) < openList[Map[j, i].ID].G)
{
n.parent = currentNode;
n.G = currentNode.G + GetMovementCost(x, y, j, i);
n.F = n.G + n.H;
BHSortNode(n.ID, n.F);
//ChangeFValue(n.ID, n.F);
}
}
}
}
}
}
}
}
}
}
private void ChangeFValue(int id, int F)
{
foreach (NodeSearch ns in sortedOpenList)
{
if (ns.ID == id)
{
ns.F = F;
}
}
}
//Check if a Node is already on the openList
private bool OnOpenList(int id)
{
return (openList[id] != null) ? true : false;
}
//Check if a Node is already on the closedList
private bool OnClosedList(int id)
{
return (closedList[id] != null) ? true : false;
}
private int GetHeuristics(int x, int y)
{
//Make sure heuristic aggression is not less then 0!
int HA = (HeuristicAggression < 0) ? 0 : HeuristicAggression;
return (int)(Mathf.Abs(x - endNode.x) * (10F + (10F * HA))) + (int)(Mathf.Abs(y - endNode.y) * (10F + (10F * HA)));
}
private int GetHeuristics(Node a, Node b)
{
//Make sure heuristic aggression is not less then 0!
int HA = (HeuristicAggression < 0) ? 0 : HeuristicAggression;
return (int)(Mathf.Abs(a.x - b.x) * (10F + (10F * HA))) + (int)(Mathf.Abs(a.y - b.y) * (10F + (10F * HA)));
}
private int GetMovementCost(int x, int y, int j, int i)
{
//Moving straight or diagonal?
return (x != j && y != i) ? 14 : 10;
}
private Node GetNodeFromOpenList(int id)
{
return (openList[id] != null) ? openList[id] : null;
}
#region Binary_Heap (min)
private void BHInsertNode(NodeSearch ns)
{
//We use index 0 as the root!
if (sortedOpenList.Count == 0)
{
sortedOpenList.Add(ns);
openList[ns.ID].sortedIndex = 0;
return;
}
sortedOpenList.Add(ns);
bool canMoveFurther = true;
int index = sortedOpenList.Count - 1;
openList[ns.ID].sortedIndex = index;
while (canMoveFurther)
{
int parent = Mathf.FloorToInt((index - 1) / 2);
if (index == 0) //We are the root
{
canMoveFurther = false;
openList[sortedOpenList[index].ID].sortedIndex = 0;
}
else
{
if (sortedOpenList[index].F < sortedOpenList[parent].F)
{
NodeSearch s = sortedOpenList[parent];
sortedOpenList[parent] = sortedOpenList[index];
sortedOpenList[index] = s;
//Save sortedlist index's for faster look up
openList[sortedOpenList[index].ID].sortedIndex = index;
openList[sortedOpenList[parent].ID].sortedIndex = parent;
//Reset index to parent ID
index = parent;
}
else
{
canMoveFurther = false;
}
}
}
}
private void BHSortNode(int id, int F)
{
bool canMoveFurther = true;
int index = openList[id].sortedIndex;
sortedOpenList[index].F = F;
while (canMoveFurther)
{
int parent = Mathf.FloorToInt((index - 1) / 2);
if (index == 0) //We are the root
{
canMoveFurther = false;
openList[sortedOpenList[index].ID].sortedIndex = 0;
}
else
{
if (sortedOpenList[index].F < sortedOpenList[parent].F)
{
NodeSearch s = sortedOpenList[parent];
sortedOpenList[parent] = sortedOpenList[index];
sortedOpenList[index] = s;
//Save sortedlist index's for faster look up
openList[sortedOpenList[index].ID].sortedIndex = index;
openList[sortedOpenList[parent].ID].sortedIndex = parent;
//Reset index to parent ID
index = parent;
}
else
{
canMoveFurther = false;
}
}
}
}
private int BHGetLowest()
{
if (sortedOpenList.Count == 1) //Remember 0 is our root
{
int ID = sortedOpenList[0].ID;
sortedOpenList.RemoveAt(0);
return ID;
}
else if (sortedOpenList.Count > 1)
{
//save lowest not, take our leaf as root, and remove it! Then switch through children to find right place.
int ID = sortedOpenList[0].ID;
sortedOpenList[0] = sortedOpenList[sortedOpenList.Count - 1];
sortedOpenList.RemoveAt(sortedOpenList.Count - 1);
openList[sortedOpenList[0].ID].sortedIndex = 0;
int index = 0;
bool canMoveFurther = true;
//Sort the list before returning the ID
while (canMoveFurther)
{
int child1 = (index * 2) + 1;
int child2 = (index * 2) + 2;
int switchIndex = -1;
if (child1 < sortedOpenList.Count)
{
switchIndex = child1;
}
else
{
break;
}
if (child2 < sortedOpenList.Count)
{
if (sortedOpenList[child2].F < sortedOpenList[child1].F)
{
switchIndex = child2;
}
}
if (sortedOpenList[index].F > sortedOpenList[switchIndex].F)
{
NodeSearch ns = sortedOpenList[index];
sortedOpenList[index] = sortedOpenList[switchIndex];
sortedOpenList[switchIndex] = ns;
//Save sortedlist index's for faster look up
openList[sortedOpenList[index].ID].sortedIndex = index;
openList[sortedOpenList[switchIndex].ID].sortedIndex = switchIndex;
//Switch around idnex
index = switchIndex;
}
else
{
break;
}
}
return ID;
}
else
{
return -1;
}
}
#endregion
#endregion //End astar region!
//---------------------------------------DRAW MAP IN EDITOR-------------------------------------//
void OnDrawGizmosSelected()
{
//if (DrawMapInEditor == true && Map != null)
//{
// for (int i = 0; i < Map.GetLength(1); i++)
// {
// for (int j = 0; j < Map.GetLength(0); j++)
// {
// if (Map[j, i] == null)
// continue;
// Gizmos.color = (Map[j, i].walkable) ? new Color(0, 0.8F, 0, 0.5F) : new Color(0.8F, 0, 0, 0.5F);
// Gizmos.DrawCube(new Vector3(Map[j, i].xCoord, Map[j, i].yCoord, Map[j, i].zCoord + 0.1F), new Vector3(Tilesize, Tilesize, 0.5F));
// }
// }
//}
}
void DrawMapLines()
{
if (DrawMapInEditor == true && Map != null)
{
for (int i = 0; i < Map.GetLength(1); i++)
{
for (int j = 0; j < Map.GetLength(0); j++)
{
for (int y = i - 1; y < i + 2; y++)
{
for (int x = j - 1; x < j + 2; x++)
{
if (y < 0 || x < 0 || y >= Map.GetLength(1) || x >= Map.GetLength(0))
continue;
if (!Map[x, y].walkable)
continue;
Vector3 start = new Vector3(Map[j, i].xCoord, Map[j, i].yCoord, Map[j, i].zCoord - 0.1f);
Vector3 end = new Vector3(Map[x, y].xCoord, Map[x, y].yCoord, Map[x, y].zCoord - 0.1f);
UnityEngine.Debug.DrawLine(start, end, Color.green);
}
}
}
}
}
}
#region DynamicSupport
public void DynamicMapEdit(List<Vector3> checkList, Action<List<Vector2>> listMethod)
{
listMethod.Invoke(DynamicFindClosestNodes(checkList));
}
public void DynamicRedoMapEdit(List<Vector2> ids)
{
foreach (Vector2 v in ids)
{
Map[(int)v.x, (int)v.y].walkable = true;
}
}
private List<Vector2> DynamicFindClosestNodes(List<Vector3> vList)
{
List<Vector2> returnList = new List<Vector2>();
foreach (Vector3 pos in vList)
{
int x = (MapStartPosition.x < 0F) ? Mathf.FloorToInt(((pos.x + Mathf.Abs(MapStartPosition.x)) / Tilesize)) : Mathf.FloorToInt((pos.x - MapStartPosition.x) / Tilesize);
int y = (MapStartPosition.y < 0F) ? Mathf.FloorToInt(((pos.y + Mathf.Abs(MapStartPosition.y)) / Tilesize)) : Mathf.FloorToInt((pos.y - MapStartPosition.y) / Tilesize);
if (x >= 0 && x < Map.GetLength(0) && y >= 0 && y < Map.GetLength(1))
{
if (Map[x, y].walkable)
{
Map[x, y].walkable = false;
returnList.Add(new Vector2(x, y));
}
}
}
return returnList;
}
#endregion
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using Axiom.Core;
using Axiom.Configuration;
namespace Axiom.Graphics {
///<summary>
/// Object representing one pass or operation in a composition sequence. This provides a
/// method to conviently interleave RenderSystem commands between Render Queues.
///</summary>
public class CompositionPass {
#region Fields
///<summary>
/// Parent technique
///</summary>
protected CompositionTargetPass parent;
///<summary>
/// Type of composition pass
///</summary>
protected CompositorPassType type;
///<summary>
/// Identifier for this pass
///</summary>
protected uint identifier;
///<summary>
/// Material used for rendering
///</summary>
protected Material material;
///<summary>
/// first render queue to render this pass (in case of CompositorPassType.RenderScene)
///</summary>
protected RenderQueueGroupID firstRenderQueue;
///<summary>
/// last render queue to render this pass (in case of CompositorPassType.RenderScene)
///</summary>
protected RenderQueueGroupID lastRenderQueue;
///<summary>
/// Clear buffers (in case of CompositorPassType.Clear)
///</summary>
protected FrameBuffer clearBuffers;
///<summary>
/// Clear colour (in case of CompositorPassType.Clear)
///</summary>
protected ColorEx clearColor;
///<summary>
/// Clear depth (in case of CompositorPassType.Clear)
///</summary>
protected float clearDepth;
///<summary>
/// Clear stencil value (in case of CompositorPassType.Clear)
///</summary>
protected int clearStencil;
///<summary>
/// Inputs (for material used for rendering the quad)
/// An empty string signifies that no input is used
///</summary>
protected string [] inputs = new string[Config.MaxTextureLayers];
///<summary>
/// Stencil operation parameters
///</summary>
protected bool stencilCheck;
protected CompareFunction stencilFunc;
protected int stencilRefValue;
protected int stencilMask;
protected StencilOperation stencilFailOp;
protected StencilOperation stencilDepthFailOp;
protected StencilOperation stencilPassOp;
protected bool stencilTwoSidedOperation;
#endregion Fields
#region Constructor
public CompositionPass(CompositionTargetPass parent) {
this.parent = parent;
type = CompositorPassType.RenderQuad;
identifier = 0;
firstRenderQueue = RenderQueueGroupID.SkiesEarly;
lastRenderQueue = RenderQueueGroupID.SkiesLate;
clearBuffers = FrameBuffer.Color | FrameBuffer.Depth;
clearColor = new ColorEx(0f, 0f, 0f, 0f);
clearDepth = 1.0f;
clearStencil = 0;
stencilCheck = false;
stencilFunc = CompareFunction.AlwaysPass;
stencilRefValue = 0;
stencilMask = (int)0x7FFFFFFF;
stencilFailOp = StencilOperation.Keep;
stencilDepthFailOp = StencilOperation.Keep;
stencilPassOp = StencilOperation.Keep;
stencilTwoSidedOperation = false;
}
#endregion Constructor
#region Properties
public CompositionTargetPass Parent {
get { return parent; }
}
public CompositorPassType Type {
get { return type; }
set { type = value; }
}
public uint Identifier {
get { return identifier; }
set { identifier = value; }
}
public Material Material {
get { return material; }
set { material = value; }
}
public string MaterialName {
set { material = MaterialManager.Instance.GetByName(value); }
}
public RenderQueueGroupID FirstRenderQueue {
get { return firstRenderQueue; }
set { firstRenderQueue = value; }
}
public RenderQueueGroupID LastRenderQueue {
get { return lastRenderQueue; }
set { lastRenderQueue = value; }
}
public FrameBuffer ClearBuffers {
get { return clearBuffers; }
set { clearBuffers = value; }
}
public ColorEx ClearColor {
get { return clearColor; }
set { clearColor = value; }
}
public float ClearDepth {
get { return clearDepth; }
set { clearDepth = value; }
}
public int ClearStencil {
get { return clearStencil; }
set { clearStencil = value; }
}
public bool StencilCheck {
get { return stencilCheck; }
set { stencilCheck = value; }
}
public CompareFunction StencilFunc {
get { return stencilFunc; }
set { stencilFunc = value; }
}
public int StencilRefValue {
get { return stencilRefValue; }
set { stencilRefValue = value; }
}
public int StencilMask {
get { return stencilMask; }
set { stencilMask = value; }
}
public StencilOperation StencilFailOp {
get { return stencilFailOp; }
set { stencilFailOp = value; }
}
public StencilOperation StencilDepthFailOp {
get { return stencilDepthFailOp; }
set { stencilDepthFailOp = value; }
}
public StencilOperation StencilPassOp {
get { return stencilPassOp; }
set { stencilPassOp = value; }
}
public bool StencilTwoSidedOperation {
get { return stencilTwoSidedOperation; }
set { stencilTwoSidedOperation = value; }
}
public bool IsSupported {
get {
if (type == CompositorPassType.RenderQuad) {
if (material == null)
return false;
material.Compile();
if (material.SupportedTechniques.Count == 0)
return false;
}
return true;
}
}
public string[] Inputs {
get { return inputs; }
}
#endregion Properties
#region Methods
///<summary>
/// Set an input local texture. An empty string clears the input.
///</summary>
///<param name="id">Input to set. Must be in 0..Config.MaxTextureLayers-1</param>
///<param name="input"Which texture to bind to this input. An empty string clears the input.</param>
///<remarks>
/// Note applies when CompositorPassType is RenderQuad
///</remarks>
public void SetInput(int id, string input) {
inputs[id] = input;
}
public void SetInput(int id) {
SetInput(id, "");
}
///<summary>
/// Get the value of an input.
///</summary>
///<param name="id">Input to get. Must be in 0..Config.MaxTextureLayers-1.</param>
///<remarks>
/// Note applies when CompositorPassType is RenderQuad
///</remarks>
public string GetInput(int id) {
return inputs[id];
}
///<summary>
/// Get the number of inputs used. If there are holes in the inputs array,
/// this number will include those entries as well.
///</summary>
///<remarks>
/// Note applies when CompositorPassType is RenderQuad
///</remarks>
public int GetNumInputs() {
int count = 0;
for (int i = 0; i < inputs.Length; ++i) {
string s = inputs[i];
if (s != null && s != "")
count = i + 1;
}
return count;
}
///<summary>
/// Clear all inputs.
///</summary>
///<remarks>
/// Note applies when CompositorPassType is RenderQuad
///</remarks>
public void ClearAllInputs() {
for (int i=0; i<Config.MaxTextureLayers; i++)
inputs[i] = "";
}
#endregion Methods
}
}
| |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using ResolutionBuddy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MenuBuddy
{
/// <summary>
/// The screen manager is a component which manages one or more GameScreen
/// instances. It maintains a stack of screens, calls their Update and Draw
/// methods at the appropriate times, and automatically routes input to the
/// topmost active screen.
/// </summary>
public class ScreenManager : DrawableGameComponent, IScreenManager
{
#region Properties
public DefaultGame DefaultGame => Game as DefaultGame;
public ScreenStack ScreenStack
{
get; set;
}
/// <summary>
/// Flag for whether or not this screen manager has been initialized
/// </summary>
private bool Initialized { get; set; }
public IInputHandler Input { get; private set; }
public SpriteBatch SpriteBatch { get; private set; }
public Color ClearColor { get; set; }
public DrawHelper DrawHelper { get; private set; }
public ScreenStackDelegate MainMenuStack { get; set; }
#endregion //Properties
#region Initialization
/// <summary>
/// Constructs a new screen manager component.
/// </summary>
public ScreenManager(Game game, ScreenStackDelegate mainMenuStack)
: base(game)
{
Initialized = false;
MainMenuStack = mainMenuStack;
ScreenStack = new ScreenStack();
ClearColor = StyleSheet.ClearColor;
//get the touch service
Input = game.Services.GetService<IInputHandler>();
if (null == Input)
{
throw new Exception("Cannot initialize ScreenManager without first adding IInputHandler service");
}
game.Components.Add(this);
game.Services.AddService(typeof(IScreenManager), this);
//When using render targets, don't clear the screen!!!
GraphicsDevice.PresentationParameters.RenderTargetUsage = RenderTargetUsage.PreserveContents;
}
/// <summary>
/// Called once by the monogame framework to initialize this thing
/// </summary>
public override void Initialize()
{
base.Initialize();
//allow the screen manager to load content from now on
Initialized = true;
}
/// <summary>
/// Load your graphics content.
/// </summary>
protected override void LoadContent()
{
SpriteBatch = new SpriteBatch(GraphicsDevice);
DrawHelper = new DrawHelper(this);
Task.Run(() => ScreenStack.LoadContent()).ConfigureAwait(false);
}
/// <summary>
/// Unload your graphics content.
/// </summary>
protected override void UnloadContent()
{
ScreenStack?.UnloadContent();
ScreenStack = null;
DrawHelper?.Dispose();
DrawHelper = null;
}
#endregion //Initialization
#region Update and Draw
public override void Update(GameTime gameTime)
{
ScreenStack.Update(gameTime, Input, !Game.IsActive);
}
/// <summary>
/// Tells each screen to draw itself.
/// </summary>
public override void Draw(GameTime gameTime)
{
ScreenStack.Draw(gameTime);
}
/// <summary>
/// A simple way to start the spritebatch from a gamescreen
/// </summary>
public void SpriteBatchBegin(SpriteSortMode sortMode = SpriteSortMode.Deferred)
{
SpriteBatch.Begin(sortMode,
BlendState.NonPremultiplied,
null, null, null, null,
Resolution.TransformationMatrix());
}
/// <summary>
/// A simple way to start the spritebatch from a gamescreen
/// </summary>
public void SpriteBatchBegin(BlendState blendState, SpriteSortMode sortMode = SpriteSortMode.Deferred)
{
SpriteBatch.Begin(sortMode,
blendState,
null, null, null, null,
Resolution.TransformationMatrix());
}
/// <summary>
/// a simple way to end a spritebatch from a gamescreen
/// </summary>
public void SpriteBatchEnd()
{
SpriteBatch.End();
}
#endregion //Update and Draw
#region Public Methods
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public virtual async Task AddScreen(IScreen screen, int? controllingPlayer = null)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
// If we have a graphics device, tell the screen to load content.
if (Initialized)
{
await screen.LoadContent();
}
ScreenStack.AddScreen(screen);
}
/// <summary>
/// Adds a new screen to the screen manager.
/// </summary>
public virtual async Task AddScreen(IScreen[] screens, int? controllingPlayer = null)
{
foreach (var screen in screens)
{
if (screen != null)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
// If we have a graphics device, tell the screen to load content.
if (Initialized)
{
await screen.LoadContent();
}
}
}
ScreenStack.AddScreen(screens);
}
/// <summary>
/// Set the top screen
/// </summary>
/// <param name="screen"></param>
/// <param name="controllingPlayer"></param>
public virtual async Task SetTopScreen(IScreen screen, int? controllingPlayer)
{
screen.ControllingPlayer = controllingPlayer;
screen.ScreenManager = this;
// If we have a graphics device, tell the screen to load content.
if (Initialized)
{
await screen.LoadContent();
}
ScreenStack.TopScreen = screen;
}
/// <summary>
/// Removes a screen from the screen manager. You should normally
/// use GameScreen.ExitScreen instead of calling this directly, so
/// the screen can gradually transition off rather than just being
/// instantly removed.
/// </summary>
public virtual void RemoveScreen(IScreen screen)
{
// If we have a graphics device, tell the screen to unload content.
if (Initialized)
{
screen.UnloadContent();
}
ScreenStack.RemoveScreen(screen);
//reset the times of all the rest of teh screens
var widgetScreens = ScreenStack.FindScreens<WidgetScreen>();
foreach (var curScreen in widgetScreens)
{
curScreen.ResetInputTimer();
}
}
public void RemoveScreens<T>() where T : IScreen
{
var screens = ScreenStack.FindScreens<T>().ToList();
foreach (var screen in screens)
{
RemoveScreen(screen);
}
}
/// <summary>
/// This method pops up a recoverable error screen.
/// </summary>
/// <param name="ex">the exception that occureed</param>
public async Task ErrorScreen(Exception ex)
{
var screens = new List<IScreen>(MainMenuStack());
screens.Add(new ErrorScreen(ex));
ClearScreens();
await LoadingScreen.Load(this, null, string.Empty, screens.ToArray());
}
public IScreen FindScreen(string screenName)
{
return ScreenStack.FindScreen(screenName);
}
public List<T> FindScreens<T>() where T : IScreen
{
return ScreenStack.FindScreens<T>().ToList();
}
/// <summary>
/// Expose an array holding all the screens. We return a copy rather
/// than the real master list, because screens should only ever be added
/// or removed using the AddScreen and RemoveScreen methods.
/// </summary>
public IScreen[] GetScreens()
{
return ScreenStack.GetScreens();
}
public void PopToScreen<T>() where T : class, IScreen
{
ScreenStack.PopToScreen<T>();
}
public void BringToTop<T>() where T : IScreen
{
ScreenStack.BringToTop<T>();
}
/// <summary>
/// Clear the entire screenstack
/// </summary>
public void ClearScreens()
{
// Tell all the current screens to transition off.
foreach (var screen in GetScreens())
{
screen.ExitScreen();
}
}
public bool OnBackButton()
{
return ScreenStack.OnBackButton();
}
#endregion //Public Methods
}
}
| |
using System;
using RSG.Exceptions;
using Xunit;
namespace RSG.Tests
{
public class PromiseProgressTests
{
[Fact]
public void can_report_simple_progress()
{
const float expectedStep = 0.25f;
var currentProgress = 0f;
var promise = new Promise<int>();
promise.Progress(v =>
{
Assert.InRange(expectedStep - (v - currentProgress), -Math.E, Math.E);
currentProgress = v;
});
for (var progress = 0.25f; progress < 1f; progress += 0.25f)
promise.ReportProgress(progress);
promise.ReportProgress(1f);
Assert.Equal(1f, currentProgress);
}
[Fact]
public void can_handle_onProgress()
{
var promise = new Promise<int>();
var progress = 0f;
promise.Then(null, null, v => progress = v);
promise.ReportProgress(1f);
Assert.Equal(1f, progress);
}
[Fact]
public void can_handle_chained_onProgress()
{
var promiseA = new Promise<int>();
var promiseB = new Promise<int>();
var progressA = 0f;
var progressB = 0f;
int result = 0;
promiseA
.Then(v => promiseB, null, v => progressA = v)
.Progress(v => progressB = v)
.Then(v => result = v)
.Done();
promiseA.ReportProgress(1f);
promiseA.Resolve(-17);
promiseB.ReportProgress(2f);
promiseB.Resolve(17);
Assert.Equal(1f, progressA);
Assert.Equal(2f, progressB);
Assert.Equal(17, result);
}
[Fact]
public void can_do_progress_weighted_average()
{
var promiseA = new Promise<int>();
var promiseB = new Promise<int>();
var promiseC = new Promise<int>();
var expectedProgress = new[] { 0.1f, 0.2f, 0.6f, 1f };
var currentProgress = 0f;
int currentStep = 0;
int result = 0;
promiseC.
Progress(v =>
{
Assert.InRange(currentStep, 0, expectedProgress.Length - 1);
Assert.Equal(v, expectedProgress[currentStep]);
currentProgress = v;
++currentStep;
})
.Then(v => result = v)
.Done()
;
promiseA.
Progress(v => promiseC.ReportProgress(v * 0.2f))
.Then(v => promiseB, null)
.Progress(v => promiseC.ReportProgress(0.2f + 0.8f * v))
.Then(v => promiseC.Resolve(v))
.Catch(ex => promiseC.Reject(ex))
;
promiseA.ReportProgress(0.5f);
promiseA.ReportProgress(1f);
promiseA.Resolve(-17);
promiseB.ReportProgress(0.5f);
promiseB.ReportProgress(1f);
promiseB.Resolve(17);
Assert.Equal(expectedProgress.Length, currentStep);
Assert.Equal(1f, currentProgress);
Assert.Equal(17, result);
}
[Fact]
public void chain_multiple_promises_reporting_progress()
{
var promiseA = new Promise<int>();
var promiseB = new Promise<int>();
var progressA = 0f;
var progressB = 0f;
int result = 0;
promiseA
.Progress(v => progressA = v)
.Then(v => promiseB, null)
.Progress(v => progressB = v)
.Then(v => result = v)
.Done()
;
promiseA.ReportProgress(1f);
promiseA.Resolve(-17);
promiseB.ReportProgress(2f);
promiseB.Resolve(17);
Assert.Equal(1f, progressA);
Assert.Equal(2f, progressB);
Assert.Equal(17, result);
}
[Fact]
public void exception_is_thrown_for_progress_after_resolve()
{
var promise = new Promise<int>();
promise.Resolve(17);
Assert.Throws<PromiseStateException>(() => promise.ReportProgress(1f));
}
[Fact]
public void exception_is_thrown_for_progress_after_reject()
{
var promise = new Promise<int>();
promise.Reject(new Exception());
Assert.Throws<PromiseStateException>(() => promise.ReportProgress(1f));
}
[Fact]
public void all_progress_is_averaged()
{
var promiseA = new Promise<int>();
var promiseB = new Promise<int>();
var promiseC = new Promise<int>();
var promiseD = new Promise<int>();
int currentStep = 0;
var expectedProgress = new[] { 0.25f, 0.50f, 0.75f, 1f };
Promise<int>.All(promiseA, promiseB, promiseC, promiseD)
.Progress(progress =>
{
Assert.InRange(currentStep, 0, expectedProgress.Length - 1);
Assert.Equal(expectedProgress[currentStep], progress);
++currentStep;
});
promiseA.ReportProgress(1f);
promiseC.ReportProgress(1f);
promiseB.ReportProgress(1f);
promiseD.ReportProgress(1f);
Assert.Equal(expectedProgress.Length, currentStep);
Assert.Equal(expectedProgress.Length, currentStep);
}
[Fact]
public void race_progress_is_maxed()
{
var promiseA = new Promise<int>();
var promiseB = new Promise<int>();
int reportCount = 0;
Promise<int>.Race(promiseA, promiseB)
.Progress(progress =>
{
Assert.Equal(progress, 0.5f);
++reportCount;
});
promiseA.ReportProgress(0.5f);
promiseB.ReportProgress(0.1f);
promiseB.ReportProgress(0.2f);
promiseB.ReportProgress(0.3f);
promiseB.ReportProgress(0.4f);
promiseB.ReportProgress(0.5f);
Assert.Equal(6, reportCount);
}
[Fact]
public void all_progress_with_resolved()
{
var promiseA = new Promise<int>();
var promiseB = Promise<int>.Resolved(17);
int reportedCount = 0;
Promise<int>.All(promiseA, promiseB)
.Progress(progress =>
{
++reportedCount;
Assert.Equal(0.75f, progress);
});
promiseA.ReportProgress(0.5f);
Assert.Equal(1, reportedCount);
}
}
}
| |
// 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.Generic;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing.TestObjects;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.Routing.Matching
{
public partial class MatcherBuilderMultipleEntryBenchmark : EndpointRoutingBenchmarkBase
{
private IServiceProvider _services;
private List<MatcherPolicy> _policies;
private ILoggerFactory _loggerFactory;
private DefaultEndpointSelector _selector;
private DefaultParameterPolicyFactory _parameterPolicyFactory;
[GlobalSetup]
public void Setup()
{
Endpoints = new RouteEndpoint[10];
Endpoints[0] = CreateEndpoint("/product", "GET");
Endpoints[1] = CreateEndpoint("/product/{id}", "GET");
Endpoints[2] = CreateEndpoint("/account", "GET");
Endpoints[3] = CreateEndpoint("/account/{id}");
Endpoints[4] = CreateEndpoint("/account/{id}", "POST");
Endpoints[5] = CreateEndpoint("/account/{id}", "UPDATE");
Endpoints[6] = CreateEndpoint("/v2/account", "GET");
Endpoints[7] = CreateEndpoint("/v2/account/{id}");
Endpoints[8] = CreateEndpoint("/v2/account/{id}", "POST");
Endpoints[9] = CreateEndpoint("/v2/account/{id}", "UPDATE");
// Define an unordered mixture of policies that implement INodeBuilderPolicy,
// IEndpointComparerPolicy and/or IEndpointSelectorPolicy
_policies = new List<MatcherPolicy>()
{
CreateNodeBuilderPolicy(4),
CreateUberPolicy(2),
CreateNodeBuilderPolicy(3),
CreateEndpointComparerPolicy(5),
CreateNodeBuilderPolicy(1),
CreateEndpointSelectorPolicy(9),
CreateEndpointComparerPolicy(7),
CreateNodeBuilderPolicy(6),
CreateEndpointSelectorPolicy(10),
CreateUberPolicy(12),
CreateEndpointComparerPolicy(11)
};
_loggerFactory = NullLoggerFactory.Instance;
_selector = new DefaultEndpointSelector();
_parameterPolicyFactory = new DefaultParameterPolicyFactory(Options.Create(new RouteOptions()), new TestServiceProvider());
_services = CreateServices();
}
private Matcher SetupMatcher(MatcherBuilder builder)
{
for (int i = 0; i < Endpoints.Length; i++)
{
builder.AddEndpoint(Endpoints[i]);
}
return builder.Build();
}
[Benchmark]
public void Dfa()
{
var builder = _services.GetRequiredService<DfaMatcherBuilder>();
SetupMatcher(builder);
}
[Benchmark]
public void Constructor_Policies()
{
new DfaMatcherBuilder(_loggerFactory, _parameterPolicyFactory, _selector, _policies);
}
private static MatcherPolicy CreateNodeBuilderPolicy(int order)
{
return new TestNodeBuilderPolicy(order);
}
private static MatcherPolicy CreateEndpointComparerPolicy(int order)
{
return new TestEndpointComparerPolicy(order);
}
private static MatcherPolicy CreateEndpointSelectorPolicy(int order)
{
return new TestEndpointSelectorPolicy(order);
}
private static MatcherPolicy CreateUberPolicy(int order)
{
return new TestUberPolicy(order);
}
private class TestUberPolicy : TestMatcherPolicyBase, INodeBuilderPolicy, IEndpointComparerPolicy
{
public TestUberPolicy(int order) : base(order)
{
}
public IComparer<Endpoint> Comparer => new TestEndpointComparer();
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
return false;
}
public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList<PolicyJumpTableEdge> edges)
{
throw new NotImplementedException();
}
public IReadOnlyList<PolicyNodeEdge> GetEdges(IReadOnlyList<Endpoint> endpoints)
{
throw new NotImplementedException();
}
}
private class TestNodeBuilderPolicy : TestMatcherPolicyBase, INodeBuilderPolicy
{
public TestNodeBuilderPolicy(int order) : base(order)
{
}
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
return false;
}
public PolicyJumpTable BuildJumpTable(int exitDestination, IReadOnlyList<PolicyJumpTableEdge> edges)
{
throw new NotImplementedException();
}
public IReadOnlyList<PolicyNodeEdge> GetEdges(IReadOnlyList<Endpoint> endpoints)
{
throw new NotImplementedException();
}
}
private class TestEndpointComparerPolicy : TestMatcherPolicyBase, IEndpointComparerPolicy
{
public TestEndpointComparerPolicy(int order) : base(order)
{
}
public IComparer<Endpoint> Comparer => new TestEndpointComparer();
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
return false;
}
public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
{
throw new NotImplementedException();
}
}
private class TestEndpointSelectorPolicy : TestMatcherPolicyBase, IEndpointSelectorPolicy
{
public TestEndpointSelectorPolicy(int order) : base(order)
{
}
public bool AppliesToEndpoints(IReadOnlyList<Endpoint> endpoints)
{
return false;
}
public Task ApplyAsync(HttpContext httpContext, CandidateSet candidates)
{
throw new NotImplementedException();
}
}
private abstract class TestMatcherPolicyBase : MatcherPolicy
{
private readonly int _order;
protected TestMatcherPolicyBase(int order)
{
_order = order;
}
public override int Order { get { return _order; } }
}
private class TestEndpointComparer : IComparer<Endpoint>
{
public int Compare(Endpoint x, Endpoint y)
{
return 0;
}
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.LanguageServices.Implementation.Venus;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using MSXML;
using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetExpansionClient : ForegroundThreadAffinitizedObject, IVsExpansionClient
{
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly Guid LanguageServiceGuid;
protected readonly ITextView TextView;
protected readonly ITextBuffer SubjectBuffer;
protected bool indentCaretOnCommit;
protected int indentDepth;
protected bool earlyEndExpansionHappened;
internal IVsExpansionSession ExpansionSession;
public AbstractSnippetExpansionClient(Guid languageServiceGuid, ITextView textView, ITextBuffer subjectBuffer, IVsEditorAdaptersFactoryService editorAdaptersFactoryService)
{
this.LanguageServiceGuid = languageServiceGuid;
this.TextView = textView;
this.SubjectBuffer = subjectBuffer;
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
}
public abstract int GetExpansionFunction(IXMLDOMNode xmlFunctionNode, string bstrFieldName, out IVsExpansionFunction pFunc);
protected abstract ITrackingSpan InsertEmptyCommentAndGetEndPositionTrackingSpan();
internal abstract Document AddImports(Document document, XElement snippetNode, bool placeSystemNamespaceFirst, CancellationToken cancellationToken);
public int FormatSpan(IVsTextLines pBuffer, VsTextSpan[] tsInSurfaceBuffer)
{
// Formatting a snippet isn't cancellable.
var cancellationToken = CancellationToken.None;
// At this point, the $selection$ token has been replaced with the selected text and
// declarations have been replaced with their default text. We need to format the
// inserted snippet text while carefully handling $end$ position (where the caret goes
// after Return is pressed). The IVsExpansionSession keeps a tracking point for this
// position but we do the tracking ourselves to properly deal with virtual space. To
// ensure the end location is correct, we take three extra steps:
// 1. Insert an empty comment ("/**/" or "'") at the current $end$ position (prior
// to formatting), and keep a tracking span for the comment.
// 2. After formatting the new snippet text, find and delete the empty multiline
// comment (via the tracking span) and notify the IVsExpansionSession of the new
// $end$ location. If the line then contains only whitespace (due to the formatter
// putting the empty comment on its own line), then delete the white space and
// remember the indentation depth for that line.
// 3. When the snippet is finally completed (via Return), and PositionCaretForEditing()
// is called, check to see if the end location was on a line containing only white
// space in the previous step. If so, and if that line is still empty, then position
// the caret in virtual space.
// This technique ensures that a snippet like "if($condition$) { $end$ }" will end up
// as:
// if ($condition$)
// {
// $end$
// }
SnapshotSpan snippetSpan;
if (!TryGetSubjectBufferSpan(tsInSurfaceBuffer[0], out snippetSpan))
{
return VSConstants.S_OK;
}
// Insert empty comment and track end position
var snippetTrackingSpan = snippetSpan.CreateTrackingSpan(SpanTrackingMode.EdgeInclusive);
var fullSnippetSpan = new VsTextSpan[1];
ExpansionSession.GetSnippetSpan(fullSnippetSpan);
var isFullSnippetFormat =
fullSnippetSpan[0].iStartLine == tsInSurfaceBuffer[0].iStartLine &&
fullSnippetSpan[0].iStartIndex == tsInSurfaceBuffer[0].iStartIndex &&
fullSnippetSpan[0].iEndLine == tsInSurfaceBuffer[0].iEndLine &&
fullSnippetSpan[0].iEndIndex == tsInSurfaceBuffer[0].iEndIndex;
var endPositionTrackingSpan = isFullSnippetFormat ? InsertEmptyCommentAndGetEndPositionTrackingSpan() : null;
var formattingSpan = CommonFormattingHelpers.GetFormattingSpan(SubjectBuffer.CurrentSnapshot, snippetTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot));
SubjectBuffer.CurrentSnapshot.FormatAndApplyToBuffer(formattingSpan, CancellationToken.None);
if (isFullSnippetFormat)
{
CleanUpEndLocation(endPositionTrackingSpan);
// Unfortunately, this is the only place we can safely add references and imports
// specified in the snippet xml. In OnBeforeInsertion we have no guarantee that the
// snippet xml will be available, and changing the buffer during OnAfterInsertion can
// cause the underlying tracking spans to get out of sync.
AddReferencesAndImports(ExpansionSession, cancellationToken);
SetNewEndPosition(endPositionTrackingSpan);
}
return VSConstants.S_OK;
}
private void SetNewEndPosition(ITrackingSpan endTrackingSpan)
{
if (SetEndPositionIfNoneSpecified(ExpansionSession))
{
return;
}
if (endTrackingSpan != null)
{
SnapshotSpan endSpanInSurfaceBuffer;
if (!TryGetSpanOnHigherBuffer(
endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot),
TextView.TextBuffer,
out endSpanInSurfaceBuffer))
{
return;
}
int endLine, endColumn;
TextView.TextSnapshot.GetLineAndColumn(endSpanInSurfaceBuffer.Start.Position, out endLine, out endColumn);
ExpansionSession.SetEndSpan(new VsTextSpan
{
iStartLine = endLine,
iStartIndex = endColumn,
iEndLine = endLine,
iEndIndex = endColumn
});
}
}
private void CleanUpEndLocation(ITrackingSpan endTrackingSpan)
{
if (endTrackingSpan != null)
{
// Find the empty comment and remove it...
var endSnapshotSpan = endTrackingSpan.GetSpan(SubjectBuffer.CurrentSnapshot);
SubjectBuffer.Delete(endSnapshotSpan.Span);
// Remove the whitespace before the comment if necessary. If whitespace is removed,
// then remember the indentation depth so we can appropriately position the caret
// in virtual space when the session is ended.
var line = SubjectBuffer.CurrentSnapshot.GetLineFromPosition(endSnapshotSpan.Start.Position);
var lineText = line.GetText();
if (lineText.Trim() == string.Empty)
{
indentCaretOnCommit = true;
var document = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
var optionService = document.Project.Solution.Workspace.Services.GetService<IOptionService>();
var tabSize = optionService.GetOption(FormattingOptions.TabSize, document.Project.Language);
indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize);
}
else
{
// If we don't have a document, then just guess the typical default TabSize value.
indentDepth = lineText.GetColumnFromLineOffset(lineText.Length, tabSize: 4);
}
SubjectBuffer.Delete(new Span(line.Start.Position, line.Length));
endSnapshotSpan = SubjectBuffer.CurrentSnapshot.GetSpan(new Span(line.Start.Position, 0));
}
}
}
/// <summary>
/// If there was no $end$ token, place it at the end of the snippet code. Otherwise, it
/// defaults to the beginning of the snippet code.
/// </summary>
private static bool SetEndPositionIfNoneSpecified(IVsExpansionSession pSession)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return false;
}
var ns = snippetNode.Name.NamespaceName;
var codeNode = snippetNode.Element(XName.Get("Code", ns));
if (codeNode == null)
{
return false;
}
var delimiterAttribute = codeNode.Attribute("Delimiter");
var delimiter = delimiterAttribute != null ? delimiterAttribute.Value : "$";
if (codeNode.Value.IndexOf(string.Format("{0}end{0}", delimiter), StringComparison.OrdinalIgnoreCase) != -1)
{
return false;
}
var snippetSpan = new VsTextSpan[1];
if (pSession.GetSnippetSpan(snippetSpan) != VSConstants.S_OK)
{
return false;
}
var newEndSpan = new VsTextSpan
{
iStartLine = snippetSpan[0].iEndLine,
iStartIndex = snippetSpan[0].iEndIndex,
iEndLine = snippetSpan[0].iEndLine,
iEndIndex = snippetSpan[0].iEndIndex
};
pSession.SetEndSpan(newEndSpan);
return true;
}
protected static bool TryGetSnippetNode(IVsExpansionSession pSession, out XElement snippetNode)
{
IXMLDOMNode xmlNode = null;
snippetNode = null;
try
{
// Cast to our own version of IVsExpansionSession so that we can get pNode as an
// IntPtr instead of a via a RCW. This allows us to guarantee that it pNode is
// released before leaving this method. Otherwise, a second invocation of the same
// snippet may cause an AccessViolationException.
var session = (IVsExpansionSessionInternal)pSession;
IntPtr pNode;
if (session.GetSnippetNode(null, out pNode) != VSConstants.S_OK)
{
return false;
}
xmlNode = (IXMLDOMNode)Marshal.GetUniqueObjectForIUnknown(pNode);
snippetNode = XElement.Parse(xmlNode.xml);
return true;
}
finally
{
if (xmlNode != null && Marshal.IsComObject(xmlNode))
{
Marshal.ReleaseComObject(xmlNode);
}
}
}
public int PositionCaretForEditing(IVsTextLines pBuffer, [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.TextSpan")]VsTextSpan[] ts)
{
// If the formatted location of the $end$ position (the inserted comment) was on an
// empty line and indented, then we have already removed the white space on that line
// and the navigation location will be at column 0 on a blank line. We must now
// position the caret in virtual space.
int lineLength;
pBuffer.GetLengthOfLine(ts[0].iStartLine, out lineLength);
string endLineText;
pBuffer.GetLineText(ts[0].iStartLine, 0, ts[0].iStartLine, lineLength, out endLineText);
int endLinePosition;
pBuffer.GetPositionOfLine(ts[0].iStartLine, out endLinePosition);
PositionCaretForEditingInternal(endLineText, endLinePosition);
return VSConstants.S_OK;
}
/// <summary>
/// Internal for testing purposes. All real caret positioning logic takes place here. <see cref="PositionCaretForEditing"/>
/// only extracts the <paramref name="endLineText"/> and <paramref name="endLinePosition"/> from the provided <see cref="IVsTextLines"/>.
/// Tests can call this method directly to avoid producing an IVsTextLines.
/// </summary>
/// <param name="endLineText"></param>
/// <param name="endLinePosition"></param>
internal void PositionCaretForEditingInternal(string endLineText, int endLinePosition)
{
if (indentCaretOnCommit && endLineText == string.Empty)
{
TextView.TryMoveCaretToAndEnsureVisible(new VirtualSnapshotPoint(TextView.TextSnapshot.GetPoint(endLinePosition), indentDepth));
}
}
public virtual bool TryHandleTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToNextExpansionField(0);
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleBackTab()
{
if (ExpansionSession != null)
{
var tabbedInsideSnippetField = VSConstants.S_OK == ExpansionSession.GoToPreviousExpansionField();
if (!tabbedInsideSnippetField)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
}
return tabbedInsideSnippetField;
}
return false;
}
public virtual bool TryHandleEscape()
{
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 1);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryHandleReturn()
{
// TODO(davip): Only move the caret if the enter was hit within the editable spans
if (ExpansionSession != null)
{
ExpansionSession.EndCurrentExpansion(fLeaveCaret: 0);
ExpansionSession = null;
return true;
}
return false;
}
public virtual bool TryInsertExpansion(int startPositionInSubjectBuffer, int endPositionInSubjectBuffer)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return false;
}
int startLine = 0;
int startIndex = 0;
int endLine = 0;
int endIndex = 0;
// The expansion itself needs to be created in the data buffer, so map everything up
var startPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(startPositionInSubjectBuffer);
var endPointInSubjectBuffer = SubjectBuffer.CurrentSnapshot.GetPoint(endPositionInSubjectBuffer);
SnapshotSpan dataBufferSpan;
if (!TryGetSpanOnHigherBuffer(
SubjectBuffer.CurrentSnapshot.GetSpan(startPositionInSubjectBuffer, endPositionInSubjectBuffer - startPositionInSubjectBuffer),
textViewModel.DataBuffer,
out dataBufferSpan))
{
return false;
}
var buffer = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer);
var expansion = buffer as IVsExpansion;
if (buffer == null || expansion == null)
{
return false;
}
buffer.GetLineIndexOfPosition(dataBufferSpan.Start.Position, out startLine, out startIndex);
buffer.GetLineIndexOfPosition(dataBufferSpan.End.Position, out endLine, out endIndex);
var textSpan = new VsTextSpan
{
iStartLine = startLine,
iStartIndex = startIndex,
iEndLine = endLine,
iEndIndex = endIndex
};
return expansion.InsertExpansion(textSpan, textSpan, this, LanguageServiceGuid, out ExpansionSession) == VSConstants.S_OK;
}
public int EndExpansion()
{
if (ExpansionSession == null)
{
earlyEndExpansionHappened = true;
}
ExpansionSession = null;
indentCaretOnCommit = false;
return VSConstants.S_OK;
}
public int IsValidKind(IVsTextLines pBuffer, VsTextSpan[] ts, string bstrKind, out int pfIsValidKind)
{
pfIsValidKind = 1;
return VSConstants.S_OK;
}
public int IsValidType(IVsTextLines pBuffer, VsTextSpan[] ts, string[] rgTypes, int iCountTypes, out int pfIsValidType)
{
pfIsValidType = 1;
return VSConstants.S_OK;
}
public int OnAfterInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnAfterInsertion);
return VSConstants.S_OK;
}
public int OnBeforeInsertion(IVsExpansionSession pSession)
{
Logger.Log(FunctionId.Snippet_OnBeforeInsertion);
this.ExpansionSession = pSession;
return VSConstants.S_OK;
}
public int OnItemChosen(string pszTitle, string pszPath)
{
var textViewModel = TextView.TextViewModel;
if (textViewModel == null)
{
Debug.Assert(TextView.IsClosed);
return VSConstants.E_FAIL;
}
var hr = VSConstants.S_OK;
try
{
VsTextSpan textSpan;
GetCaretPositionInSurfaceBuffer(out textSpan.iStartLine, out textSpan.iStartIndex);
textSpan.iEndLine = textSpan.iStartLine;
textSpan.iEndIndex = textSpan.iStartIndex;
IVsExpansion expansion = EditorAdaptersFactoryService.GetBufferAdapter(textViewModel.DataBuffer) as IVsExpansion;
earlyEndExpansionHappened = false;
hr = expansion.InsertNamedExpansion(pszTitle, pszPath, textSpan, this, LanguageServiceGuid, fShowDisambiguationUI: 0, pSession: out ExpansionSession);
if (earlyEndExpansionHappened)
{
// EndExpansion was called before InsertNamedExpansion returned, so set
// expansionSession to null to indicate that there is no active expansion
// session. This can occur when the snippet inserted doesn't have any expansion
// fields.
ExpansionSession = null;
earlyEndExpansionHappened = false;
}
}
catch (COMException ex)
{
hr = ex.ErrorCode;
}
return hr;
}
private void GetCaretPositionInSurfaceBuffer(out int caretLine, out int caretColumn)
{
var vsTextView = EditorAdaptersFactoryService.GetViewAdapter(TextView);
vsTextView.GetCaretPos(out caretLine, out caretColumn);
IVsTextLines textLines;
vsTextView.GetBuffer(out textLines);
// Handle virtual space (e.g, see Dev10 778675)
int lineLength;
textLines.GetLengthOfLine(caretLine, out lineLength);
if (caretColumn > lineLength)
{
caretColumn = lineLength;
}
}
private void AddReferencesAndImports(IVsExpansionSession pSession, CancellationToken cancellationToken)
{
XElement snippetNode;
if (!TryGetSnippetNode(pSession, out snippetNode))
{
return;
}
var documentWithImports = this.SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (documentWithImports == null)
{
return;
}
var optionService = documentWithImports.Project.Solution.Workspace.Services.GetService<IOptionService>();
var placeSystemNamespaceFirst = optionService.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst, documentWithImports.Project.Language);
documentWithImports = AddImports(documentWithImports, snippetNode, placeSystemNamespaceFirst, cancellationToken);
AddReferences(documentWithImports.Project, snippetNode);
}
private void AddReferences(Project originalProject, XElement snippetNode)
{
var referencesNode = snippetNode.Element(XName.Get("References", snippetNode.Name.NamespaceName));
if (referencesNode == null)
{
return;
}
var existingReferenceNames = originalProject.MetadataReferences.Select(r => Path.GetFileNameWithoutExtension(r.Display));
var workspace = originalProject.Solution.Workspace;
var projectId = originalProject.Id;
var assemblyXmlName = XName.Get("Assembly", snippetNode.Name.NamespaceName);
var failedReferenceAdditions = new List<string>();
var visualStudioWorkspace = workspace as VisualStudioWorkspaceImpl;
foreach (var reference in referencesNode.Elements(XName.Get("Reference", snippetNode.Name.NamespaceName)))
{
// Note: URL references are not supported
var assemblyElement = reference.Element(assemblyXmlName);
var assemblyName = assemblyElement != null ? assemblyElement.Value.Trim() : null;
if (string.IsNullOrEmpty(assemblyName))
{
continue;
}
if (visualStudioWorkspace == null ||
!visualStudioWorkspace.TryAddReferenceToProject(projectId, assemblyName))
{
failedReferenceAdditions.Add(assemblyName);
}
}
if (failedReferenceAdditions.Any())
{
var notificationService = workspace.Services.GetService<INotificationService>();
notificationService.SendNotification(
string.Format(ServicesVSResources.ReferencesNotFound, Environment.NewLine)
+ Environment.NewLine + Environment.NewLine
+ string.Join(Environment.NewLine, failedReferenceAdditions),
severity: NotificationSeverity.Warning);
}
}
protected static bool TryAddImportsToContainedDocument(Document document, IEnumerable<string> memberImportsNamespaces)
{
var vsWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (vsWorkspace == null)
{
return false;
}
var containedDocument = vsWorkspace.GetHostDocument(document.Id) as ContainedDocument;
if (containedDocument == null)
{
return false;
}
var containedLanguageHost = containedDocument.ContainedLanguage.ContainedLanguageHost as IVsContainedLanguageHostInternal;
if (containedLanguageHost != null)
{
foreach (var importClause in memberImportsNamespaces)
{
if (containedLanguageHost.InsertImportsDirective(importClause) != VSConstants.S_OK)
{
return false;
}
}
}
return true;
}
protected static bool TryGetSnippetFunctionInfo(IXMLDOMNode xmlFunctionNode, out string snippetFunctionName, out string param)
{
if (xmlFunctionNode.text.IndexOf('(') == -1 ||
xmlFunctionNode.text.IndexOf(')') == -1 ||
xmlFunctionNode.text.IndexOf(')') < xmlFunctionNode.text.IndexOf('('))
{
snippetFunctionName = null;
param = null;
return false;
}
snippetFunctionName = xmlFunctionNode.text.Substring(0, xmlFunctionNode.text.IndexOf('('));
var paramStart = xmlFunctionNode.text.IndexOf('(') + 1;
var paramLength = xmlFunctionNode.text.LastIndexOf(')') - xmlFunctionNode.text.IndexOf('(') - 1;
param = xmlFunctionNode.text.Substring(paramStart, paramLength);
return true;
}
internal bool TryGetSubjectBufferSpan(VsTextSpan surfaceBufferTextSpan, out SnapshotSpan subjectBufferSpan)
{
var snapshotSpan = TextView.TextSnapshot.GetSpan(surfaceBufferTextSpan);
var subjectBufferSpanCollection = TextView.BufferGraph.MapDownToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, SubjectBuffer);
// Bail if a snippet span does not map down to exactly one subject buffer span.
if (subjectBufferSpanCollection.Count == 1)
{
subjectBufferSpan = subjectBufferSpanCollection.Single();
return true;
}
subjectBufferSpan = default(SnapshotSpan);
return false;
}
internal bool TryGetSpanOnHigherBuffer(SnapshotSpan snapshotSpan, ITextBuffer targetBuffer, out SnapshotSpan span)
{
var spanCollection = TextView.BufferGraph.MapUpToBuffer(snapshotSpan, SpanTrackingMode.EdgeExclusive, targetBuffer);
// Bail if a snippet span does not map up to exactly one span.
if (spanCollection.Count == 1)
{
span = spanCollection.Single();
return true;
}
span = default(SnapshotSpan);
return false;
}
}
}
| |
// <copyright file="Requires.cs" company="LeetABit">
// Copyright (c) Hubert Bukowski. All rights reserved.
// Licensed under the MIT License.
// See LICENSE file in the project root for full license information.
// </copyright>
namespace LeetABit.Binary
{
using System;
using LeetABit.Binary.Properties;
/// <summary>
/// Provides methods for checking method requirements such as argument and object state verification.
/// </summary>
internal static class Requires
{
/// <summary>
/// Checks whether the specified argument is not <see langword="null"/>.
/// </summary>
/// <typeparam name="T">
/// Type of the argument.
/// </typeparam>
/// <param name="argument">
/// Argument object to check.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <returns>
/// <paramref name="argument"/> argument.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="argument"/> is <see langword="null"/>.
/// </exception>
public static T ArgumentNotNull<T>(T argument, string parameterName)
{
return argument ?? throw new ArgumentNullException(parameterName);
}
/// <summary>
/// Checks whether the specified argument is not <see langword="null"/> and is not composed of white spaces only.
/// </summary>
/// <param name="argument">
/// Argument object to check.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="argument"/> argument.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <paramref name="argument"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// <paramref name="argument"/> is composed of white spaces only.
/// </exception>
public static string ArgumentNotNullNorWhiteSpace(string argument, string parameterName, string? message = null)
{
message ??= Resources.Exception_Argument_WhiteSpace;
_ = ArgumentNotNull(argument, parameterName);
return !string.IsNullOrWhiteSpace(argument)
? argument
: throw new ArgumentException(message, parameterName);
}
/// <summary>
/// Checks whether the specified integer is greater or equals to zero.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is less than zero.
/// </exception>
public static int ArgumentGreaterThanOrEqualsZero(int value, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentLessThanZero;
return value >= 0
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified integer is equals to the specified value.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="expected">
/// Expected value.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is different than the specified <paramref name="expected"/> value.
/// </exception>
public static int ArgumentEquals(int value, int expected, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentDifferentThanExpected;
return value == expected
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified integer is less than the specified limit value.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="limit">
/// Value upper limit.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is greater than or equals to the specified <paramref name="limit"/>.
/// </exception>
public static int ArgumentLessThan(int value, int limit, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentGreaterThanOrEquals;
return value < limit
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified integer is greater than the specified limit value.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="limit">
/// Value lower limit.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is less than or equals to the specified <paramref name="limit"/>.
/// </exception>
public static int ArgumentGreaterThan(int value, int limit, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentLessThanOrEquals;
return value > limit
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified integer is less than or equals the specified limit value.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="limit">
/// Value upper limit.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is greater than the specified <paramref name="limit"/>.
/// </exception>
public static int ArgumentLessThanOrEquals(int value, int limit, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentGreaterThan;
return value <= limit
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified integer is greater than or equals the specified limit value.
/// </summary>
/// <param name="value">
/// Value to verify.
/// </param>
/// <param name="limit">
/// Value lower limit.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which the arguemnt was bound.
/// </param>
/// <param name="message">
/// Message for the exception in case of check failure.
/// </param>
/// <returns>
/// <paramref name="value"/> argument.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="value"/> is greater than the specified <paramref name="limit"/>.
/// </exception>
public static int ArgumentGreaterThanOrEquals(int value, int limit, string parameterName, string? message = null)
{
message ??= Resources.Exception_ArgumentOutOfRange_ArgumentLessThan;
return value >= limit
? value
: throw new ArgumentOutOfRangeException(parameterName, value, message);
}
/// <summary>
/// Checks whether the specified bit index lies within the specified number of bits.
/// </summary>
/// <param name="bitIndex">
/// Bit index to verify.
/// </param>
/// <param name="numberOfBits">
/// Number of bits available for the bit index.
/// </param>
/// <param name="parameterName">
/// Name of the paraemter for which the value of <paramref name="bitIndex"/> parameter was passed as an argument.
/// </param>
/// <returns>
/// Value of the <paramref name="bitIndex"/> parameter.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="bitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="bitIndex"/> is greater than or equals to number of bits available for bit index.
/// </exception>
public static int BitIndexWithinAvailableSpan(int bitIndex, int numberOfBits, string parameterName)
{
_ = ArgumentGreaterThanOrEqualsZero(bitIndex, parameterName);
return ArgumentLessThan(bitIndex, numberOfBits, parameterName, Resources.Exception_ArgumentOutOfRange_BitIndexOutsideOfBitsSpan);
}
/// <summary>
/// Checks whether the specified bit block lies within boundary of the available size.
/// </summary>
/// <param name="startBitIndex">
/// First bit of the bit span.
/// </param>
/// <param name="bitLength">
/// Bit length of the bit span.
/// </param>
/// <param name="numberOfBits">
/// Number of bits available for the bit index.
/// </param>
/// <param name="startBitParameterName">
/// Name of the parameter for which the <paramref name="startBitIndex"/> argument was bound.
/// </param>
/// <param name="bitLengthParameterName">
/// Name of the parameter for which the <paramref name="bitLength"/> argument was bound.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="startBitIndex"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is greater than the non zero number of available bits.
/// <para>-or-</para>
/// <paramref name="startBitIndex"/> is different than zero and number of avaialble bits is zero.
/// <para>-or-</para>
/// <paramref name="bitLength"/> is less than zero.
/// <para>-or-</para>
/// <paramref name="bitLength"/> applied to <paramref name="startBitIndex"/> does not fit into the number of available bits.
/// </exception>
public static void BitBlockWithinAvailableSpan(int startBitIndex, int bitLength, int numberOfBits, string startBitParameterName, string bitLengthParameterName)
{
_ = numberOfBits == 0
? ArgumentEquals(startBitIndex, 0, startBitParameterName, Resources.Exception_ArgumentOutOfRange_BitIndexNonZeroForEmptySize)
: BitIndexWithinAvailableSpan(startBitIndex, numberOfBits, startBitParameterName);
_ = ArgumentGreaterThanOrEqualsZero(bitLength, bitLengthParameterName);
_ = ArgumentLessThanOrEquals(bitLength, numberOfBits - startBitIndex, bitLengthParameterName, Resources.Exception_ArgumentOutOfRange_BitLengthOutsideOfBitsSpan);
}
/// <summary>
/// Throws an <see cref="ArgumentException"/> if the <paramref name="condition"/> is <see langword="false"/>.
/// </summary>
/// <param name="condition">
/// Condition to evaluate.
/// </param>
/// <param name="parameterName">
/// Name of the parameter for which verification failed.
/// </param>
/// <param name="message">
/// Message of the exception to be thrown.
/// </param>
/// <exception cref="ArgumentException">
/// <paramref name="condition"/> is <see langword="false"/>.
/// </exception>
public static void ArgumentState(bool condition, string parameterName, string message)
{
if (!condition)
{
throw new ArgumentException(message, parameterName);
}
}
/// <summary>
/// Throws an <see cref="InvalidOperationException"/> if the <paramref name="condition"/> is <see langword="false"/>.
/// </summary>
/// <param name="condition">
/// Condition to evaluate.
/// </param>
/// <param name="message">
/// Message of the exception to be thrown.
/// </param>
/// <exception cref="InvalidOperationException">
/// <paramref name="condition"/> is <see langword="false"/>.
/// </exception>
public static void ObjectState(bool condition, string message)
{
if (!condition)
{
throw new InvalidOperationException(message);
}
}
}
}
| |
#if !UNITY_METRO && !UNITY_WEBPLAYER && (UNITY_PRO_LICENSE || !(UNITY_ANDROID || UNITY_IPHONE))
#define UTT_SOCKETS_SUPPORTED
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using UnityTest.IntegrationTestRunner;
#if UTT_SOCKETS_SUPPORTED
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
#endif
#if UNITY_EDITOR
using UnityEditorInternal;
#endif
namespace UnityTest
{
public class TestRunnerConfigurator
{
public static string integrationTestsNetwork = "networkconfig.txt";
public static string batchRunFileMarker = "batchrun.txt";
public static string testScenesToRun = "testscenes.txt";
public static string previousScenes = "previousScenes.txt";
public bool isBatchRun { get; private set; }
public bool sendResultsOverNetwork { get; private set; }
#if UTT_SOCKETS_SUPPORTED
private readonly List<IPEndPoint> m_IPEndPointList = new List<IPEndPoint>();
#endif
public TestRunnerConfigurator()
{
CheckForBatchMode();
CheckForSendingResultsOverNetwork();
}
#if UNITY_EDITOR
public UnityEditor.EditorBuildSettingsScene[] GetPreviousScenesToRestore()
{
string text = null;
if (Application.isEditor)
{
text = GetTextFromTempFile(previousScenes);
}
if(text != null)
{
var serializer = new System.Xml.Serialization.XmlSerializer(typeof(UnityEditor.EditorBuildSettingsScene[]));
using(var textReader = new StringReader(text))
{
try
{
return (UnityEditor.EditorBuildSettingsScene[] )serializer.Deserialize(textReader);
}
catch (System.Xml.XmlException e)
{
return null;
}
}
}
return null;
}
#endif
public string GetIntegrationTestScenes(int testSceneNum)
{
string text;
if (Application.isEditor)
text = GetTextFromTempFile(testScenesToRun);
else
text = GetTextFromTextAsset(testScenesToRun);
List<string> sceneList = new List<string>();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
sceneList.Add(line.ToString());
}
if (testSceneNum < sceneList.Count)
return sceneList.ElementAt(testSceneNum);
else
return null;
}
private void CheckForSendingResultsOverNetwork()
{
#if UTT_SOCKETS_SUPPORTED
string text;
if (Application.isEditor)
text = GetTextFromTempFile(integrationTestsNetwork);
else
text = GetTextFromTextAsset(integrationTestsNetwork);
if (text == null) return;
sendResultsOverNetwork = true;
m_IPEndPointList.Clear();
foreach (var line in text.Split(new[] {'\n'}, StringSplitOptions.RemoveEmptyEntries))
{
var idx = line.IndexOf(':');
if (idx == -1) throw new Exception(line);
var ip = line.Substring(0, idx);
var port = line.Substring(idx + 1);
m_IPEndPointList.Add(new IPEndPoint(IPAddress.Parse(ip), Int32.Parse(port)));
}
#endif // if UTT_SOCKETS_SUPPORTED
}
private static string GetTextFromTextAsset(string fileName)
{
var nameWithoutExtension = fileName.Substring(0, fileName.LastIndexOf('.'));
var resultpathFile = Resources.Load(nameWithoutExtension) as TextAsset;
return resultpathFile != null ? resultpathFile.text : null;
}
private static string GetTextFromTempFile(string fileName)
{
string text = null;
try
{
#if UNITY_EDITOR && !UNITY_WEBPLAYER
text = File.ReadAllText(Path.Combine("Temp", fileName));
#endif
}
catch
{
return null;
}
return text;
}
private void CheckForBatchMode()
{
#if IMITATE_BATCH_MODE
isBatchRun = true;
#elif UNITY_EDITOR
if (Application.isEditor && InternalEditorUtility.inBatchMode)
isBatchRun = true;
#else
if (GetTextFromTextAsset(batchRunFileMarker) != null) isBatchRun = true;
#endif
}
public static List<string> GetAvailableNetworkIPs()
{
#if UTT_SOCKETS_SUPPORTED
if (!NetworkInterface.GetIsNetworkAvailable())
return new List<String>{IPAddress.Loopback.ToString()};
var ipList = new List<UnicastIPAddressInformation>();
var allIpsList = new List<UnicastIPAddressInformation>();
foreach (var netInterface in NetworkInterface.GetAllNetworkInterfaces())
{
if (netInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 &&
netInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet)
continue;
var ipAdresses = netInterface.GetIPProperties().UnicastAddresses
.Where(a => a.Address.AddressFamily == AddressFamily.InterNetwork);
allIpsList.AddRange(ipAdresses);
if (netInterface.OperationalStatus != OperationalStatus.Up) continue;
ipList.AddRange(ipAdresses);
}
//On Mac 10.10 all interfaces return OperationalStatus.Unknown, thus this workaround
if(!ipList.Any()) return allIpsList.Select(i => i.Address.ToString()).ToList();
// sort ip list by their masks to predict which ip belongs to lan network
ipList.Sort((ip1, ip2) =>
{
var mask1 = BitConverter.ToInt32(ip1.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
var mask2 = BitConverter.ToInt32(ip2.IPv4Mask.GetAddressBytes().Reverse().ToArray(), 0);
return mask2.CompareTo(mask1);
});
if (ipList.Count == 0)
return new List<String> { IPAddress.Loopback.ToString() };
return ipList.Select(i => i.Address.ToString()).ToList();
#else
return new List<string>();
#endif // if UTT_SOCKETS_SUPPORTED
}
public ITestRunnerCallback ResolveNetworkConnection()
{
#if UTT_SOCKETS_SUPPORTED
var nrsList = m_IPEndPointList.Select(ipEndPoint => new NetworkResultSender(ipEndPoint.Address.ToString(), ipEndPoint.Port)).ToList();
var timeout = TimeSpan.FromSeconds(30);
DateTime startTime = DateTime.Now;
while ((DateTime.Now - startTime) < timeout)
{
foreach (var networkResultSender in nrsList)
{
try
{
if (!networkResultSender.Ping()) continue;
}
catch (Exception e)
{
Debug.LogException(e);
sendResultsOverNetwork = false;
return null;
}
return networkResultSender;
}
Thread.Sleep(500);
}
Debug.LogError("Couldn't connect to the server: " + string.Join(", ", m_IPEndPointList.Select(ipep => ipep.Address + ":" + ipep.Port).ToArray()));
sendResultsOverNetwork = false;
#endif // if UTT_SOCKETS_SUPPORTED
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Security.Cryptography.EcDsa.Tests;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.Cng.Tests
{
public class ECDsaCngTests : ECDsaTestsBase
{
[Fact]
public static void TestNegativeVerify256()
{
CngKey key = TestData.s_ECDsa256Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429"
+ "e8713dad9a67eb0a5c355e9e23dc").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
public static void TestPositiveVerify384()
{
CngKey key = TestData.s_ECDsa384Key;
ECDsaCng e = new ECDsaCng(key);
byte[] sig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8"
+ "2366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig);
Assert.True(verified);
}
[Fact]
public static void TestNegativeVerify384()
{
CngKey key = TestData.s_ECDsa384Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8"
+ "f366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
public static void TestPositiveVerify521()
{
CngKey key = TestData.s_ECDsa521Key;
ECDsaCng e = new ECDsaCng(key);
byte[] sig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845"
+ "b6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7"
+ "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig);
Assert.True(verified);
}
[Fact]
public static void TestNegativeVerify521()
{
CngKey key = TestData.s_ECDsa521Key;
ECDsaCng e = new ECDsaCng(key);
byte[] tamperedSig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845"
+ "a6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7"
+ "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray();
bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
Assert.False(verified);
}
[Fact]
public static void TestVerify521_EcdhKey()
{
byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone();
// Rewrite the dwMagic value to be ECDH
// ECDSA prefix: 45 43 53 36
// ECDH prefix : 45 43 4b 36
keyBlob[2] = 0x4b;
using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob))
{
// Preconditions:
Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup);
Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm);
using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key))
using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521))
{
byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512);
byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512);
Assert.True(
ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512),
"ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)");
Assert.True(
ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512),
"ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)");
}
}
}
[Fact]
public static void CreateEcdsaFromRsaKey_Fails()
{
using (RSACng rsaCng = new RSACng())
{
Assert.Throws<ArgumentException>(() => new ECDsaCng(rsaCng.Key));
}
}
[Fact]
public static void TestCreateKeyFromCngAlgorithmNistP256()
{
CngAlgorithm alg = CngAlgorithm.ECDsaP256;
using (CngKey key = CngKey.Create(alg))
{
VerifyKey(key);
using (ECDsaCng e = new ECDsaCng(key))
{
Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup);
Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm);
VerifyKey(e.Key);
e.Exercise();
}
}
}
[Fact]
public static void TestCreateByKeySizeNistP256()
{
using (ECDsaCng cng = new ECDsaCng(256))
{
CngKey key1 = cng.Key;
Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);
// The three legacy nist curves are not treated as generic named curves
Assert.Equal(CngAlgorithm.ECDsaP256, key1.Algorithm);
Assert.Equal(256, key1.KeySize);
VerifyKey(key1);
}
}
#if netcoreapp
[Fact]
public static void TestPositive256WithBlob()
{
CngKey key = TestData.s_ECDsa256Key;
ECDsaCng e = new ECDsaCng(key);
Verify256(e, true);
}
[Theory, MemberData(nameof(TestCurves))]
public static void TestKeyPropertyFromNamedCurve(CurveDef curveDef)
{
ECDsaCng e = new ECDsaCng(curveDef.Curve);
CngKey key1 = e.Key;
VerifyKey(key1);
e.Exercise();
CngKey key2 = e.Key;
Assert.Same(key1, key2);
}
[Fact]
public static void TestCreateByNameNistP521()
{
using (ECDsaCng cng = new ECDsaCng(ECCurve.NamedCurves.nistP521))
{
CngKey key1 = cng.Key;
Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);
// The three legacy nist curves are not treated as generic named curves
Assert.Equal(CngAlgorithm.ECDsaP521, key1.Algorithm);
Assert.Equal(521, key1.KeySize);
VerifyKey(key1);
}
}
[Theory, MemberData(nameof(TestInvalidCurves))]
public static void TestCreateKeyFromCngAlgorithmNegative(CurveDef curveDef)
{
CngAlgorithm alg = CngAlgorithm.ECDsa;
Assert.ThrowsAny<Exception>(() => CngKey.Create(alg));
}
[Theory, MemberData(nameof(SpecialNistKeys))]
public static void TestSpecialNistKeys(int keySize, string curveName, CngAlgorithm algorithm)
{
using (ECDsaCng cng = (ECDsaCng)ECDsaFactory.Create(keySize))
{
Assert.Equal(keySize, cng.KeySize);
ECParameters param = cng.ExportParameters(false);
Assert.Equal(curveName, param.Curve.Oid.FriendlyName);
Assert.Equal(algorithm, cng.Key.Algorithm);
}
}
#endif // netcoreapp
public static IEnumerable<object[]> SpecialNistKeys
{
get
{
yield return new object[] { 256, "nistP256", CngAlgorithm.ECDsaP256};
yield return new object[] { 384, "nistP384", CngAlgorithm.ECDsaP384};
yield return new object[] { 521, "nistP521", CngAlgorithm.ECDsaP521};
}
}
private static void VerifyKey(CngKey key)
{
Assert.Equal("ECDSA", key.AlgorithmGroup.AlgorithmGroup);
Assert.False(string.IsNullOrEmpty(key.Algorithm.Algorithm));
Assert.True(key.KeySize > 0);
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.UI;
using NServiceKit.Common.Extensions;
using NServiceKit.Common.Utils;
using NServiceKit.Common.Web;
using NServiceKit.Text;
using NServiceKit.WebHost.Endpoints.Support;
using NServiceKit.WebHost.Endpoints.Support.Metadata.Controls;
using HttpRequestWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpRequestWrapper;
using HttpResponseWrapper = NServiceKit.WebHost.Endpoints.Extensions.HttpResponseWrapper;
namespace NServiceKit.WebHost.Endpoints.Metadata
{
using System.Text;
using ServiceHost;
/// <summary>A base metadata handler.</summary>
public abstract class BaseMetadataHandler : HttpHandlerBase, INServiceKitHttpHandler
{
/// <summary>Gets the format to use.</summary>
///
/// <value>The format.</value>
public abstract Format Format { get; }
/// <summary>Gets or sets the type of the content.</summary>
///
/// <value>The type of the content.</value>
public string ContentType { get; set; }
/// <summary>Gets or sets the content format.</summary>
///
/// <value>The content format.</value>
public string ContentFormat { get; set; }
/// <summary>Executes the given context.</summary>
///
/// <param name="context">The context.</param>
public override void Execute(HttpContext context)
{
var writer = new HtmlTextWriter(context.Response.Output);
context.Response.ContentType = "text/html";
ProcessOperations(writer, new HttpRequestWrapper(GetType().Name, context.Request), new HttpResponseWrapper(context.Response));
}
/// <summary>Process the request.</summary>
///
/// <param name="httpReq"> The HTTP request.</param>
/// <param name="httpRes"> The HTTP resource.</param>
/// <param name="operationName">Name of the operation.</param>
public virtual void ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
{
using (var sw = new StreamWriter(httpRes.OutputStream))
{
var writer = new HtmlTextWriter(sw);
httpRes.ContentType = "text/html";
ProcessOperations(writer, httpReq, httpRes);
}
}
/// <summary>Creates a response.</summary>
///
/// <param name="type">The type.</param>
///
/// <returns>The new response.</returns>
public virtual string CreateResponse(Type type)
{
if (type == typeof(string))
return "(string)";
if (type == typeof(byte[]))
return "(byte[])";
if (type == typeof(Stream))
return "(Stream)";
if (type == typeof(HttpWebResponse))
return "(HttpWebResponse)";
return CreateMessage(type);
}
/// <summary>Process the operations.</summary>
///
/// <param name="writer"> The writer.</param>
/// <param name="httpReq">The HTTP request.</param>
/// <param name="httpRes">The HTTP resource.</param>
protected virtual void ProcessOperations(HtmlTextWriter writer, IHttpRequest httpReq, IHttpResponse httpRes)
{
var operationName = httpReq.QueryString["op"];
if (!AssertAccess(httpReq, httpRes, operationName)) return;
ContentFormat = Common.Web.ContentType.GetContentFormat(Format);
var metadata = EndpointHost.Metadata;
if (operationName != null)
{
var allTypes = metadata.GetAllTypes();
var operationType = allTypes.Single(x => x.Name == operationName);
var op = metadata.GetOperation(operationType);
var requestMessage = CreateResponse(operationType);
string responseMessage = null;
var responseType = metadata.GetResponseTypeByRequest(operationType);
if (responseType != null)
{
responseMessage = CreateResponse(responseType);
}
var isSoap = Format == Format.Soap11 || Format == Format.Soap12;
var sb = new StringBuilder();
var description = operationType.GetDescription();
if (!description.IsNullOrEmpty())
{
sb.AppendFormat("<h3 id='desc'>{0}</div>", ConvertToHtml(description));
}
if (op.Routes.Count > 0)
{
sb.Append("<table>");
if (!isSoap)
{
sb.Append("<caption>The following routes are available for this service:</caption>");
}
sb.Append("<tbody>");
foreach (var route in op.Routes)
{
if (isSoap && !(route.AllowsAllVerbs || route.AllowedVerbs.Contains(HttpMethods.Post)))
continue;
sb.Append("<tr>");
var verbs = route.AllowsAllVerbs ? "All Verbs" : route.AllowedVerbs;
if (!isSoap)
{
var path = "/" + PathUtils.CombinePaths(EndpointHost.Config.NServiceKitHandlerFactoryPath, route.Path);
sb.AppendFormat("<th>{0}</th>", verbs);
sb.AppendFormat("<th>{0}</th>", path);
}
sb.AppendFormat("<td>{0}</td>", route.Summary);
sb.AppendFormat("<td><i>{0}</i></td>", route.Notes);
sb.Append("</tr>");
}
sb.Append("<tbody>");
sb.Append("</tbody>");
sb.Append("</table>");
}
var apiMembers = operationType.GetApiMembers();
if (apiMembers.Count > 0)
{
sb.Append("<table><caption>Parameters:</caption>");
sb.Append("<thead><tr>");
sb.Append("<th>Name</th>");
sb.Append("<th>Parameter</th>");
sb.Append("<th>Data Type</th>");
sb.Append("<th>Required</th>");
sb.Append("<th>Description</th>");
sb.Append("</tr></thead>");
sb.Append("<tbody>");
foreach (var apiMember in apiMembers)
{
sb.Append("<tr>");
sb.AppendFormat("<td>{0}</td>", ConvertToHtml(apiMember.Name));
sb.AppendFormat("<td>{0}</td>", apiMember.ParameterType);
sb.AppendFormat("<td>{0}</td>", apiMember.DataType);
sb.AppendFormat("<td>{0}</td>", apiMember.IsRequired ? "Yes" : "No");
sb.AppendFormat("<td>{0}</td>", apiMember.Description);
sb.Append("</tr>");
}
sb.Append("</tbody>");
sb.Append("</table>");
}
sb.Append(@"<div class=""call-info"">");
var overrideExtCopy = EndpointHost.Config.AllowRouteContentTypeExtensions
? " the <b>.{0}</b> suffix or ".Fmt(ContentFormat)
: "";
sb.AppendFormat(@"<p>To override the Content-type in your clients HTTP <b>Accept</b> Header, append {1} <b>?format={0}</b></p>", ContentFormat, overrideExtCopy);
if (ContentFormat == "json")
{
sb.Append("<p>To embed the response in a <b>jsonp</b> callback, append <b>?callback=myCallback</b></p>");
}
sb.Append("</div>");
RenderOperation(writer, httpReq, operationName, requestMessage, responseMessage, sb.ToString());
return;
}
RenderOperations(writer, httpReq, metadata);
}
private string ConvertToHtml(string text)
{
return text.Replace("<", "<")
.Replace(">", ">")
.Replace("\n", "<br />\n");
}
/// <summary>Assert access.</summary>
///
/// <param name="httpReq"> The HTTP request.</param>
/// <param name="httpRes"> The HTTP resource.</param>
/// <param name="operationName">Name of the operation.</param>
///
/// <returns>true if it succeeds, false if it fails.</returns>
protected bool AssertAccess(IHttpRequest httpReq, IHttpResponse httpRes, string operationName)
{
if (!EndpointHost.Config.HasAccessToMetadata(httpReq, httpRes)) return false;
if (operationName == null) return true; //For non-operation pages we don't need to check further permissions
if (!EndpointHost.Config.EnableAccessRestrictions) return true;
if (!EndpointHost.Config.MetadataPagesConfig.IsVisible(httpReq, Format, operationName))
{
EndpointHost.Config.HandleErrorResponse(httpReq, httpRes, HttpStatusCode.Forbidden, "Service Not Available");
return false;
}
return true;
}
/// <summary>Creates a message.</summary>
///
/// <param name="dtoType">Type of the dto.</param>
///
/// <returns>The new message.</returns>
protected abstract string CreateMessage(Type dtoType);
/// <summary>Renders the operation.</summary>
///
/// <param name="writer"> The writer.</param>
/// <param name="httpReq"> The HTTP request.</param>
/// <param name="operationName"> Name of the operation.</param>
/// <param name="requestMessage"> Message describing the request.</param>
/// <param name="responseMessage">Message describing the response.</param>
/// <param name="metadataHtml"> The metadata HTML.</param>
protected virtual void RenderOperation(HtmlTextWriter writer, IHttpRequest httpReq, string operationName,
string requestMessage, string responseMessage, string metadataHtml)
{
var operationControl = new OperationControl
{
HttpRequest = httpReq,
MetadataConfig = EndpointHost.Config.ServiceEndpointsMetadataConfig,
Title = EndpointHost.Config.ServiceName,
Format = this.Format,
OperationName = operationName,
HostName = httpReq.GetUrlHostName(),
RequestMessage = requestMessage,
ResponseMessage = responseMessage,
MetadataHtml = metadataHtml,
};
if (!this.ContentType.IsNullOrEmpty())
{
operationControl.ContentType = this.ContentType;
}
if (!this.ContentFormat.IsNullOrEmpty())
{
operationControl.ContentFormat = this.ContentFormat;
}
operationControl.Render(writer);
}
/// <summary>Renders the operations.</summary>
///
/// <param name="writer"> The writer.</param>
/// <param name="httpReq"> The HTTP request.</param>
/// <param name="metadata">The metadata.</param>
protected abstract void RenderOperations(HtmlTextWriter writer, IHttpRequest httpReq, ServiceMetadata metadata);
}
}
| |
/*
* Copyright (c) 2009 - 2015 Jim Radford http://www.jimradford.com
* Copyright (c) 2012 John Peterson
* 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.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using log4net;
using System.Diagnostics;
using System.Web;
using System.Collections.Specialized;
using SuperPutty.Data;
using WeifenLuo.WinFormsUI.Docking;
using SuperPutty.Utils;
using System.Threading;
using System.Configuration;
using SuperPutty.Gui;
using log4net.Core;
namespace SuperPutty
{
/// <summary>A control that hosts a putty window</summary>
public partial class ctlPuttyPanel : ToolWindowDocument
{
private static readonly ILog Log = LogManager.GetLogger(typeof(ctlPuttyPanel));
private static int RefocusAttempts = Convert.ToInt32(ConfigurationManager.AppSettings["SuperPuTTY.RefocusAttempts"] ?? "5");
private static int RefocusIntervalMs = Convert.ToInt32(ConfigurationManager.AppSettings["SuperPuTTY.RefocusIntervalMs"] ?? "80");
private PuttyStartInfo m_puttyStartInfo;
private ApplicationPanel m_AppPanel;
private SessionData m_Session;
private PuttyClosedCallback m_ApplicationExit;
public ctlPuttyPanel(SessionData session, PuttyClosedCallback callback)
{
m_Session = session;
m_ApplicationExit = callback;
m_puttyStartInfo = new PuttyStartInfo(session);
InitializeComponent();
this.Text = session.SessionName;
this.TabText = session.SessionName;
this.TextOverride = session.SessionName;
CreatePanel();
AdjustMenu();
}
/// <summary>Gets or sets the text displayed on a tab.</summary>
public override string Text
{
get
{
return base.Text;
}
set
{
this.TabText = value != null ? value.Replace("&", "&&") : null;
base.Text = value;
if (Log.Logger.IsEnabledFor(Level.Trace))
{
Log.DebugFormat("SetText: text={0}", value);
}
}
}
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
this.ToolTipText = this.Text;
}
private void CreatePanel()
{
this.m_AppPanel = new ApplicationPanel();
this.SuspendLayout();
this.m_AppPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_AppPanel.ApplicationName = this.m_puttyStartInfo.Executable;
this.m_AppPanel.ApplicationParameters = this.m_puttyStartInfo.Args;
this.m_AppPanel.ApplicationWorkingDirectory = this.m_puttyStartInfo.WorkingDir;
this.m_AppPanel.Location = new System.Drawing.Point(0, 0);
this.m_AppPanel.Name = this.m_Session.SessionId; // "applicationControl1";
this.m_AppPanel.Size = new System.Drawing.Size(this.Width, this.Height);
this.m_AppPanel.TabIndex = 0;
this.m_AppPanel.m_CloseCallback = this.m_ApplicationExit;
this.Controls.Add(this.m_AppPanel);
this.ResumeLayout();
}
void AdjustMenu()
{
// for mintty, disable the putty menu items
if (this.Session.Proto == ConnectionProtocol.Mintty)
{
this.toolStripPuttySep1.Visible = false;
this.eventLogToolStripMenuItem.Visible = false;
this.toolStripPuttySep2.Visible = false;
this.changeSettingsToolStripMenuItem.Visible = false;
this.copyAllToClipboardToolStripMenuItem.Visible = false;
this.restartSessionToolStripMenuItem.Visible = false;
this.clearScrollbackToolStripMenuItem.Visible = false;
this.resetTerminalToolStripMenuItem.Visible = false;
}
}
void CreateMenu()
{
this.newSessionToolStripMenuItem.Enabled = SuperPuTTY.Settings.PuttyPanelShowNewSessionMenu;
if (SuperPuTTY.Settings.PuttyPanelShowNewSessionMenu)
{
this.contextMenuStrip1.SuspendLayout();
// BBB: do i need to dispose each one?
newSessionToolStripMenuItem.DropDownItems.Clear();
foreach (SessionData session in SuperPuTTY.GetAllSessions())
{
ToolStripMenuItem tsmiParent = newSessionToolStripMenuItem;
foreach (string part in SessionData.GetSessionNameParts(session.SessionId))
{
if (part == session.SessionName)
{
ToolStripMenuItem newSessionTSMI = new ToolStripMenuItem
{
Tag = session,
Text = session.SessionName
};
newSessionTSMI.Click += new System.EventHandler(newSessionTSMI_Click);
newSessionTSMI.ToolTipText = session.ToString();
tsmiParent.DropDownItems.Add(newSessionTSMI);
}
else
{
if (tsmiParent.DropDownItems.ContainsKey(part))
{
tsmiParent = (ToolStripMenuItem)tsmiParent.DropDownItems[part];
}
else
{
ToolStripMenuItem newSessionFolder = new ToolStripMenuItem(part) {Name = part};
tsmiParent.DropDownItems.Add(newSessionFolder);
tsmiParent = newSessionFolder;
}
}
}
}
this.contextMenuStrip1.ResumeLayout();
}
DockPane pane = GetDockPane();
if (pane != null)
{
this.closeOthersToTheRightToolStripMenuItem.Enabled =
pane.Contents.IndexOf(this) != pane.Contents.Count - 1;
}
this.closeOthersToolStripMenuItem.Enabled = this.DockPanel.DocumentsCount > 1;
this.closeAllToolStripMenuItem.Enabled = this.DockPanel.DocumentsCount > 1;
}
private void closeSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void closeOthersToolStripMenuItem_Click(object sender, EventArgs e)
{
var docs = from doc in this.DockPanel.DocumentsToArray()
where doc is ToolWindowDocument && doc != this
select doc as ToolWindowDocument;
CloseDocs("Close Others", docs);
}
private void closeAllToolStripMenuItem_Click(object sender, EventArgs e)
{
var docs = from doc in this.DockPanel.DocumentsToArray()
where doc is ToolWindowDocument
select doc as ToolWindowDocument;
CloseDocs("Close All", docs);
}
private void closeOthersToTheRightToolStripMenuItem_Click(object sender, EventArgs e)
{
// find the dock pane with this window
DockPane pane = GetDockPane();
if (pane != null)
{
// found the pane
List<ToolWindowDocument> docsToClose = new List<ToolWindowDocument>();
bool close = false;
foreach (IDockContent content in new List<IDockContent>(pane.Contents))
{
if (content == this)
{
close = true;
continue;
}
if (close)
{
ToolWindowDocument win = content as ToolWindowDocument;
if (win != null)
{
docsToClose.Add(win);
}
}
}
if (docsToClose.Count > 0)
{
CloseDocs("Close Other To the Right", docsToClose);
}
}
}
void CloseDocs(string source, IEnumerable<ToolWindowDocument> docsToClose)
{
int n = docsToClose.Count();
Log.InfoFormat("Closing mulitple docs: source={0}, count={1}, conf={2}", source, n, SuperPuTTY.Settings.MultipleTabCloseConfirmation);
bool okToClose = true;
if (SuperPuTTY.Settings.MultipleTabCloseConfirmation && n > 1)
{
okToClose = DialogResult.Yes == MessageBox.Show(this, string.Format("Close {0} Tabs?", n), source, MessageBoxButtons.YesNo);
}
if (okToClose)
{
foreach (ToolWindowDocument doc in docsToClose)
{
doc.Close();
}
}
}
DockPane GetDockPane()
{
return this.DockPanel.Panes.FirstOrDefault(pane => pane.Contents.Contains(this));
}
/// <summary>
/// Reset the focus to the child application window
/// </summary>
internal void SetFocusToChildApplication(string caller)
{
if (!this.m_AppPanel.ExternalProcessCaptured) { return; }
bool success = false;
for (int i = 0; i < RefocusAttempts; i++)
{
Thread.Sleep(RefocusIntervalMs);
if (this.m_AppPanel.ReFocusPuTTY(caller))
{
if (i > 0)
{
Log.DebugFormat("SetFocusToChildApplication success after {0} attempts", i + 1);
}
success = true;
break;
}
}
if (!success)
{
Log.WarnFormat("Unable to SetFocusToChildApplication, {0}", this.Text);
}
}
protected override string GetPersistString()
{
string str = String.Format("{0}?SessionId={1}&TabName={2}",
this.GetType().FullName,
HttpUtility.UrlEncodeUnicode(this.m_Session.SessionId),
HttpUtility.UrlEncodeUnicode(this.TextOverride));
return str;
}
/// <summary>Restore sessions from a string containing previous sessions</summary>
/// <param name="persistString">A string containing the sessions to restore</param>
/// <returns>The <seealso cref="ctlPuttyPanel"/> object which is the parent of the hosted putty application, null if unable to start session</returns>
public static ctlPuttyPanel FromPersistString(String persistString)
{
ctlPuttyPanel panel = null;
if (persistString.StartsWith(typeof(ctlPuttyPanel).FullName))
{
int idx = persistString.IndexOf("?");
if (idx != -1)
{
NameValueCollection data = HttpUtility.ParseQueryString(persistString.Substring(idx + 1));
string sessionId = data["SessionId"] ?? data["SessionName"];
string tabName = data["TabName"];
Log.InfoFormat("Restoring putty session, sessionId={0}, tabName={1}", sessionId, tabName);
SessionData session = SuperPuTTY.GetSessionById(sessionId);
if (session != null)
{
panel = SuperPuTTY.OpenPuttySession(session);
if (panel == null)
{
Log.WarnFormat("Could not restore putty session, sessionId={0}", sessionId);
}
else
{
panel.Icon = SuperPuTTY.GetIconForSession(session);
panel.Text = tabName;
panel.TextOverride = tabName;
}
}
else
{
Log.WarnFormat("Session not found, sessionId={0}", sessionId);
}
}
else
{
idx = persistString.IndexOf(":");
if (idx != -1)
{
string sessionId = persistString.Substring(idx + 1);
Log.InfoFormat("Restoring putty session, sessionId={0}", sessionId);
SessionData session = SuperPuTTY.GetSessionById(sessionId);
if (session != null)
{
panel = SuperPuTTY.OpenPuttySession(session);
}
else
{
Log.WarnFormat("Session not found, sessionId={0}", sessionId);
}
}
}
}
return panel;
}
private void aboutPuttyToolStripMenuItem_Click(object sender, EventArgs e)
{
Process.Start("http://www.chiark.greenend.org.uk/~sgtatham/putty/");
}
private void duplicateSessionToolStripMenuItem_Click(object sender, EventArgs e)
{
SuperPuTTY.OpenPuttySession(this.m_Session);
}
private void renameTabToolStripMenuItem_Click(object sender, EventArgs e)
{
dlgRenameItem dialog = new dlgRenameItem
{
ItemName = this.Text,
DetailName = this.m_Session.SessionId
};
if (dialog.ShowDialog(this) == DialogResult.OK)
{
this.Text = dialog.ItemName;
this.TextOverride = dialog.ItemName;
}
}
private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.m_AppPanel != null)
{
this.m_AppPanel.RefreshAppWindow();
}
}
public SessionData Session { get { return this.m_Session; } }
public ApplicationPanel AppPanel { get { return this.m_AppPanel; } }
public ctlPuttyPanel previousPanel { get; set; }
public ctlPuttyPanel nextPanel { get; set; }
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
CreateMenu();
}
private void newSessionTSMI_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem) sender;
SessionData session = menuItem.Tag as SessionData;
if (session != null)
{
SuperPuTTY.OpenPuttySession(session);
}
}
private void puTTYMenuTSMI_Click(object sender, EventArgs e)
{
ToolStripMenuItem menuItem = (ToolStripMenuItem) sender;
string[] tags = ((ToolStripMenuItem)sender).Tag.ToString().Split(';');
uint[] commands = new uint[tags.Length];
for (int i = 0; i < tags.Length; ++i)
{
commands[i] = Convert.ToUInt32(tags[i], 16);
Log.DebugFormat("Sending Putty Command: menu={2}, tag={0}, command={1}", tags[i], commands[i], menuItem.Text);
}
ThreadPool.QueueUserWorkItem(delegate
{
try
{
this.SetFocusToChildApplication("MenuHandler");
for (int i = 0; i < commands.Length; ++i)
{
NativeMethods.SendMessage(m_AppPanel.AppWindowHandle, (uint)NativeMethods.WM.SYSCOMMAND, commands[i], 0);
}
}
catch (Exception ex)
{
Log.ErrorFormat("Error sending command menu command to embedded putty", ex);
}
});
}
public bool AcceptCommands
{
get { return this.acceptCommandsToolStripMenuItem.Checked; }
set { this.acceptCommandsToolStripMenuItem.Checked = value; }
}
public string TextOverride { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using CS2JSWeb.Areas.HelpPage.ModelDescriptions;
using CS2JSWeb.Areas.HelpPage.Models;
namespace CS2JSWeb.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Telegram.Bot.Args;
using Telegram.Bot.Exceptions;
using Telegram.Bot.Requests;
using Telegram.Bot.Requests.Abstractions;
using Telegram.Bot.Types;
using Telegram.Bot.Types.Enums;
using Telegram.Bot.Types.InlineQueryResults;
using Telegram.Bot.Types.InputFiles;
using Telegram.Bot.Types.Payments;
using Telegram.Bot.Types.ReplyMarkups;
using File = Telegram.Bot.Types.File;
namespace Telegram.Bot
{
/// <summary>
/// A client to use the Telegram Bot API
/// </summary>
public class TelegramBotClient : ITelegramBotClient
{
/// <inheritdoc/>
public int BotId { get; }
private static readonly Update[] EmptyUpdates = { };
private const string BaseUrl = "https://api.telegram.org/bot";
private const string BaseFileUrl = "https://api.telegram.org/file/bot";
private readonly string _baseRequestUrl;
private readonly string _token;
private readonly HttpClient _httpClient;
#region Config Properties
/// <summary>
/// Timeout for requests
/// </summary>
public TimeSpan Timeout
{
get => _httpClient.Timeout;
set => _httpClient.Timeout = value;
}
/// <summary>
/// Indicates if receiving updates
/// </summary>
public bool IsReceiving { get; set; }
private CancellationTokenSource _receivingCancellationTokenSource;
/// <summary>
/// The current message offset
/// </summary>
public int MessageOffset { get; set; }
#endregion Config Properties
#region Events
/// <summary>
/// Occurs before sending a request to API
/// </summary>
public event EventHandler<ApiRequestEventArgs> MakingApiRequest;
/// <summary>
/// Occurs after receiving the response to an API request
/// </summary>
public event EventHandler<ApiResponseEventArgs> ApiResponseReceived;
/// <summary>
/// Raises the <see cref="OnUpdate" />, <see cref="OnMessage"/>, <see cref="OnInlineQuery"/>, <see cref="OnInlineResultChosen"/> and <see cref="OnCallbackQuery"/> events.
/// </summary>
/// <param name="e">The <see cref="UpdateEventArgs"/> instance containing the event data.</param>
protected virtual void OnUpdateReceived(UpdateEventArgs e)
{
OnUpdate?.Invoke(this, e);
switch (e.Update.Type)
{
case UpdateType.Message:
OnMessage?.Invoke(this, e);
break;
case UpdateType.InlineQuery:
OnInlineQuery?.Invoke(this, e);
break;
case UpdateType.ChosenInlineResult:
OnInlineResultChosen?.Invoke(this, e);
break;
case UpdateType.CallbackQuery:
OnCallbackQuery?.Invoke(this, e);
break;
case UpdateType.EditedMessage:
OnMessageEdited?.Invoke(this, e);
break;
}
}
/// <summary>
/// Occurs when an <see cref="Update"/> is received.
/// </summary>
public event EventHandler<UpdateEventArgs> OnUpdate;
/// <summary>
/// Occurs when a <see cref="Message"/> is received.
/// </summary>
public event EventHandler<MessageEventArgs> OnMessage;
/// <summary>
/// Occurs when <see cref="Message"/> was edited.
/// </summary>
public event EventHandler<MessageEventArgs> OnMessageEdited;
/// <summary>
/// Occurs when an <see cref="InlineQuery"/> is received.
/// </summary>
public event EventHandler<InlineQueryEventArgs> OnInlineQuery;
/// <summary>
/// Occurs when a <see cref="ChosenInlineResult"/> is received.
/// </summary>
public event EventHandler<ChosenInlineResultEventArgs> OnInlineResultChosen;
/// <summary>
/// Occurs when an <see cref="CallbackQuery"/> is received
/// </summary>
public event EventHandler<CallbackQueryEventArgs> OnCallbackQuery;
/// <summary>
/// Occurs when an error occurs during the background update pooling.
/// </summary>
public event EventHandler<ReceiveErrorEventArgs> OnReceiveError;
/// <summary>
/// Occurs when an error occurs during the background update pooling.
/// </summary>
public event EventHandler<ReceiveGeneralErrorEventArgs> OnReceiveGeneralError;
#endregion
/// <summary>
/// Create a new <see cref="TelegramBotClient"/> instance.
/// </summary>
/// <param name="token">API token</param>
/// <param name="httpClient">A custom <see cref="HttpClient"/></param>
/// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception>
public TelegramBotClient(string token, HttpClient httpClient = null)
{
_token = token ?? throw new ArgumentNullException(nameof(token));
string[] parts = _token.Split(':');
if (parts.Length > 1 && int.TryParse(parts[0], out int id))
{
BotId = id;
}
else
{
throw new ArgumentException(
"Invalid format. A valid token looks like \"1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy\".",
nameof(token)
);
}
_baseRequestUrl = $"{BaseUrl}{_token}/";
_httpClient = httpClient ?? new HttpClient();
}
/// <summary>
/// Create a new <see cref="TelegramBotClient"/> instance behind a proxy.
/// </summary>
/// <param name="token">API token</param>
/// <param name="webProxy">Use this <see cref="IWebProxy"/> to connect to the API</param>
/// <exception cref="ArgumentException">Thrown if <paramref name="token"/> format is invalid</exception>
public TelegramBotClient(string token, IWebProxy webProxy)
{
_token = token ?? throw new ArgumentNullException(nameof(token));
string[] parts = _token.Split(':');
if (int.TryParse(parts[0], out int id))
{
BotId = id;
}
else
{
throw new ArgumentException(
"Invalid format. A valid token looks like \"1234567:4TT8bAc8GHUspu3ERYn-KGcvsvGB9u_n4ddy\".",
nameof(token)
);
}
_baseRequestUrl = $"{BaseUrl}{_token}/";
var httpClientHander = new HttpClientHandler
{
Proxy = webProxy,
UseProxy = true
};
_httpClient = new HttpClient(httpClientHander);
}
#region Helpers
/// <inheritdoc />
public async Task<TResponse> MakeRequestAsync<TResponse>(
IRequest<TResponse> request,
CancellationToken cancellationToken = default)
{
string url = _baseRequestUrl + request.MethodName;
var httpRequest = new HttpRequestMessage(request.Method, url)
{
Content = request.ToHttpContent()
};
var reqDataArgs = new ApiRequestEventArgs
{
MethodName = request.MethodName,
HttpContent = httpRequest.Content,
};
MakingApiRequest?.Invoke(this, reqDataArgs);
HttpResponseMessage httpResponse;
try
{
httpResponse = await _httpClient.SendAsync(httpRequest, cancellationToken)
.ConfigureAwait(false);
}
catch (TaskCanceledException e)
{
if (cancellationToken.IsCancellationRequested)
throw;
throw new ApiRequestException("Request timed out", 408, e);
}
// required since user might be able to set new status code using following event arg
var actualResponseStatusCode = httpResponse.StatusCode;
string responseJson = await httpResponse.Content.ReadAsStringAsync()
.ConfigureAwait(false);
ApiResponseReceived?.Invoke(this, new ApiResponseEventArgs
{
ResponseMessage = httpResponse,
ApiRequestEventArgs = reqDataArgs
});
switch (actualResponseStatusCode)
{
case HttpStatusCode.OK:
break;
case HttpStatusCode.Unauthorized:
case HttpStatusCode.BadRequest when !string.IsNullOrWhiteSpace(responseJson):
case HttpStatusCode.Forbidden when !string.IsNullOrWhiteSpace(responseJson):
case HttpStatusCode.Conflict when !string.IsNullOrWhiteSpace(responseJson):
// Do NOT throw here, an ApiRequestException will be thrown next
break;
default:
httpResponse.EnsureSuccessStatusCode();
break;
}
var apiResponse =
JsonConvert.DeserializeObject<ApiResponse<TResponse>>(responseJson)
?? new ApiResponse<TResponse> // ToDo is required? unit test
{
Ok = false,
Description = "No response received"
};
if (!apiResponse.Ok)
throw ApiExceptionParser.Parse(apiResponse);
return apiResponse.Result;
}
/// <summary>
/// Test the API token
/// </summary>
/// <returns><c>true</c> if token is valid</returns>
public async Task<bool> TestApiAsync(CancellationToken cancellationToken = default)
{
try
{
await GetMeAsync(cancellationToken).ConfigureAwait(false);
return true;
}
catch (ApiRequestException e)
when (e.ErrorCode == 401)
{
return false;
}
}
/// <summary>
/// Start update receiving
/// </summary>
/// <param name="allowedUpdates">List the types of updates you want your bot to receive.</param>
/// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
/// <exception cref="ApiRequestException"> Thrown if token is invalid</exception>
public void StartReceiving(UpdateType[] allowedUpdates = null,
CancellationToken cancellationToken = default)
{
_receivingCancellationTokenSource = new CancellationTokenSource();
cancellationToken.Register(() => _receivingCancellationTokenSource.Cancel());
ReceiveAsync(allowedUpdates, _receivingCancellationTokenSource.Token);
}
#pragma warning disable AsyncFixer03 // Avoid fire & forget async void methods
private async void ReceiveAsync(
UpdateType[] allowedUpdates,
CancellationToken cancellationToken = default)
{
IsReceiving = true;
while (!cancellationToken.IsCancellationRequested)
{
var timeout = Convert.ToInt32(Timeout.TotalSeconds);
var updates = EmptyUpdates;
try
{
updates = await GetUpdatesAsync(
MessageOffset,
timeout: timeout,
allowedUpdates: allowedUpdates,
cancellationToken: cancellationToken
).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (ApiRequestException apiException)
{
OnReceiveError?.Invoke(this, apiException);
}
catch (Exception generalException)
{
OnReceiveGeneralError?.Invoke(this, generalException);
}
try
{
foreach (var update in updates)
{
OnUpdateReceived(new UpdateEventArgs(update));
MessageOffset = update.Id + 1;
}
}
catch
{
IsReceiving = false;
throw;
}
}
IsReceiving = false;
}
#pragma warning restore AsyncFixer03 // Avoid fire & forget async void methods
/// <summary>
/// Stop update receiving
/// </summary>
public void StopReceiving()
{
try
{
_receivingCancellationTokenSource.Cancel();
}
catch (WebException)
{
}
catch (TaskCanceledException)
{
}
}
#endregion Helpers
#region Getting updates
/// <inheritdoc />
public Task<Update[]> GetUpdatesAsync(
int offset = default,
int limit = default,
int timeout = default,
IEnumerable<UpdateType> allowedUpdates = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetUpdatesRequest
{
Offset = offset,
Limit = limit,
Timeout = timeout,
AllowedUpdates = allowedUpdates
}, cancellationToken);
/// <inheritdoc />
public Task SetWebhookAsync(
string url,
InputFileStream certificate = default,
int maxConnections = default,
IEnumerable<UpdateType> allowedUpdates = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetWebhookRequest(url, certificate)
{
MaxConnections = maxConnections,
AllowedUpdates = allowedUpdates
}, cancellationToken);
/// <inheritdoc />
public Task DeleteWebhookAsync(CancellationToken cancellationToken = default)
=> MakeRequestAsync(new DeleteWebhookRequest(), cancellationToken);
/// <inheritdoc />
public Task<WebhookInfo> GetWebhookInfoAsync(CancellationToken cancellationToken = default)
=> MakeRequestAsync(new GetWebhookInfoRequest(), cancellationToken);
#endregion Getting updates
#region Available methods
/// <inheritdoc />
public Task<User> GetMeAsync(CancellationToken cancellationToken = default)
=> MakeRequestAsync(new GetMeRequest(), cancellationToken);
/// <inheritdoc />
public Task<Message> SendTextMessageAsync(
ChatId chatId,
string text,
ParseMode parseMode = default,
bool disableWebPagePreview = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendMessageRequest(chatId, text)
{
ParseMode = parseMode,
DisableWebPagePreview = disableWebPagePreview,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> ForwardMessageAsync(
ChatId chatId,
ChatId fromChatId,
int messageId,
bool disableNotification = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new ForwardMessageRequest(chatId, fromChatId, messageId)
{
DisableNotification = disableNotification
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendPhotoAsync(
ChatId chatId,
InputOnlineFile photo,
string caption = default,
ParseMode parseMode = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendPhotoRequest(chatId, photo)
{
Caption = caption,
ParseMode = parseMode,
ReplyToMessageId = replyToMessageId,
DisableNotification = disableNotification,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendAudioAsync(
ChatId chatId,
InputOnlineFile audio,
string caption = default,
ParseMode parseMode = default,
int duration = default,
string performer = default,
string title = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
InputMedia thumb = default
) =>
MakeRequestAsync(new SendAudioRequest(chatId, audio)
{
Caption = caption,
ParseMode = parseMode,
Duration = duration,
Performer = performer,
Title = title,
Thumb = thumb,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendDocumentAsync(
ChatId chatId,
InputOnlineFile document,
string caption = default,
ParseMode parseMode = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
InputMedia thumb = default
) =>
MakeRequestAsync(new SendDocumentRequest(chatId, document)
{
Caption = caption,
Thumb = thumb,
ParseMode = parseMode,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendStickerAsync(
ChatId chatId,
InputOnlineFile sticker,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendStickerRequest(chatId, sticker)
{
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendVideoAsync(
ChatId chatId,
InputOnlineFile video,
int duration = default,
int width = default,
int height = default,
string caption = default,
ParseMode parseMode = default,
bool supportsStreaming = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
InputMedia thumb = default
) =>
MakeRequestAsync(new SendVideoRequest(chatId, video)
{
Duration = duration,
Width = width,
Height = height,
Thumb = thumb,
Caption = caption,
ParseMode = parseMode,
SupportsStreaming = supportsStreaming,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendAnimationAsync(
ChatId chatId,
InputOnlineFile animation,
int duration = default,
int width = default,
int height = default,
InputMedia thumb = default,
string caption = default,
ParseMode parseMode = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendAnimationRequest(chatId, animation)
{
Duration = duration,
Width = width,
Height = height,
Thumb = thumb,
Caption = caption,
ParseMode = parseMode,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup,
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendVoiceAsync(
ChatId chatId,
InputOnlineFile voice,
string caption = default,
ParseMode parseMode = default,
int duration = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendVoiceRequest(chatId, voice)
{
Caption = caption,
ParseMode = parseMode,
Duration = duration,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendVideoNoteAsync(
ChatId chatId,
InputTelegramFile videoNote,
int duration = default,
int length = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
InputMedia thumb = default
) =>
MakeRequestAsync(new SendVideoNoteRequest(chatId, videoNote)
{
Duration = duration,
Length = length,
Thumb = thumb,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
[Obsolete("Use the other overload of this method instead. Only photo and video input types are allowed.")]
public Task<Message[]> SendMediaGroupAsync(
ChatId chatId,
IEnumerable<InputMediaBase> media,
bool disableNotification = default,
int replyToMessageId = default,
CancellationToken cancellationToken = default
)
{
var inputMedia = media
.Select(m => m as IAlbumInputMedia)
.Where(m => m != null)
.ToArray();
return MakeRequestAsync(new SendMediaGroupRequest(chatId, inputMedia)
{
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
}, cancellationToken);
}
/// <inheritdoc />
public Task<Message[]> SendMediaGroupAsync(
IEnumerable<IAlbumInputMedia> inputMedia,
ChatId chatId,
bool disableNotification = default,
int replyToMessageId = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendMediaGroupRequest(chatId, inputMedia)
{
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendLocationAsync(
ChatId chatId,
float latitude,
float longitude,
int livePeriod = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendLocationRequest(chatId, latitude, longitude)
{
LivePeriod = livePeriod,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendVenueAsync(
ChatId chatId,
float latitude,
float longitude,
string title,
string address,
string foursquareId = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
string foursquareType = default
) =>
MakeRequestAsync(new SendVenueRequest(chatId, latitude, longitude, title, address)
{
FoursquareId = foursquareId,
FoursquareType = foursquareType,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SendContactAsync(
ChatId chatId,
string phoneNumber,
string firstName,
string lastName = default,
bool disableNotification = default,
int replyToMessageId = default,
IReplyMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
string vCard = default
) =>
MakeRequestAsync(new SendContactRequest(chatId, phoneNumber, firstName)
{
LastName = lastName,
Vcard = vCard,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task SendChatActionAsync(
ChatId chatId,
ChatAction chatAction,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendChatActionRequest(chatId, chatAction), cancellationToken);
/// <inheritdoc />
public Task<UserProfilePhotos> GetUserProfilePhotosAsync(
int userId,
int offset = default,
int limit = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetUserProfilePhotosRequest(userId)
{
Offset = offset,
Limit = limit
}, cancellationToken);
/// <inheritdoc />
public Task<File> GetFileAsync(
string fileId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetFileRequest(fileId), cancellationToken);
/// <inheritdoc />
[Obsolete("This method will be removed in next major release. Use its overload instead.")]
public async Task<Stream> DownloadFileAsync(
string filePath,
CancellationToken cancellationToken = default
)
{
var stream = new MemoryStream();
await DownloadFileAsync(filePath, stream, cancellationToken)
.ConfigureAwait(false);
return stream;
}
/// <inheritdoc />
public async Task DownloadFileAsync(
string filePath,
Stream destination,
CancellationToken cancellationToken = default
)
{
if (string.IsNullOrWhiteSpace(filePath) || filePath.Length < 2)
{
throw new ArgumentException("Invalid file path", nameof(filePath));
}
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
var fileUri = new Uri($"{BaseFileUrl}{_token}/{filePath}");
var response = await _httpClient
.GetAsync(fileUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using (response)
{
await response.Content.CopyToAsync(destination)
.ConfigureAwait(false);
}
}
/// <inheritdoc />
public async Task<File> GetInfoAndDownloadFileAsync(
string fileId,
Stream destination,
CancellationToken cancellationToken = default
)
{
var file = await GetFileAsync(fileId, cancellationToken)
.ConfigureAwait(false);
await DownloadFileAsync(file.FilePath, destination, cancellationToken)
.ConfigureAwait(false);
return file;
}
/// <inheritdoc />
public Task KickChatMemberAsync(
ChatId chatId,
int userId,
DateTime untilDate = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new KickChatMemberRequest(chatId, userId)
{
UntilDate = untilDate
}, cancellationToken);
/// <inheritdoc />
public Task LeaveChatAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new LeaveChatRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task UnbanChatMemberAsync(
ChatId chatId,
int userId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new UnbanChatMemberRequest(chatId, userId), cancellationToken);
/// <inheritdoc />
public Task<Chat> GetChatAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetChatRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task<ChatMember[]> GetChatAdministratorsAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetChatAdministratorsRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task<int> GetChatMembersCountAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetChatMembersCountRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task<ChatMember> GetChatMemberAsync(
ChatId chatId,
int userId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetChatMemberRequest(chatId, userId), cancellationToken);
/// <inheritdoc />
public Task AnswerCallbackQueryAsync(
string callbackQueryId,
string text = default,
bool showAlert = default,
string url = default,
int cacheTime = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerCallbackQueryRequest(callbackQueryId)
{
Text = text,
ShowAlert = showAlert,
Url = url,
CacheTime = cacheTime
}, cancellationToken);
/// <inheritdoc />
public Task RestrictChatMemberAsync(
ChatId chatId,
int userId,
DateTime untilDate = default,
bool? canSendMessages = default,
bool? canSendMediaMessages = default,
bool? canSendOtherMessages = default,
bool? canAddWebPagePreviews = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new RestrictChatMemberRequest(chatId, userId)
{
CanSendMessages = canSendMessages,
CanSendMediaMessages = canSendMediaMessages,
CanSendOtherMessages = canSendOtherMessages,
CanAddWebPagePreviews = canAddWebPagePreviews,
UntilDate = untilDate
}, cancellationToken);
/// <inheritdoc />
public Task PromoteChatMemberAsync(
ChatId chatId,
int userId,
bool? canChangeInfo = default,
bool? canPostMessages = default,
bool? canEditMessages = default,
bool? canDeleteMessages = default,
bool? canInviteUsers = default,
bool? canRestrictMembers = default,
bool? canPinMessages = default,
bool? canPromoteMembers = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new PromoteChatMemberRequest(chatId, userId)
{
CanChangeInfo = canChangeInfo,
CanPostMessages = canPostMessages,
CanEditMessages = canEditMessages,
CanDeleteMessages = canDeleteMessages,
CanInviteUsers = canInviteUsers,
CanRestrictMembers = canRestrictMembers,
CanPinMessages = canPinMessages,
CanPromoteMembers = canPromoteMembers
}, cancellationToken);
/// <inheritdoc />
public Task<Message> StopMessageLiveLocationAsync(
ChatId chatId,
int messageId,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new StopMessageLiveLocationRequest(chatId, messageId)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task StopMessageLiveLocationAsync(
string inlineMessageId,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new StopInlineMessageLiveLocationRequest(inlineMessageId)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
#endregion Available methods
#region Updating messages
/// <inheritdoc />
public Task<Message> EditMessageTextAsync(
ChatId chatId,
int messageId,
string text,
ParseMode parseMode = default,
bool disableWebPagePreview = default,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditMessageTextRequest(chatId, messageId, text)
{
ParseMode = parseMode,
DisableWebPagePreview = disableWebPagePreview,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task EditMessageTextAsync(
string inlineMessageId,
string text,
ParseMode parseMode = default,
bool disableWebPagePreview = default,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditInlineMessageTextRequest(inlineMessageId, text)
{
DisableWebPagePreview = disableWebPagePreview,
ReplyMarkup = replyMarkup,
ParseMode = parseMode
}, cancellationToken);
/// <inheritdoc />
public Task<Message> EditMessageCaptionAsync(
ChatId chatId,
int messageId,
string caption,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
ParseMode parseMode = default
) =>
MakeRequestAsync(new EditMessageCaptionRequest(chatId, messageId, caption)
{
ParseMode = parseMode,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task EditMessageCaptionAsync(
string inlineMessageId,
string caption,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default,
ParseMode parseMode = default
) =>
MakeRequestAsync(new EditInlineMessageCaptionRequest(inlineMessageId, caption)
{
ParseMode = parseMode,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> EditMessageMediaAsync(
ChatId chatId,
int messageId,
InputMediaBase media,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditMessageMediaRequest(chatId, messageId, media)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task EditMessageMediaAsync(
string inlineMessageId,
InputMediaBase media,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditInlineMessageMediaRequest(inlineMessageId, media)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> EditMessageReplyMarkupAsync(
ChatId chatId,
int messageId,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(
new EditMessageReplyMarkupRequest(chatId, messageId, replyMarkup),
cancellationToken);
/// <inheritdoc />
public Task EditMessageReplyMarkupAsync(
string inlineMessageId,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(
new EditInlineMessageReplyMarkupRequest(inlineMessageId, replyMarkup),
cancellationToken);
/// <inheritdoc />
public Task<Message> EditMessageLiveLocationAsync(
ChatId chatId,
int messageId,
float latitude,
float longitude,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditMessageLiveLocationRequest(chatId, messageId, latitude, longitude)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task EditMessageLiveLocationAsync(
string inlineMessageId,
float latitude,
float longitude,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new EditInlineMessageLiveLocationRequest(inlineMessageId, latitude, longitude)
{
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task DeleteMessageAsync(
ChatId chatId,
int messageId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new DeleteMessageRequest(chatId, messageId), cancellationToken);
#endregion Updating messages
#region Inline mode
/// <inheritdoc />
public Task AnswerInlineQueryAsync(
string inlineQueryId,
IEnumerable<InlineQueryResultBase> results,
int? cacheTime = default,
bool isPersonal = default,
string nextOffset = default,
string switchPmText = default,
string switchPmParameter = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerInlineQueryRequest(inlineQueryId, results)
{
CacheTime = cacheTime,
IsPersonal = isPersonal,
NextOffset = nextOffset,
SwitchPmText = switchPmText,
SwitchPmParameter = switchPmParameter
}, cancellationToken);
# endregion Inline mode
#region Payments
/// <inheritdoc />
public Task<Message> SendInvoiceAsync(
int chatId,
string title,
string description,
string payload,
string providerToken,
string startParameter,
string currency,
IEnumerable<LabeledPrice> prices,
string providerData = default,
string photoUrl = default,
int photoSize = default,
int photoWidth = default,
int photoHeight = default,
bool needName = default,
bool needPhoneNumber = default,
bool needEmail = default,
bool needShippingAddress = default,
bool isFlexible = default,
bool disableNotification = default,
int replyToMessageId = default,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendInvoiceRequest(
chatId,
title,
description,
payload,
providerToken,
startParameter,
currency,
// ReSharper disable once PossibleMultipleEnumeration
prices
)
{
ProviderData = providerData,
PhotoUrl = photoUrl,
PhotoSize = photoSize,
PhotoWidth = photoWidth,
PhotoHeight = photoHeight,
NeedName = needName,
NeedPhoneNumber = needPhoneNumber,
NeedEmail = needEmail,
NeedShippingAddress = needShippingAddress,
IsFlexible = isFlexible,
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task AnswerShippingQueryAsync(
string shippingQueryId,
IEnumerable<ShippingOption> shippingOptions,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerShippingQueryRequest(shippingQueryId, shippingOptions), cancellationToken);
/// <inheritdoc />
public Task AnswerShippingQueryAsync(
string shippingQueryId,
string errorMessage,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerShippingQueryRequest(shippingQueryId, errorMessage), cancellationToken);
/// <inheritdoc />
public Task AnswerPreCheckoutQueryAsync(
string preCheckoutQueryId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerPreCheckoutQueryRequest(preCheckoutQueryId), cancellationToken);
/// <inheritdoc />
public Task AnswerPreCheckoutQueryAsync(
string preCheckoutQueryId,
string errorMessage,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AnswerPreCheckoutQueryRequest(preCheckoutQueryId, errorMessage), cancellationToken);
#endregion Payments
#region Games
/// <inheritdoc />
public Task<Message> SendGameAsync(
long chatId,
string gameShortName,
bool disableNotification = default,
int replyToMessageId = default,
InlineKeyboardMarkup replyMarkup = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SendGameRequest(chatId, gameShortName)
{
DisableNotification = disableNotification,
ReplyToMessageId = replyToMessageId,
ReplyMarkup = replyMarkup
}, cancellationToken);
/// <inheritdoc />
public Task<Message> SetGameScoreAsync(
int userId,
int score,
long chatId,
int messageId,
bool force = default,
bool disableEditMessage = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetGameScoreRequest(userId, score, chatId, messageId)
{
Force = force,
DisableEditMessage = disableEditMessage
}, cancellationToken);
/// <inheritdoc />
public Task SetGameScoreAsync(
int userId,
int score,
string inlineMessageId,
bool force = default,
bool disableEditMessage = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetInlineGameScoreRequest(userId, score, inlineMessageId)
{
Force = force,
DisableEditMessage = disableEditMessage
}, cancellationToken);
/// <inheritdoc />
public Task<GameHighScore[]> GetGameHighScoresAsync(
int userId,
long chatId,
int messageId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(
new GetGameHighScoresRequest(userId, chatId, messageId),
cancellationToken);
/// <inheritdoc />
public Task<GameHighScore[]> GetGameHighScoresAsync(
int userId,
string inlineMessageId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(
new GetInlineGameHighScoresRequest(userId, inlineMessageId),
cancellationToken);
#endregion Games
#region Group and channel management
/// <inheritdoc />
public Task<string> ExportChatInviteLinkAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new ExportChatInviteLinkRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task SetChatPhotoAsync(
ChatId chatId,
InputFileStream photo,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetChatPhotoRequest(chatId, photo), cancellationToken);
/// <inheritdoc />
public Task DeleteChatPhotoAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new DeleteChatPhotoRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task SetChatTitleAsync(
ChatId chatId,
string title,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetChatTitleRequest(chatId, title), cancellationToken);
/// <inheritdoc />
public Task SetChatDescriptionAsync(
ChatId chatId,
string description = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetChatDescriptionRequest(chatId, description), cancellationToken);
/// <inheritdoc />
public Task PinChatMessageAsync(
ChatId chatId,
int messageId,
bool disableNotification = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new PinChatMessageRequest(chatId, messageId)
{
DisableNotification = disableNotification
}, cancellationToken);
/// <inheritdoc />
public Task UnpinChatMessageAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new UnpinChatMessageRequest(chatId), cancellationToken);
/// <inheritdoc />
public Task SetChatStickerSetAsync(
ChatId chatId,
string stickerSetName,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetChatStickerSetRequest(chatId, stickerSetName), cancellationToken);
/// <inheritdoc />
public Task DeleteChatStickerSetAsync(
ChatId chatId,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new DeleteChatStickerSetRequest(chatId), cancellationToken);
#endregion
#region Stickers
/// <inheritdoc />
public Task<StickerSet> GetStickerSetAsync(
string name,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new GetStickerSetRequest(name), cancellationToken);
/// <inheritdoc />
public Task<File> UploadStickerFileAsync(
int userId,
InputFileStream pngSticker,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new UploadStickerFileRequest(userId, pngSticker), cancellationToken);
/// <inheritdoc />
public Task CreateNewStickerSetAsync(
int userId,
string name,
string title,
InputOnlineFile pngSticker,
string emojis,
bool isMasks = default,
MaskPosition maskPosition = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new CreateNewStickerSetRequest(userId, name, title, pngSticker, emojis)
{
ContainsMasks = isMasks,
MaskPosition = maskPosition
}, cancellationToken);
/// <inheritdoc />
public Task AddStickerToSetAsync(
int userId,
string name,
InputOnlineFile pngSticker,
string emojis,
MaskPosition maskPosition = default,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new AddStickerToSetRequest(userId, name, pngSticker, emojis)
{
MaskPosition = maskPosition
}, cancellationToken);
/// <inheritdoc />
public Task SetStickerPositionInSetAsync(
string sticker,
int position,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new SetStickerPositionInSetRequest(sticker, position), cancellationToken);
/// <inheritdoc />
public Task DeleteStickerFromSetAsync(
string sticker,
CancellationToken cancellationToken = default
) =>
MakeRequestAsync(new DeleteStickerFromSetRequest(sticker), cancellationToken);
#endregion
}
}
| |
// Copyright 2009 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Linq;
using System.Collections.Generic;
using NUnit.Framework;
using DBus;
using DBus.Protocol;
namespace DBus.Tests
{
[TestFixture]
public class SignatureTest
{
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Parse_NullString ()
{
new Signature ((string) null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Parse_NullArray ()
{
new Signature ((DType []) null);
}
[Test]
public void Parse_Empty ()
{
var x = new Signature ("");
Assert.AreEqual (Signature.Empty, x, "#1");
}
[Test]
public void ParseStruct ()
{
var sig = new Signature ("(iu)");
Assert.IsTrue (sig.IsStruct, "#1");
var elements = sig.GetFieldSignatures ().ToArray ();
Assert.AreEqual (2, elements.Length, "#2");
Assert.AreEqual (Signature.Int32Sig, elements [0], "#3");
Assert.AreEqual (Signature.UInt32Sig, elements [1], "#4");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ParseInvalid_TypeCode ()
{
// Use an invalid type code
new Signature ("z");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ParseInvalid_MissingClosingBrace ()
{
// Use an invalid type code
new Signature ("(i");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void ParseInvalid_MissingOpeningBrace ()
{
// Use an invalid type code
new Signature ("i)");
}
[Test]
public void Parse_ArrayOfString ()
{
string sigText = "as";
Signature sig = new Signature (sigText);
Assert.IsTrue (sig.IsArray);
Assert.IsFalse (sig.IsDict);
Assert.IsFalse (sig.IsPrimitive);
}
[Test]
public void Equality ()
{
string sigText = "as";
Signature a = new Signature (sigText);
Signature b = new Signature (sigText);
Assert.IsTrue (a == b);
Assert.IsTrue (a.GetElementSignature () == Signature.StringSig);
Assert.AreEqual (Signature.ArraySig + Signature.StringSig + Signature.Empty, new Signature ("as"));
}
[Test]
public void FixedSize ()
{
Signature sig;
sig = new Signature ("s");
Assert.IsFalse (sig.IsFixedSize);
sig = new Signature ("as");
Assert.IsFalse (sig.IsFixedSize);
sig = new Signature ("u");
Assert.IsTrue (sig.IsFixedSize);
sig = new Signature ("u(ub)");
Assert.IsTrue (sig.IsFixedSize);
sig = new Signature ("u(uvb)");
Assert.IsFalse (sig.IsFixedSize);
}
[Test]
public void CombineSignatures ()
{
var x = Signature.ByteSig + Signature.StringSig;
Assert.AreEqual ("ys", x.Value, "#1");
}
[Test]
public void MakeArray ()
{
var x = Signature.MakeArray (Signature.Int32Sig);
Assert.AreEqual ("ai", x.Value, "#1");
}
[Test]
public void MakeArrayOfStruct ()
{
var type = Signature.MakeStruct (Signature.Int32Sig + Signature.Int32Sig);
var x = Signature.MakeArray (type);
Assert.AreEqual ("a(ii)", x.Value, "#1");
}
[Test]
public void MakeArrayOfArray ()
{
var x = Signature.MakeArray (Signature.Int32Sig);
x = Signature.MakeArray (x);
Assert.AreEqual ("aai", x.Value, "#1");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void MakeArray_NotSingleCompleteType ()
{
Signature.MakeArray (Signature.Int32Sig + Signature.UInt16Sig);
}
[Test]
public void MakeStruct ()
{
// 'r' isn't used, just brackets.
var x = Signature.MakeStruct (Signature.ByteSig + Signature.StringSig);
Assert.AreEqual ("(ys)", x.Value, "#1");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void MakeStruct_Empty ()
{
Signature.MakeStruct (Signature.Empty);
}
[Test]
public void MakeDictionaryEntry ()
{
// Make a valid dictionary entry, should appear as an array of dict_entries
var x = Signature.MakeDictEntry (Signature.StringSig, Signature.Int32Sig);
Assert.AreEqual ("{si}", x.Value, "#1");
}
[Test]
public void MakeDictionary ()
{
// 'r' isn't used, just brackets.
var x = Signature.MakeDict (Signature.StringSig, Signature.Int32Sig);
Assert.AreEqual ("a{si}", x.Value, "#1");
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void MakeDictionary_TwoCompleteTypes_Key ()
{
// They key is not a single complete type
Signature.MakeDictEntry (Signature.StringSig + Signature.Int32Sig, Signature.Int32Sig);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void MakeDictionary_TwoCompleteTypes_Value ()
{
// They value is not a single complete type
Signature.MakeDictEntry (Signature.StringSig, Signature.Int32Sig + Signature.Int32Sig);
}
[Test]
public void ComplexSignatureIsSingleTypeTest ()
{
string sig = "(ssa{i(ss)})";
Assert.IsTrue (new Signature (sig).IsSingleCompleteType);
}
[Test]
public void AssertComplexTypeToTypeTest ()
{
var sig = new Signature ("(ssa{i(ss)})");
Assert.AreEqual (typeof (DBusStruct<string, string, Dictionary<int, DBusStruct<string, string>>>),
sig.ToType ());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Xml.Serialization
{
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using Microsoft.CodeDom;
using Microsoft.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
/// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier"]/*' />
///<internalonly/>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public class CodeIdentifier
{
internal static CodeDomProvider csharp = new CSharpCodeProvider();
internal const int MaxIdentifierLength = 511;
[Obsolete("This class should never get constructed as it contains only static methods.")]
public CodeIdentifier()
{
}
/// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier.MakePascal"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakePascal(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return identifier.ToUpperInvariant();
else if (char.IsLower(identifier[0]))
return char.ToUpperInvariant(identifier[0]).ToString() + identifier.Substring(1);
else
return identifier;
}
/// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier.MakeCamel"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeCamel(string identifier)
{
identifier = MakeValid(identifier);
if (identifier.Length <= 2)
return identifier.ToLowerInvariant();
else if (char.IsUpper(identifier[0]))
return char.ToLowerInvariant(identifier[0]).ToString() + identifier.Substring(1);
else
return identifier;
}
/// <include file='doc\CodeIdentifier.uex' path='docs/doc[@for="CodeIdentifier.MakeValid"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static string MakeValid(string identifier)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < identifier.Length && builder.Length < MaxIdentifierLength; i++)
{
char c = identifier[i];
if (IsValid(c))
{
if (builder.Length == 0 && !IsValidStart(c))
{
builder.Append("Item");
}
builder.Append(c);
}
}
if (builder.Length == 0) return "Item";
return builder.ToString();
}
internal static string MakeValidInternal(string identifier)
{
if (identifier.Length > 30)
{
return "Item";
}
return MakeValid(identifier);
}
private static bool IsValidStart(char c)
{
// the given char is already a valid name character
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
if (!IsValid(c)) throw new ArgumentException(string.Format(ResXml.XmlInternalErrorDetails, "Invalid identifier character " + ((Int16)c).ToString()), "c");
#endif
// First char cannot be a number
//if (Char.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber)
Decimal d;
if (Decimal.TryParse(c.ToString(), out d))
return false;
return true;
}
private static bool IsValid(char c)
{
UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory(c);
//
// each char must be Lu, Ll, Lt, Lm, Lo, Nd, Mn, Mc, Pc
//
switch (uc)
{
case UnicodeCategory.UppercaseLetter: // Lu
case UnicodeCategory.LowercaseLetter: // Ll
case UnicodeCategory.TitlecaseLetter: // Lt
case UnicodeCategory.ModifierLetter: // Lm
case UnicodeCategory.OtherLetter: // Lo
case UnicodeCategory.DecimalDigitNumber: // Nd
case UnicodeCategory.NonSpacingMark: // Mn
case UnicodeCategory.SpacingCombiningMark: // Mc
case UnicodeCategory.ConnectorPunctuation: // Pc
break;
case UnicodeCategory.LetterNumber:
case UnicodeCategory.OtherNumber:
case UnicodeCategory.EnclosingMark:
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
case UnicodeCategory.Control:
case UnicodeCategory.Format:
case UnicodeCategory.Surrogate:
case UnicodeCategory.PrivateUse:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
case UnicodeCategory.MathSymbol:
case UnicodeCategory.CurrencySymbol:
case UnicodeCategory.ModifierSymbol:
case UnicodeCategory.OtherSymbol:
case UnicodeCategory.OtherNotAssigned:
return false;
default:
#if DEBUG
// use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe
throw new ArgumentException(string.Format(ResXml.XmlInternalErrorDetails, "Unhandled category " + uc), "c");
#else
return false;
#endif
}
return true;
}
internal static void CheckValidIdentifier(string ident)
{
if (!CodeGenerator.IsValidLanguageIndependentIdentifier(ident))
throw new ArgumentException(string.Format(ResXml.XmlInvalidIdentifier, ident), "ident");
}
internal static string GetCSharpName(string name)
{
//UNDONE: switch to using CodeDom csharp.GetTypeOutput after they fix the VSWhidbey bug #202199 CodeDom: does not esacpes full names properly
//return GetTypeName(name, csharp);
return EscapeKeywords(name.Replace('+', '.'), csharp);
}
private static int GetCSharpName(Type t, Type[] parameters, int index, StringBuilder sb)
{
if (t.DeclaringType != null && t.DeclaringType != t)
{
index = GetCSharpName(t.DeclaringType, parameters, index, sb);
sb.Append(".");
}
string name = t.Name;
int nameEnd = name.IndexOf('`');
if (nameEnd < 0)
{
nameEnd = name.IndexOf('!');
}
if (nameEnd > 0)
{
EscapeKeywords(name.Substring(0, nameEnd), csharp, sb);
sb.Append("<");
int arguments = Int32.Parse(name.Substring(nameEnd + 1), CultureInfo.InvariantCulture) + index;
for (; index < arguments; index++)
{
sb.Append(GetCSharpName(parameters[index]));
if (index < arguments - 1)
{
sb.Append(",");
}
}
sb.Append(">");
}
else
{
EscapeKeywords(name, csharp, sb);
}
return index;
}
internal static string GetCSharpName(Type t)
{
int rank = 0;
while (t.IsArray)
{
t = t.GetElementType();
rank++;
}
StringBuilder sb = new StringBuilder();
sb.Append("global::");
string ns = t.Namespace;
if (ns != null && ns.Length > 0)
{
string[] parts = ns.Split(new char[] { '.' });
for (int i = 0; i < parts.Length; i++)
{
EscapeKeywords(parts[i], csharp, sb);
sb.Append(".");
}
}
TypeInfo info = t.GetTypeInfo();
Type[] arguments = info.IsGenericType || info.ContainsGenericParameters ? t.GetGenericArguments() : new Type[0];
GetCSharpName(t, arguments, 0, sb);
for (int i = 0; i < rank; i++)
{
sb.Append("[]");
}
return sb.ToString();
}
//UNDONE: switch to using CodeDom csharp.GetTypeOutput after they fix the VSWhidbey bug #202199 CodeDom: does not esacpes full names properly
/*
internal static string GetTypeName(string name, CodeDomProvider codeProvider) {
return codeProvider.GetTypeOutput(new CodeTypeReference(name));
}
*/
private static void EscapeKeywords(string identifier, CodeDomProvider codeProvider, StringBuilder sb)
{
if (identifier == null || identifier.Length == 0)
return;
string originalIdentifier = identifier;
int arrayCount = 0;
while (identifier.EndsWith("[]", StringComparison.Ordinal))
{
arrayCount++;
identifier = identifier.Substring(0, identifier.Length - 2);
}
if (identifier.Length > 0)
{
CheckValidIdentifier(identifier);
identifier = codeProvider.CreateEscapedIdentifier(identifier);
sb.Append(identifier);
}
for (int i = 0; i < arrayCount; i++)
{
sb.Append("[]");
}
}
private static string EscapeKeywords(string identifier, CodeDomProvider codeProvider)
{
if (identifier == null || identifier.Length == 0) return identifier;
string originalIdentifier = identifier;
string[] names = identifier.Split(new char[] { '.', ',', '<', '>' });
StringBuilder sb = new StringBuilder();
int separator = -1;
for (int i = 0; i < names.Length; i++)
{
if (separator >= 0)
{
sb.Append(originalIdentifier.Substring(separator, 1));
}
separator++;
separator += names[i].Length;
string escapedName = names[i].Trim();
EscapeKeywords(escapedName, codeProvider, sb);
}
if (sb.Length != originalIdentifier.Length)
return sb.ToString();
return originalIdentifier;
}
}
}
| |
#region Using
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
#endregion
namespace DSELib.CAPI
{
/// <summary>
/// CAPI-Versions-Klasse
/// </summary>
public class CapiVersion
{
protected uint m_CAPIMajor = 0;
protected uint m_CAPIMinor = 0;
protected uint m_ManufacturerMajor = 0;
protected uint m_ManufacturerMinor = 0;
public CapiVersion(uint liCAPIMajor, uint liCAPIMinor, uint liManufacturerMajor, uint liManufacturerMinor)
{
m_CAPIMajor = liCAPIMajor;
m_CAPIMinor = liCAPIMinor;
m_ManufacturerMajor = liManufacturerMajor;
m_ManufacturerMinor = liManufacturerMinor;
}
public uint CAPIMajor { get { return m_CAPIMajor; } set { m_CAPIMajor = value; } }
public uint CAPIMinor { get { return m_CAPIMinor; } set { m_CAPIMinor = value; } }
public uint ManufacturerMajor { get { return m_ManufacturerMajor; } set { m_ManufacturerMajor = value; } }
public uint ManufacturerMinor { get { return m_ManufacturerMinor; } set { m_ManufacturerMinor = value; } }
}
public class NCCIClass : PLCIClass
{
protected ushort m_NCCI = 0;
public ushort NCCI
{
get { return m_NCCI; }
set { m_NCCI = value; }
}
public override void SetValue(uint liData)
{
m_ControllerType = (ControllerType_Enum)(liData & 64);
m_Controller = (byte)(liData & 63);
m_PLCI = (byte)((liData >> 8) & 0xff);
m_NCCI = (byte)((liData >> (8 + 16)) & 0xffff);
}
public override uint GetValue()
{
return (uint)m_ControllerType + (uint)m_Controller + (uint)(m_PLCI << 8) + (uint)(m_NCCI << (8 + 16));
}
}
public class PLCIClass : ControllerClass
{
protected byte m_PLCI = 0;
public byte PLCI
{
get { return m_PLCI; }
set { m_PLCI = value; }
}
public override void SetValue(uint liData)
{
m_ControllerType = (ControllerType_Enum)(liData & 64);
m_Controller = (byte)(liData & 63);
m_PLCI = (byte)((liData >> 8) & 0xff);
}
public override uint GetValue()
{
return (uint)m_ControllerType + (uint)m_Controller + (uint)(m_PLCI << 8);
}
}
public class ControllerClass
{
protected ControllerType_Enum m_ControllerType = ControllerType_Enum.InternalController;
protected byte m_Controller = 1;
public ControllerType_Enum ControllerType
{
get { return m_ControllerType; }
set { m_ControllerType = value; }
}
public byte Controller
{
get { return m_Controller; }
set
{
if (value == 0)
{
throw new Exception("Controller 0 is reserved from CAPI.");
}
else if (value > 63)
{
throw new Exception("Controller higher than 63 are not allowed from CAPI.");
}
else
{
m_Controller = value;
}
}
}
public virtual void SetValue(uint liData)
{
m_ControllerType = (ControllerType_Enum)(liData & 64);
m_Controller = (byte)(liData & 63);
}
public virtual uint GetValue()
{
return (uint)m_ControllerType + (uint)m_Controller;
}
}
public class CCBSID
{
protected ushort m_ID = 0;
public ushort ID
{
get { return m_ID; }
set { m_ID = value; }
}
public virtual void SetValue(ushort liData)
{
m_ID = (ushort)(liData & 0x7F);
}
public virtual ushort GetValue()
{
return (ushort)(m_ID & 0x7F);
}
}
public class CCBSReference
{
protected ushort m_ID = 0;
public ushort ID
{
get { return m_ID; }
set { m_ID = value; }
}
public bool AllReferences
{
get { return ((m_ID & 0xFF) == 0xFF); }
set
{
if (value)
{
m_ID = 0xFF;
}
else
{
m_ID &= 0x7F;
}
}
}
public virtual void SetValue(ushort liData)
{
m_ID = (ushort)(liData & 0xFF);
}
public virtual ushort GetValue()
{
return (ushort)(m_ID & 0xFF);
}
}
public class CCBSStatusReport
{
protected LineStatus_Enum m_Status = LineStatus_Enum.Busy;
public LineStatus_Enum Status
{
get { return m_Status; }
set { m_Status = value; }
}
public virtual void SetValue(ushort liData)
{
if (liData == 0)
{
m_Status = LineStatus_Enum.Busy;
}
else
{
m_Status = LineStatus_Enum.Free;
}
}
public virtual ushort GetValue()
{
return (ushort)m_Status;
}
}
public class NumberOfMessages
{
protected uint m_Number = 0;
public uint Number
{
get { return m_Number; }
set { m_Number = value; }
}
public bool Suppress
{
get { return ((m_Number & 0xFFFFFFFF) == 0xFFFFFFFF); }
set
{
if (value)
{
m_Number = 0xFFFFFFFF;
}
else
{
m_Number &= 0xFFFF0000;
}
}
}
public virtual void SetValue(uint liData)
{
m_Number = liData;
}
public virtual uint GetValue()
{
return m_Number;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ServiceModel.Description
{
using Microsoft.CodeDom;
using System.Collections.Generic;
using System.Net.Security;
using System.Reflection;
using System.Runtime;
using System.Runtime.Serialization;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.ComponentModel;
using System.Threading.Tasks;
internal enum MessageContractType { None, WrappedMessageContract, BareMessageContract }
internal interface IWrappedBodyTypeGenerator
{
void ValidateForParameterMode(OperationDescription operationDescription);
void AddMemberAttributes(XmlName messageName, MessagePartDescription part, CodeAttributeDeclarationCollection attributesImported, CodeAttributeDeclarationCollection typeAttributes, CodeAttributeDeclarationCollection fieldAttributes);
void AddTypeAttributes(string messageName, string typeNS, CodeAttributeDeclarationCollection typeAttributes, bool isEncoded);
}
internal class OperationGenerator //: IOperationBehavior, IOperationContractGenerationExtension
{
private Dictionary<MessagePartDescription, CodeTypeReference> _parameterTypes;
private Dictionary<MessagePartDescription, CodeAttributeDeclarationCollection> _parameterAttributes;
private Dictionary<MessagePartDescription, string> _specialPartName;
internal OperationGenerator()
{
}
internal Dictionary<MessagePartDescription, CodeAttributeDeclarationCollection> ParameterAttributes
{
get
{
if (_parameterAttributes == null)
_parameterAttributes = new Dictionary<MessagePartDescription, CodeAttributeDeclarationCollection>();
return _parameterAttributes;
}
}
internal Dictionary<MessagePartDescription, CodeTypeReference> ParameterTypes
{
get
{
if (_parameterTypes == null)
_parameterTypes = new Dictionary<MessagePartDescription, CodeTypeReference>();
return _parameterTypes;
}
}
internal Dictionary<MessagePartDescription, string> SpecialPartName
{
get
{
if (_specialPartName == null)
_specialPartName = new Dictionary<MessagePartDescription, string>();
return _specialPartName;
}
}
internal void GenerateOperation(OperationContractGenerationContext context, ref OperationFormatStyle style, bool isEncoded, IWrappedBodyTypeGenerator wrappedBodyTypeGenerator, Dictionary<MessagePartDescription, ICollection<CodeTypeReference>> knownTypes)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("context"));
if (context.Operation == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SRServiceModel.OperationPropertyIsRequiredForAttributeGeneration));
MethodSignatureGenerator methodSignatureGenerator = new MethodSignatureGenerator(this, context, style, isEncoded, wrappedBodyTypeGenerator, knownTypes);
methodSignatureGenerator.GenerateSyncSignature(ref style);
if (context.IsTask)
{
methodSignatureGenerator.GenerateTaskSignature(ref style);
}
if (context.IsAsync)
{
methodSignatureGenerator.GenerateAsyncSignature(ref style);
}
}
internal static CodeAttributeDeclaration GenerateAttributeDeclaration(ServiceContractGenerator generator, Attribute attribute)
{
return CustomAttributeHelper.GenerateAttributeDeclaration(generator, attribute);
}
private class MethodSignatureGenerator
{
private readonly OperationGenerator _parent;
private readonly OperationContractGenerationContext _context;
private readonly OperationFormatStyle _style;
private readonly bool _isEncoded;
private readonly IWrappedBodyTypeGenerator _wrappedBodyTypeGenerator;
private readonly Dictionary<MessagePartDescription, ICollection<CodeTypeReference>> _knownTypes;
private CodeMemberMethod _method;
private CodeMemberMethod _endMethod;
private readonly string _contractName;
private string _defaultName;
private readonly string _contractNS;
private readonly string _defaultNS;
private readonly bool _oneway;
private readonly MessageDescription _request;
private readonly MessageDescription _response;
private bool _isNewRequest;
private bool _isNewResponse;
private bool _isTaskWithOutputParameters;
private MessageContractType _messageContractType;
private IPartCodeGenerator _beginPartCodeGenerator;
private IPartCodeGenerator _endPartCodeGenerator;
internal MethodSignatureGenerator(OperationGenerator parent, OperationContractGenerationContext context, OperationFormatStyle style, bool isEncoded, IWrappedBodyTypeGenerator wrappedBodyTypeGenerator, Dictionary<MessagePartDescription, ICollection<CodeTypeReference>> knownTypes)
{
_parent = parent;
_context = context;
_style = style;
_isEncoded = isEncoded;
_wrappedBodyTypeGenerator = wrappedBodyTypeGenerator;
_knownTypes = knownTypes;
_messageContractType = context.ServiceContractGenerator.OptionsInternal.IsSet(ServiceContractGenerationOptions.TypedMessages) ? MessageContractType.WrappedMessageContract : MessageContractType.None;
_contractName = context.Contract.Contract.CodeName;
_contractNS = context.Operation.DeclaringContract.Namespace;
_defaultNS = (style == OperationFormatStyle.Rpc) ? string.Empty : _contractNS;
_oneway = (context.Operation.IsOneWay);
_request = context.Operation.Messages[0];
_response = _oneway ? null : context.Operation.Messages[1];
_isNewRequest = true;
_isNewResponse = true;
_beginPartCodeGenerator = null;
_endPartCodeGenerator = null;
_isTaskWithOutputParameters = context.IsTask && context.Operation.HasOutputParameters;
Fx.Assert(_oneway == (_response == null), "OperationContractGenerationContext.Operation cannot contain a null response message when the operation is not one-way");
}
internal void GenerateSyncSignature(ref OperationFormatStyle style)
{
_method = _context.SyncMethod;
_endMethod = _context.SyncMethod;
_defaultName = _method.Name;
GenerateOperationSignatures(ref style);
}
internal void GenerateAsyncSignature(ref OperationFormatStyle style)
{
_method = _context.BeginMethod;
_endMethod = _context.EndMethod;
_defaultName = _method.Name.Substring(5);
GenerateOperationSignatures(ref style);
}
private void GenerateOperationSignatures(ref OperationFormatStyle style)
{
if (_messageContractType != MessageContractType.None || this.GenerateTypedMessageForTaskWithOutputParameters())
{
CheckAndSetMessageContractTypeToBare();
this.GenerateTypedMessageOperation(false /*hideFromEditor*/, ref style);
}
else if (!this.TryGenerateParameterizedOperation())
{
this.GenerateTypedMessageOperation(true /*hideFromEditor*/, ref style);
}
}
private bool GenerateTypedMessageForTaskWithOutputParameters()
{
if (_isTaskWithOutputParameters)
{
if (_method == _context.TaskMethod)
{
_method.Comments.Add(new CodeCommentStatement(string.Format(SRServiceModel.SFxCodeGenWarning, SRServiceModel.SFxCannotImportAsParameters_OutputParameterAndTask)));
}
return true;
}
return false;
}
private void CheckAndSetMessageContractTypeToBare()
{
if (_messageContractType == MessageContractType.BareMessageContract)
return;
try
{
_wrappedBodyTypeGenerator.ValidateForParameterMode(_context.Operation);
}
catch (ParameterModeException ex)
{
_messageContractType = ex.MessageContractType;
}
}
private bool TryGenerateParameterizedOperation()
{
CodeParameterDeclarationExpressionCollection methodParameters, endMethodParameters = null;
methodParameters = new CodeParameterDeclarationExpressionCollection(_method.Parameters);
if (_endMethod != null)
endMethodParameters = new CodeParameterDeclarationExpressionCollection(_endMethod.Parameters);
try
{
GenerateParameterizedOperation();
}
catch (ParameterModeException ex)
{
_messageContractType = ex.MessageContractType;
CodeMemberMethod method = _method;
method.Comments.Add(new CodeCommentStatement(string.Format(SRServiceModel.SFxCodeGenWarning, ex.Message)));
method.Parameters.Clear();
method.Parameters.AddRange(methodParameters);
if (_context.IsAsync)
{
CodeMemberMethod endMethod = _endMethod;
endMethod.Parameters.Clear();
endMethod.Parameters.AddRange(endMethodParameters);
}
return false;
}
return true;
}
private void GenerateParameterizedOperation()
{
ParameterizedMessageHelper.ValidateProtectionLevel(this);
CreateOrOverrideActionProperties();
if (this.HasUntypedMessages)
{
if (!this.IsCompletelyUntyped)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_Message, _context.Operation.CodeName)));
CreateUntypedMessages();
}
else
{
ParameterizedMessageHelper.ValidateWrapperSettings(this);
ParameterizedMessageHelper.ValidateNoHeaders(this);
_wrappedBodyTypeGenerator.ValidateForParameterMode(_context.Operation);
ParameterizedMethodGenerator generator = new ParameterizedMethodGenerator(_method, _endMethod);
_beginPartCodeGenerator = generator.InputGenerator;
_endPartCodeGenerator = generator.OutputGenerator;
if (!_oneway && _response.Body.ReturnValue != null)
{
_endMethod.ReturnType = GetParameterType(_response.Body.ReturnValue);
ParameterizedMessageHelper.GenerateMessageParameterAttribute(_response.Body.ReturnValue, _endMethod.ReturnTypeCustomAttributes, TypeLoader.GetReturnValueName(_defaultName), _defaultNS);
AddAdditionalAttributes(_response.Body.ReturnValue, _endMethod.ReturnTypeCustomAttributes, _isEncoded);
}
GenerateMessageBodyParts(false /*generateTypedMessages*/);
}
}
private void GenerateTypedMessageOperation(bool hideFromEditor, ref OperationFormatStyle style)
{
CreateOrOverrideActionProperties();
if (this.HasUntypedMessages)
{
CreateUntypedMessages();
if (this.IsCompletelyUntyped)
return;
}
CodeNamespace ns = _context.ServiceContractGenerator.NamespaceManager.EnsureNamespace(_contractNS);
if (!_request.IsUntypedMessage)
{
CodeTypeReference typedReqMessageRef = GenerateTypedMessageHeaderAndReturnValueParts(ns, _defaultName + "Request", _request, false /*isReply*/, hideFromEditor, ref _isNewRequest, out _beginPartCodeGenerator);
_method.Parameters.Insert(0, new CodeParameterDeclarationExpression(typedReqMessageRef, "request"));
}
if (!_oneway && !_response.IsUntypedMessage)
{
CodeTypeReference typedRespMessageRef = GenerateTypedMessageHeaderAndReturnValueParts(ns, _defaultName + "Response", _response, true /*isReply*/, hideFromEditor, ref _isNewResponse, out _endPartCodeGenerator);
_endMethod.ReturnType = typedRespMessageRef;
}
GenerateMessageBodyParts(true /*generateTypedMessages*/);
if (!_isEncoded)
style = OperationFormatStyle.Document;
}
private CodeTypeReference GenerateTypedMessageHeaderAndReturnValueParts(CodeNamespace ns, string defaultName, MessageDescription message, bool isReply, bool hideFromEditor, ref bool isNewMessage, out IPartCodeGenerator partCodeGenerator)
{
CodeTypeReference typedMessageRef;
if (TypedMessageHelper.FindGeneratedTypedMessage(_context.Contract, message, out typedMessageRef))
{
partCodeGenerator = null;
isNewMessage = false;
}
else
{
UniqueCodeNamespaceScope namespaceScope = new UniqueCodeNamespaceScope(ns);
CodeTypeDeclaration typedMessageDecl = _context.Contract.TypeFactory.CreateClassType();
string messageName = XmlName.IsNullOrEmpty(message.MessageName) ? null : message.MessageName.DecodedName;
typedMessageRef = namespaceScope.AddUnique(typedMessageDecl, messageName, defaultName);
TypedMessageHelper.AddGeneratedTypedMessage(_context.Contract, message, typedMessageRef);
if (_messageContractType == MessageContractType.BareMessageContract && message.Body.WrapperName != null)
WrapTypedMessage(ns, typedMessageDecl.Name, message, isReply, _context.IsInherited, hideFromEditor);
partCodeGenerator = new TypedMessagePartCodeGenerator(typedMessageDecl);
if (hideFromEditor)
{
TypedMessageHelper.AddEditorBrowsableAttribute(typedMessageDecl.CustomAttributes);
}
TypedMessageHelper.GenerateWrapperAttribute(message, partCodeGenerator);
TypedMessageHelper.GenerateProtectionLevelAttribute(message, partCodeGenerator);
foreach (MessageHeaderDescription setting in message.Headers)
GenerateHeaderPart(setting, partCodeGenerator);
if (isReply && message.Body.ReturnValue != null)
{
GenerateBodyPart(0, message.Body.ReturnValue, partCodeGenerator, true, _isEncoded, _defaultNS);
}
}
return typedMessageRef;
}
private bool IsCompletelyUntyped
{
get
{
bool isRequestMessage = _request != null && _request.IsUntypedMessage;
bool isResponseMessage = _response != null && _response.IsUntypedMessage;
if (isRequestMessage && isResponseMessage)
return true;
else if (isResponseMessage && _request == null || IsEmpty(_request))
return true;
else if (isRequestMessage && _response == null || IsEmpty(_response))
return true;
else
return false;
}
}
private bool IsEmpty(MessageDescription message)
{
return (message.Body.Parts.Count == 0 && message.Headers.Count == 0);
}
private bool HasUntypedMessages
{
get
{
bool isRequestMessage = _request != null && _request.IsUntypedMessage;
bool isResponseMessage = _response != null && _response.IsUntypedMessage;
return (isRequestMessage || isResponseMessage);
}
}
private void CreateUntypedMessages()
{
bool isRequestMessage = _request != null && _request.IsUntypedMessage;
bool isResponseMessage = _response != null && _response.IsUntypedMessage;
if (isRequestMessage)
_method.Parameters.Insert(0, new CodeParameterDeclarationExpression(_context.ServiceContractGenerator.GetCodeTypeReference((typeof(Message))), "request"));
if (isResponseMessage)
_endMethod.ReturnType = _context.ServiceContractGenerator.GetCodeTypeReference(typeof(Message));
}
private void CreateOrOverrideActionProperties()
{
if (_request != null)
{
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(
CustomAttributeHelper.FindOrCreateAttributeDeclaration<OperationContractAttribute>(_method.CustomAttributes), OperationContractAttribute.ActionPropertyName, _request.Action);
}
if (_response != null)
{
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(
CustomAttributeHelper.FindOrCreateAttributeDeclaration<OperationContractAttribute>(_method.CustomAttributes), OperationContractAttribute.ReplyActionPropertyName, _response.Action);
}
}
private interface IPartCodeGenerator
{
CodeAttributeDeclarationCollection AddPart(CodeTypeReference type, ref string name);
CodeAttributeDeclarationCollection MessageLevelAttributes { get; }
void EndCodeGeneration();
}
private class ParameterizedMethodGenerator
{
private ParametersPartCodeGenerator _ins;
private ParametersPartCodeGenerator _outs;
private bool _isSync;
internal ParameterizedMethodGenerator(CodeMemberMethod beginMethod, CodeMemberMethod endMethod)
{
_ins = new ParametersPartCodeGenerator(this, beginMethod.Name, beginMethod.Parameters, beginMethod.CustomAttributes, FieldDirection.In);
_outs = new ParametersPartCodeGenerator(this, beginMethod.Name, endMethod.Parameters, beginMethod.CustomAttributes, FieldDirection.Out);
_isSync = (beginMethod == endMethod);
}
internal CodeParameterDeclarationExpression GetOrCreateParameter(CodeTypeReference type, string name, FieldDirection direction, ref int index, out bool createdNew)
{
Fx.Assert(Microsoft.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(name), String.Format(System.Globalization.CultureInfo.InvariantCulture, "Type name '{0}' is not ValidLanguageIndependentIdentifier!", name));
ParametersPartCodeGenerator existingParams = direction != FieldDirection.In ? _ins : _outs;
int i = index;
CodeParameterDeclarationExpression existing = existingParams.GetParameter(name, ref i);
bool isRef = existing != null && existing.Type.BaseType == type.BaseType;
if (isRef)
{
existing.Direction = FieldDirection.Ref;
if (_isSync)
{
index = i + 1;
createdNew = false;
return existing;
}
}
CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression();
paramDecl.Name = name;
paramDecl.Type = type;
paramDecl.Direction = direction;
if (isRef)
paramDecl.Direction = FieldDirection.Ref;
createdNew = true;
return paramDecl;
}
internal IPartCodeGenerator InputGenerator
{
get
{
return _ins;
}
}
internal IPartCodeGenerator OutputGenerator
{
get
{
return _outs;
}
}
private class ParametersPartCodeGenerator : IPartCodeGenerator
{
private ParameterizedMethodGenerator _parent;
private FieldDirection _direction;
private CodeParameterDeclarationExpressionCollection _parameters;
private CodeAttributeDeclarationCollection _messageAttrs;
private string _methodName;
private int _index;
internal ParametersPartCodeGenerator(ParameterizedMethodGenerator parent, string methodName, CodeParameterDeclarationExpressionCollection parameters, CodeAttributeDeclarationCollection messageAttrs, FieldDirection direction)
{
_parent = parent;
_methodName = methodName;
_parameters = parameters;
_messageAttrs = messageAttrs;
_direction = direction;
_index = 0;
}
public bool NameExists(string name)
{
if (String.Compare(name, _methodName, StringComparison.OrdinalIgnoreCase) == 0)
return true;
int index = 0;
return GetParameter(name, ref index) != null;
}
CodeAttributeDeclarationCollection IPartCodeGenerator.AddPart(CodeTypeReference type, ref string name)
{
bool createdNew;
name = UniqueCodeIdentifierScope.MakeValid(name, "param");
CodeParameterDeclarationExpression paramDecl = _parent.GetOrCreateParameter(type, name, _direction, ref _index, out createdNew);
if (createdNew)
{
paramDecl.Name = GetUniqueParameterName(paramDecl.Name, this);
_parameters.Insert(_index++, paramDecl);
}
name = paramDecl.Name;
if (!createdNew)
return null;
return paramDecl.CustomAttributes;
}
internal CodeParameterDeclarationExpression GetParameter(string name, ref int index)
{
for (int i = index; i < _parameters.Count; i++)
{
CodeParameterDeclarationExpression parameter = _parameters[i];
if (String.Compare(parameter.Name, name, StringComparison.OrdinalIgnoreCase) == 0)
{
index = i;
return parameter;
}
}
return null;
}
CodeAttributeDeclarationCollection IPartCodeGenerator.MessageLevelAttributes
{
get
{
return _messageAttrs;
}
}
void IPartCodeGenerator.EndCodeGeneration()
{
}
private static string GetUniqueParameterName(string name, ParametersPartCodeGenerator parameters)
{
return NamingHelper.GetUniqueName(name, DoesParameterNameExist, parameters);
}
private static bool DoesParameterNameExist(string name, object parametersObject)
{
return ((ParametersPartCodeGenerator)parametersObject).NameExists(name);
}
}
}
private class TypedMessagePartCodeGenerator : IPartCodeGenerator
{
private CodeTypeDeclaration _typeDecl;
private UniqueCodeIdentifierScope _memberScope;
internal TypedMessagePartCodeGenerator(CodeTypeDeclaration typeDecl)
{
_typeDecl = typeDecl;
_memberScope = new UniqueCodeIdentifierScope();
_memberScope.AddReserved(typeDecl.Name);
}
CodeAttributeDeclarationCollection IPartCodeGenerator.AddPart(CodeTypeReference type, ref string name)
{
CodeMemberField memberDecl = new CodeMemberField();
memberDecl.Name = name = _memberScope.AddUnique(name, "member");
memberDecl.Type = type;
memberDecl.Attributes = MemberAttributes.Public;
_typeDecl.Members.Add(memberDecl);
return memberDecl.CustomAttributes;
}
CodeAttributeDeclarationCollection IPartCodeGenerator.MessageLevelAttributes
{
get
{
return _typeDecl.CustomAttributes;
}
}
void IPartCodeGenerator.EndCodeGeneration()
{
TypedMessageHelper.GenerateConstructors(_typeDecl);
}
}
private void WrapTypedMessage(CodeNamespace ns, string typeName, MessageDescription messageDescription, bool isReply, bool isInherited, bool hideFromEditor)
{
Fx.Assert(String.IsNullOrEmpty(typeName) || Microsoft.CodeDom.Compiler.CodeGenerator.IsValidLanguageIndependentIdentifier(typeName), String.Format(System.Globalization.CultureInfo.InvariantCulture, "Type name '{0}' is not ValidLanguageIndependentIdentifier!", typeName));
UniqueCodeNamespaceScope namespaceScope = new UniqueCodeNamespaceScope(ns);
CodeTypeDeclaration wrapperTypeDecl = _context.Contract.TypeFactory.CreateClassType();
CodeTypeReference wrapperTypeRef = namespaceScope.AddUnique(wrapperTypeDecl, typeName + "Body", "Body");
if (hideFromEditor)
{
TypedMessageHelper.AddEditorBrowsableAttribute(wrapperTypeDecl.CustomAttributes);
}
string defaultNS = GetWrapperNamespace(messageDescription);
string messageName = XmlName.IsNullOrEmpty(messageDescription.MessageName) ? null : messageDescription.MessageName.DecodedName;
_wrappedBodyTypeGenerator.AddTypeAttributes(messageName, defaultNS, wrapperTypeDecl.CustomAttributes, _isEncoded);
IPartCodeGenerator partGenerator = new TypedMessagePartCodeGenerator(wrapperTypeDecl);
System.Net.Security.ProtectionLevel protectionLevel = System.Net.Security.ProtectionLevel.None;
bool isProtectionLevelSetExplicitly = false;
if (messageDescription.Body.ReturnValue != null)
{
AddWrapperPart(messageDescription.MessageName, _wrappedBodyTypeGenerator, partGenerator, messageDescription.Body.ReturnValue, wrapperTypeDecl.CustomAttributes);
protectionLevel = ProtectionLevelHelper.Max(protectionLevel, messageDescription.Body.ReturnValue.ProtectionLevel);
if (messageDescription.Body.ReturnValue.HasProtectionLevel)
isProtectionLevelSetExplicitly = true;
}
List<CodeTypeReference> wrapperKnownTypes = new List<CodeTypeReference>();
foreach (MessagePartDescription part in messageDescription.Body.Parts)
{
AddWrapperPart(messageDescription.MessageName, _wrappedBodyTypeGenerator, partGenerator, part, wrapperTypeDecl.CustomAttributes);
protectionLevel = ProtectionLevelHelper.Max(protectionLevel, part.ProtectionLevel);
if (part.HasProtectionLevel)
isProtectionLevelSetExplicitly = true;
ICollection<CodeTypeReference> knownTypesForPart = null;
if (_knownTypes != null && _knownTypes.TryGetValue(part, out knownTypesForPart))
{
foreach (CodeTypeReference typeReference in knownTypesForPart)
wrapperKnownTypes.Add(typeReference);
}
}
messageDescription.Body.Parts.Clear();
MessagePartDescription wrapperPart = new MessagePartDescription(messageDescription.Body.WrapperName, messageDescription.Body.WrapperNamespace);
if (_knownTypes != null)
_knownTypes.Add(wrapperPart, wrapperKnownTypes);
if (isProtectionLevelSetExplicitly)
wrapperPart.ProtectionLevel = protectionLevel;
messageDescription.Body.WrapperName = null;
messageDescription.Body.WrapperNamespace = null;
if (isReply)
messageDescription.Body.ReturnValue = wrapperPart;
else
messageDescription.Body.Parts.Add(wrapperPart);
TypedMessageHelper.GenerateConstructors(wrapperTypeDecl);
_parent.ParameterTypes.Add(wrapperPart, wrapperTypeRef);
_parent.SpecialPartName.Add(wrapperPart, "Body");
}
private string GetWrapperNamespace(MessageDescription messageDescription)
{
string defaultNS = _defaultNS;
if (messageDescription.Body.ReturnValue != null)
defaultNS = messageDescription.Body.ReturnValue.Namespace;
else if (messageDescription.Body.Parts.Count > 0)
defaultNS = messageDescription.Body.Parts[0].Namespace;
return defaultNS;
}
private void GenerateMessageBodyParts(bool generateTypedMessages)
{
int order = 0;
if (_isNewRequest)
{
foreach (MessagePartDescription setting in _request.Body.Parts)
GenerateBodyPart(order++, setting, _beginPartCodeGenerator, generateTypedMessages, _isEncoded, _defaultNS);
}
if (!_oneway && _isNewResponse)
{
order = _response.Body.ReturnValue != null ? 1 : 0;
foreach (MessagePartDescription setting in _response.Body.Parts)
GenerateBodyPart(order++, setting, _endPartCodeGenerator, generateTypedMessages, _isEncoded, _defaultNS);
}
if (_isNewRequest)
{
if (_beginPartCodeGenerator != null)
_beginPartCodeGenerator.EndCodeGeneration();
}
if (_isNewResponse)
{
if (_endPartCodeGenerator != null)
_endPartCodeGenerator.EndCodeGeneration();
}
}
private void AddWrapperPart(XmlName messageName, IWrappedBodyTypeGenerator wrappedBodyTypeGenerator, IPartCodeGenerator partGenerator, MessagePartDescription part, CodeAttributeDeclarationCollection typeAttributes)
{
string fieldName = part.CodeName;
CodeTypeReference type;
if (part.Type == typeof(System.IO.Stream))
type = _context.ServiceContractGenerator.GetCodeTypeReference(typeof(byte[]));
else
type = GetParameterType(part);
CodeAttributeDeclarationCollection fieldAttributes = partGenerator.AddPart(type, ref fieldName);
CodeAttributeDeclarationCollection importedAttributes = null;
bool hasAttributes = _parent.ParameterAttributes.TryGetValue(part, out importedAttributes);
wrappedBodyTypeGenerator.AddMemberAttributes(messageName, part, importedAttributes, typeAttributes, fieldAttributes);
_parent.ParameterTypes.Remove(part);
if (hasAttributes)
_parent.ParameterAttributes.Remove(part);
}
private void GenerateBodyPart(int order, MessagePartDescription messagePart, IPartCodeGenerator partCodeGenerator, bool generateTypedMessage, bool isEncoded, string defaultNS)
{
if (!generateTypedMessage) order = -1;
string partName;
if (!_parent.SpecialPartName.TryGetValue(messagePart, out partName))
partName = messagePart.CodeName;
CodeTypeReference partType = GetParameterType(messagePart);
CodeAttributeDeclarationCollection partAttributes = partCodeGenerator.AddPart(partType, ref partName);
if (partAttributes == null)
return;
XmlName xmlPartName = new XmlName(partName);
if (generateTypedMessage)
TypedMessageHelper.GenerateMessageBodyMemberAttribute(order, messagePart, partAttributes, xmlPartName);
else
ParameterizedMessageHelper.GenerateMessageParameterAttribute(messagePart, partAttributes, xmlPartName, defaultNS);
AddAdditionalAttributes(messagePart, partAttributes, generateTypedMessage || isEncoded);
}
private void GenerateHeaderPart(MessageHeaderDescription setting, IPartCodeGenerator parts)
{
string partName;
if (!_parent.SpecialPartName.TryGetValue(setting, out partName))
partName = setting.CodeName;
CodeTypeReference partType = GetParameterType(setting);
CodeAttributeDeclarationCollection partAttributes = parts.AddPart(partType, ref partName);
TypedMessageHelper.GenerateMessageHeaderAttribute(setting, partAttributes, new XmlName(partName));
AddAdditionalAttributes(setting, partAttributes, true /*isAdditionalAttributesAllowed*/);
}
private CodeTypeReference GetParameterType(MessagePartDescription setting)
{
if (setting.Type != null)
return _context.ServiceContractGenerator.GetCodeTypeReference(setting.Type);
else if (_parent._parameterTypes.ContainsKey(setting))
return _parent._parameterTypes[setting];
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(string.Format(SRServiceModel.SfxNoTypeSpecifiedForParameter, setting.Name)));
}
private void AddAdditionalAttributes(MessagePartDescription setting, CodeAttributeDeclarationCollection attributes, bool isAdditionalAttributesAllowed)
{
if (_parent._parameterAttributes != null && _parent._parameterAttributes.ContainsKey(setting))
{
CodeAttributeDeclarationCollection localAttributes = _parent._parameterAttributes[setting];
if (localAttributes != null && localAttributes.Count > 0)
{
if (isAdditionalAttributesAllowed)
attributes.AddRange(localAttributes);
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SfxUseTypedMessageForCustomAttributes, setting.Name, localAttributes[0].AttributeType.BaseType)));
}
}
}
private static class TypedMessageHelper
{
internal static void GenerateProtectionLevelAttribute(MessageDescription message, IPartCodeGenerator partCodeGenerator)
{
CodeAttributeDeclaration messageContractAttr = CustomAttributeHelper.FindOrCreateAttributeDeclaration<MessageContractAttribute>(partCodeGenerator.MessageLevelAttributes);
if (message.HasProtectionLevel)
{
messageContractAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), message.ProtectionLevel.ToString())));
}
}
internal static void GenerateWrapperAttribute(MessageDescription message, IPartCodeGenerator partCodeGenerator)
{
CodeAttributeDeclaration messageContractAttr = CustomAttributeHelper.FindOrCreateAttributeDeclaration<MessageContractAttribute>(partCodeGenerator.MessageLevelAttributes);
if (message.Body.WrapperName != null)
{
// use encoded name to specify exactly what goes on the wire.
messageContractAttr.Arguments.Add(new CodeAttributeArgument("WrapperName",
new CodePrimitiveExpression(NamingHelper.CodeName(message.Body.WrapperName))));
messageContractAttr.Arguments.Add(new CodeAttributeArgument("WrapperNamespace",
new CodePrimitiveExpression(message.Body.WrapperNamespace)));
messageContractAttr.Arguments.Add(new CodeAttributeArgument("IsWrapped",
new CodePrimitiveExpression(true)));
}
else
messageContractAttr.Arguments.Add(new CodeAttributeArgument("IsWrapped",
new CodePrimitiveExpression(false)));
}
internal static void AddEditorBrowsableAttribute(CodeAttributeDeclarationCollection attributes)
{
attributes.Add(ClientClassGenerator.CreateEditorBrowsableAttribute(EditorBrowsableState.Advanced));
}
internal static void AddGeneratedTypedMessage(ServiceContractGenerationContext contract, MessageDescription message, CodeTypeReference codeTypeReference)
{
if (message.XsdTypeName != null && !message.XsdTypeName.IsEmpty)
{
contract.ServiceContractGenerator.GeneratedTypedMessages.Add(message, codeTypeReference);
}
}
internal static bool FindGeneratedTypedMessage(ServiceContractGenerationContext contract, MessageDescription message, out CodeTypeReference codeTypeReference)
{
if (message.XsdTypeName == null || message.XsdTypeName.IsEmpty)
{
codeTypeReference = null;
return false;
}
return contract.ServiceContractGenerator.GeneratedTypedMessages.TryGetValue(message, out codeTypeReference);
}
internal static void GenerateConstructors(CodeTypeDeclaration typeDecl)
{
CodeConstructor defaultCtor = new CodeConstructor();
defaultCtor.Attributes = MemberAttributes.Public;
typeDecl.Members.Add(defaultCtor);
CodeConstructor otherCtor = new CodeConstructor();
otherCtor.Attributes = MemberAttributes.Public;
foreach (CodeTypeMember member in typeDecl.Members)
{
CodeMemberField field = member as CodeMemberField;
if (field == null)
continue;
CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression(field.Type, field.Name);
otherCtor.Parameters.Add(param);
otherCtor.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), field.Name), new CodeArgumentReferenceExpression(param.Name)));
}
if (otherCtor.Parameters.Count > 0)
typeDecl.Members.Add(otherCtor);
}
internal static void GenerateMessageBodyMemberAttribute(int order, MessagePartDescription setting, CodeAttributeDeclarationCollection attributes, XmlName defaultName)
{
GenerateMessageContractMemberAttribute<MessageBodyMemberAttribute>(order, setting, attributes, defaultName);
}
internal static void GenerateMessageHeaderAttribute(MessageHeaderDescription setting, CodeAttributeDeclarationCollection attributes, XmlName defaultName)
{
if (setting.Multiple)
GenerateMessageContractMemberAttribute<MessageHeaderArrayAttribute>(-1, setting, attributes, defaultName);
else
GenerateMessageContractMemberAttribute<MessageHeaderAttribute>(-1, setting, attributes, defaultName);
}
private static void GenerateMessageContractMemberAttribute<T>(int order, MessagePartDescription setting, CodeAttributeDeclarationCollection attrs, XmlName defaultName)
where T : Attribute
{
CodeAttributeDeclaration decl = CustomAttributeHelper.FindOrCreateAttributeDeclaration<T>(attrs);
if (setting.Name != defaultName.EncodedName)
// override name with encoded value specified in wsdl; this only works beacuse
// our Encoding algorithm will leave alredy encoded names untouched
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(decl, MessageContractMemberAttribute.NamePropertyName, setting.Name);
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(decl, MessageContractMemberAttribute.NamespacePropertyName, setting.Namespace);
if (setting.HasProtectionLevel)
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(decl, MessageContractMemberAttribute.ProtectionLevelPropertyName, setting.ProtectionLevel);
if (order >= 0)
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(decl, MessageBodyMemberAttribute.OrderPropertyName, order);
}
}
private static class ParameterizedMessageHelper
{
internal static void GenerateMessageParameterAttribute(MessagePartDescription setting, CodeAttributeDeclarationCollection attributes, XmlName defaultName, string defaultNS)
{
if (setting.Name != defaultName.EncodedName)
{
// override name with encoded value specified in wsdl; this only works beacuse
// our Encoding algorithm will leave alredy encoded names untouched
CustomAttributeHelper.CreateOrOverridePropertyDeclaration(
CustomAttributeHelper.FindOrCreateAttributeDeclaration<MessageParameterAttribute>(attributes), MessageParameterAttribute.NamePropertyName, setting.Name);
}
if (setting.Namespace != defaultNS)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_NamespaceMismatch, setting.Namespace, defaultNS)));
}
internal static void ValidateProtectionLevel(MethodSignatureGenerator parent)
{
if (parent._request != null && parent._request.HasProtectionLevel)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_MessageHasProtectionLevel, parent._request.Action == null ? "" : parent._request.Action)));
}
if (parent._response != null && parent._response.HasProtectionLevel)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_MessageHasProtectionLevel, parent._response.Action == null ? "" : parent._response.Action)));
}
}
internal static void ValidateWrapperSettings(MethodSignatureGenerator parent)
{
if (parent._request.Body.WrapperName == null || (parent._response != null && parent._response.Body.WrapperName == null))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_Bare, parent._context.Operation.CodeName)));
if (!StringEqualOrNull(parent._request.Body.WrapperNamespace, parent._contractNS))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_DifferentWrapperNs, parent._request.MessageName, parent._request.Body.WrapperNamespace, parent._contractNS)));
XmlName defaultName = new XmlName(parent._defaultName);
if (!String.Equals(parent._request.Body.WrapperName, defaultName.EncodedName, StringComparison.Ordinal))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_DifferentWrapperName, parent._request.MessageName, parent._request.Body.WrapperName, defaultName.EncodedName)));
if (parent._response != null)
{
if (!StringEqualOrNull(parent._response.Body.WrapperNamespace, parent._contractNS))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_DifferentWrapperNs, parent._response.MessageName, parent._response.Body.WrapperNamespace, parent._contractNS)));
if (!String.Equals(parent._response.Body.WrapperName, TypeLoader.GetBodyWrapperResponseName(defaultName).EncodedName, StringComparison.Ordinal))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_DifferentWrapperName, parent._response.MessageName, parent._response.Body.WrapperName, defaultName.EncodedName)));
}
}
internal static void ValidateNoHeaders(MethodSignatureGenerator parent)
{
if (parent._request.Headers.Count > 0)
{
if (parent._isEncoded)
{
parent._context.Contract.ServiceContractGenerator.Errors.Add(new MetadataConversionError(string.Format(SRServiceModel.SFxCannotImportAsParameters_HeadersAreIgnoredInEncoded, parent._request.MessageName), true/*isWarning*/));
}
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_HeadersAreUnsupported, parent._request.MessageName)));
}
if (!parent._oneway && parent._response.Headers.Count > 0)
{
if (parent._isEncoded)
parent._context.Contract.ServiceContractGenerator.Errors.Add(new MetadataConversionError(string.Format(SRServiceModel.SFxCannotImportAsParameters_HeadersAreIgnoredInEncoded, parent._response.MessageName), true/*isWarning*/));
else
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ParameterModeException(string.Format(SRServiceModel.SFxCannotImportAsParameters_HeadersAreUnsupported, parent._response.MessageName)));
}
}
private static bool StringEqualOrNull(string overrideValue, string defaultValue)
{
return overrideValue == null || String.Equals(overrideValue, defaultValue, StringComparison.Ordinal);
}
}
internal void GenerateTaskSignature(ref OperationFormatStyle style)
{
_method = _context.TaskMethod;
_endMethod = _context.TaskMethod;
_defaultName = _context.SyncMethod.Name;
GenerateOperationSignatures(ref style);
CodeTypeReference resultType = _method.ReturnType;
CodeTypeReference taskReturnType;
if (resultType.BaseType == ServiceReflector.VoidType.FullName)
{
taskReturnType = new CodeTypeReference(ServiceReflector.taskType);
}
else
{
taskReturnType = new CodeTypeReference(_context.ServiceContractGenerator.GetCodeTypeReference(ServiceReflector.taskTResultType).BaseType, resultType);
}
_method.ReturnType = taskReturnType;
}
}
private static class CustomAttributeHelper
{
internal static void CreateOrOverridePropertyDeclaration<V>(CodeAttributeDeclaration attribute, string propertyName, V value)
{
SecurityAttributeGenerationHelper.CreateOrOverridePropertyDeclaration<V>(attribute, propertyName, value);
}
internal static CodeAttributeDeclaration FindOrCreateAttributeDeclaration<T>(CodeAttributeDeclarationCollection attributes)
where T : Attribute
{
return SecurityAttributeGenerationHelper.FindOrCreateAttributeDeclaration<T>(attributes);
}
internal static CodeAttributeDeclaration GenerateAttributeDeclaration(ServiceContractGenerator generator, Attribute attribute)
{
Type attributeType = attribute.GetType();
Attribute defaultAttribute = (Attribute)Activator.CreateInstance(attributeType);
MemberInfo[] publicMembers = attributeType.GetMembers(BindingFlags.Instance | BindingFlags.Public);
Array.Sort<MemberInfo>(publicMembers,
delegate (MemberInfo a, MemberInfo b)
{
return String.Compare(a.Name, b.Name, StringComparison.Ordinal);
}
);
// we should create this reference through ServiceContractGenerator, which tracks referenced assemblies
CodeAttributeDeclaration attr = new CodeAttributeDeclaration(generator.GetCodeTypeReference(attributeType));
foreach (MemberInfo member in publicMembers)
{
if (member.DeclaringType == typeof(Attribute))
continue;
FieldInfo field = member as FieldInfo;
if (field != null)
{
object fieldValue = field.GetValue(attribute);
object defaultValue = field.GetValue(defaultAttribute);
if (!object.Equals(fieldValue, defaultValue))
attr.Arguments.Add(new CodeAttributeArgument(field.Name, GetArgValue(fieldValue)));
continue;
}
PropertyInfo property = member as PropertyInfo;
if (property != null)
{
object propertyValue = property.GetValue(attribute, null);
object defaultValue = property.GetValue(defaultAttribute, null);
if (!object.Equals(propertyValue, defaultValue))
attr.Arguments.Add(new CodeAttributeArgument(property.Name, GetArgValue(propertyValue)));
continue;
}
}
return attr;
}
private static CodeExpression GetArgValue(object val)
{
Type type = val.GetType();
TypeInfo info = type.GetTypeInfo();
if (info.IsPrimitive || type == typeof(string))
return new CodePrimitiveExpression(val);
if (info.IsEnum)
return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(type), Enum.Format(type, val, "G"));
Fx.Assert(String.Format(System.Globalization.CultureInfo.InvariantCulture, "Attribute generation is not supported for argument type {0}", type));
return null;
}
}
}
internal class ParameterModeException : Exception
{
private MessageContractType _messageContractType = MessageContractType.WrappedMessageContract;
public ParameterModeException() { }
public ParameterModeException(string message) : base(message) { }
public MessageContractType MessageContractType
{
get { return _messageContractType; }
set { _messageContractType = value; }
}
}
}
| |
#region License
/*
* Copyright 2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#region Imports
using NUnit.Framework;
using Solenoid.Expressions.Support.Collections;
#endregion
namespace Solenoid.Expressions.Tests.Collections
{
/// <summary>
/// <b>Base</b> class for tests on the <see cref="ISet"/>
/// interface.
/// </summary>
/// <remarks>
/// <p>
/// This defines a set of tests that exercise the contract of the set interface.
/// Subclasses need only supply a concrete ISET imnplementation instance... this
/// instance must be set on the Set property exposed by this class in the
/// SetUp method. The Set instance must be empty for the start of each new test.
/// </p>
/// <p>
/// The SetForSetOps needs to be set during the SetUp method too.
/// </p>
/// </remarks>
/// <author>Rick Evans</author>
public abstract class SetTests
{
protected static readonly object StuffOne = "This Is";
protected static readonly object StuffTwo = "Uncle";
protected static readonly object StuffThree = "Bob";
protected readonly object [] UniqueStuff = new object [] {StuffOne, StuffTwo, StuffThree};
protected readonly object [] DuplicatedStuff = new object [] {StuffOne, StuffTwo, StuffTwo};
/// <summary>
/// The setup logic executed before the execution of each individual test.
/// </summary>
public abstract void SetUp ();
/// <summary>
/// The tear down logic executed after the execution of each individual test.
/// </summary>
[TearDown]
public virtual void TearDown () {
Set = null;
SetForSetOps = null;
}
[Test]
public void Union()
{
Set.AddAll (UniqueStuff);
SetForSetOps.AddAll (new object [] {"Bar", StuffOne});
ISet union = Set.Union (SetForSetOps);
Assert.IsTrue (union.Count == UniqueStuff.Length + 1);
Assert.IsFalse (object.ReferenceEquals (union, Set), "Got back same instance after set operation.");
Assert.IsTrue (Set.Count == UniqueStuff.Length);
Assert.IsTrue (SetForSetOps.Count == 2);
}
[Test]
public void Intersect()
{
Set.AddAll (UniqueStuff);
SetForSetOps.AddAll (new object [] {"Bar", StuffOne});
ISet intersection = Set.Intersect (SetForSetOps);
Assert.IsTrue (intersection.Count == 1);
Assert.IsFalse (object.ReferenceEquals (intersection, Set), "Got back same instance after set operation.");
Assert.IsTrue (Set.Count == UniqueStuff.Length);
Assert.IsTrue (SetForSetOps.Count == 2);
}
[Test]
public void Minus()
{
Set.AddAll (UniqueStuff);
SetForSetOps.AddAll (new object [] {"Bar", StuffOne});
ISet minus = Set.Minus (SetForSetOps);
Assert.IsTrue (minus.Count == UniqueStuff.Length - 1);
Assert.IsFalse (object.ReferenceEquals (minus, Set), "Got back same instance after set operation.");
Assert.IsTrue (Set.Count == UniqueStuff.Length);
Assert.IsTrue (SetForSetOps.Count == 2);
}
[Test]
public void ExclusiveOr()
{
Set.AddAll (UniqueStuff);
SetForSetOps.AddAll (new object [] {"Bar", StuffOne});
ISet xor = Set.ExclusiveOr (SetForSetOps);
Assert.IsTrue (xor.Count == 3);
Assert.IsTrue (xor.ContainsAll (new object [] {"Bar", StuffTwo, StuffThree}));
Assert.IsFalse (object.ReferenceEquals (xor, Set), "Got back same instance after set operation.");
Assert.IsTrue (Set.Count == UniqueStuff.Length);
Assert.IsTrue (SetForSetOps.Count == 2);
}
[Test]
public void Contains()
{
Set.AddAll (UniqueStuff);
Assert.IsTrue (Set.Contains (StuffThree));
Assert.IsFalse (Set.Contains ("SourDough"));
}
[Test]
public void ContainsAll()
{
Set.AddAll (UniqueStuff);
Assert.IsTrue (Set.ContainsAll (new object [] {StuffThree, StuffTwo, StuffOne}));
}
[Test]
public void IsEmpty ()
{
Set.Add (StuffOne);
Set.Remove (StuffOne);
Assert.IsTrue (Set.IsEmpty);
}
[Test]
public void Add()
{
Assert.IsTrue (Set.Add (StuffOne));
Assert.IsTrue (Set.Count == 1, "Added 1 unique item, but the Count property wasn't sitting at 1.");
}
[Test]
public void AddNull()
{
if (SupportsNull)
{
Assert.IsTrue (Set.Add (StuffOne));
Assert.IsTrue (Set.Add (null));
Assert.IsTrue (Set.Count == 2, "Added 2 unique item (one null), but the Count property wasn't sitting at 2.");
Assert.IsFalse (Set.Add (null));
Assert.IsTrue (Set.Count == 2, "Added null to a set already containing null, but the Count property changed.");
}
}
[Test]
public void EnumeratesNull()
{
if (SupportsNull)
{
Set.AddAll (new object [] {StuffOne, null, StuffTwo});
bool gotNull = false;
foreach (object o in Set)
{
if (o == null)
{
gotNull = true;
break;
}
}
Assert.IsTrue (gotNull, "Stuffed a null value into the set but didn't get it back when enumerating over the set.");
}
}
[Test]
public void CopiesNull ()
{
if (SupportsNull)
{
object [] expected = new object [] {StuffOne, null, StuffTwo};
Set.AddAll (expected);
object [] actual = new object [expected.Length];
Set.CopyTo (actual, 0);
bool gotNull = false;
foreach (object o in actual)
{
if (o == null)
{
gotNull = true;
break;
}
}
Assert.IsTrue (gotNull, "Copied a set with a null value into an array, but the resulting array did not contain a a null.");
}
}
[Test]
public void AddDuplicate()
{
Set.Add (StuffOne);
Assert.IsFalse (Set.Add (StuffOne));
Assert.IsTrue (Set.Count == 1, "Added 2 duplicate items, but the Count property wasn't sitting at 1.");
}
[Test]
public void AddAll()
{
Assert.IsTrue (Set.AddAll (UniqueStuff));
Assert.IsTrue (Set.Count == UniqueStuff.Length, "Added 3 unique items, but the Count property wasn't sitting at 3.");
}
[Test]
public void AddAllDuplicated()
{
Assert.IsTrue (Set.AddAll (DuplicatedStuff));
Assert.IsTrue (Set.Count == 2, "Added 3 (2 duplicated) items, but the Count property wasn't sitting at 2.");
}
[Test]
public void Remove()
{
Set.AddAll (UniqueStuff);
Set.Remove (StuffOne);
Assert.IsTrue (Set.Count == (UniqueStuff.Length - 1));
Assert.IsFalse (Set.Contains (StuffOne));
Assert.IsTrue (Set.Contains (StuffTwo));
Assert.IsTrue (Set.Contains (StuffThree));
}
[Test]
public void RemoveNull()
{
if (SupportsNull)
{
Set.AddAll (UniqueStuff);
Assert.IsFalse (Set.Remove (null));
Set.Add (null);
Assert.IsTrue (Set.Remove (null));
}
}
[Test]
public void RemoveAll()
{
Set.AddAll (UniqueStuff);
object [] removed = new object [] {StuffOne, StuffTwo};
Set.RemoveAll (removed);
Assert.IsTrue (Set.Count == (UniqueStuff.Length - removed.Length));
Assert.IsFalse (Set.Contains (StuffOne));
Assert.IsFalse (Set.Contains (StuffTwo));
Assert.IsTrue (Set.Contains (StuffThree));
}
[Test]
public void RetainAll()
{
Set.AddAll (UniqueStuff);
Set.RetainAll (new object [] {StuffOne, StuffTwo});
Assert.IsTrue (Set.Count == 2);
Assert.IsTrue (Set.Contains (StuffOne));
Assert.IsTrue (Set.Contains (StuffTwo));
Assert.IsFalse (Set.Contains (StuffThree));
}
[Test]
public void Clear()
{
Set.AddAll (UniqueStuff);
Set.Clear ();
Assert.IsTrue (Set.Count == 0, "Calling Clear () did not remove all of the elements.");
}
/// <summary>
/// The ISet being tested.
/// </summary>
protected virtual ISet Set
{
get
{
return _set;
}
set
{
_set = value;
}
}
/// <summary>
/// An extra ISet instance for use during the set operation tests.
/// </summary>
protected virtual ISet SetForSetOps
{
get
{
return _setForSetOps;
}
set
{
_setForSetOps = value;
}
}
/// <summary>
/// Does the Set being tested support the addition of null values?
/// </summary>
/// <remarks>
/// <p>
/// If true, then the tests that test the handling of the null value
/// will be executed.
/// </p>
/// </remarks>
protected bool SupportsNull
{
get
{
return _setSupportsNullValue;
}
set
{
_setSupportsNullValue = value;
}
}
private ISet _set;
private ISet _setForSetOps;
private bool _setSupportsNullValue = true;
}
}
| |
// -*- Mode: csharp; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*-
//
// System.Collections.ObjectModel.ReadOnlyCollection
//
// Author:
// Zoltan Varga ([email protected])
// David Waite ([email protected])
//
// (C) 2005 Novell, Inc.
// (C) 2005 David Waite
//
//
// Copyright (C) 2005 Novell, Inc (http://www.novell.com)
// Copyright (C) 2005 David Waite
//
// 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.Collections.ObjectModel;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerDisplay ("Count={Count}")]
public class ReadOnlyCollection <T> : IList <T>, ICollection <T>, IEnumerable <T>, IList, ICollection, IEnumerable
{
IList <T> list;
public ReadOnlyCollection (IList <T> list)
{
if (list == null)
throw new ArgumentNullException ("list");
this.list = list;
}
void ICollection<T>.Add (T item)
{
throw new NotSupportedException ();
}
void ICollection<T>.Clear ()
{
throw new NotSupportedException ();
}
public bool Contains (T value)
{
return list.Contains (value);
}
public void CopyTo (T [] array, int index)
{
list.CopyTo (array, index);
}
public IEnumerator <T> GetEnumerator ()
{
return list.GetEnumerator ();
}
public int IndexOf (T value)
{
return list.IndexOf (value);
}
void IList<T>.Insert (int index, T item)
{
throw new NotSupportedException ();
}
bool ICollection<T>.Remove (T item)
{
throw new NotSupportedException ();
}
void IList<T>.RemoveAt (int index)
{
throw new NotSupportedException ();
}
public int Count {
get { return list.Count; }
}
protected IList<T> Items {
get { return list; }
}
public T this [int index] {
get { return list [index]; }
}
T IList<T>.this [int index] {
get { return this [index]; }
set { throw new NotSupportedException (); }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
internal static bool IsValidItem(object item)
{
bool arg_29_0;
if (item is T)
{
arg_29_0 = true;
}
else
{
arg_29_0 = ((item != null) ? false : (!typeof(T).IsValueType));
}
return arg_29_0;
}
#region Not generic interface implementations
void ICollection.CopyTo (Array array, int index)
{
((ICollection)list).CopyTo (array, index);
}
IEnumerator IEnumerable.GetEnumerator ()
{
return ((IEnumerable) list).GetEnumerator ();
}
int IList.Add (object value)
{
throw new NotSupportedException ();
}
void IList.Clear ()
{
throw new NotSupportedException ();
}
bool IList.Contains (object value)
{
if (ReadOnlyCollection<T>.IsValidItem(value))
return list.Contains ((T) value);
return false;
}
int IList.IndexOf (object value)
{
if (ReadOnlyCollection<T>.IsValidItem(value))
return list.IndexOf ((T) value);
return -1;
}
void IList.Insert (int index, object value)
{
throw new NotSupportedException ();
}
void IList.Remove (object value)
{
throw new NotSupportedException ();
}
void IList.RemoveAt (int index)
{
throw new NotSupportedException ();
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return this; }
}
bool IList.IsFixedSize {
get { return true; }
}
bool IList.IsReadOnly {
get { return true; }
}
object IList.this [int index] {
get { return list [index]; }
set { throw new NotSupportedException (); }
}
#endregion
}
}
namespace Antlr3.Runtime.PCL
{
public static class ListExtensions
{
public static ReadOnlyCollection<T> AsReadOnly<T>(this List<T> list)
{
return new ReadOnlyCollection<T>(list);
}
}
}
| |
using System;
namespace BizHawk.Emulation.Common.Components.MC6809
{
public partial class MC6809
{
public ulong TotalExecutedCycles;
// variables for executing instructions
public int instr_pntr = 0;
public ushort[] cur_instr = new ushort[60];
public int opcode_see;
public int IRQS;
public int irq_pntr;
ushort reg_d_ad;
ushort reg_h_ad;
ushort reg_l_ad;
public void FetchInstruction(byte opcode)
{
opcode_see = opcode;
switch (opcode)
{
case 0x00: DIRECT_MEM(NEG); break; // NEG (Direct)
case 0x01: ILLEGAL(); break; // ILLEGAL
case 0x02: ILLEGAL(); break; // ILLEGAL
case 0x03: DIRECT_MEM(COM); break; // COM (Direct)
case 0x04: DIRECT_MEM(LSR); break; // LSR (Direct)
case 0x05: ILLEGAL(); break; // ILLEGAL
case 0x06: DIRECT_MEM(ROR); break; // ROR (Direct)
case 0x07: DIRECT_MEM(ASR); break; // ASR (Direct)
case 0x08: DIRECT_MEM(ASL); break; // ASL , LSL (Direct)
case 0x09: DIRECT_MEM(ROL); break; // ROL (Direct)
case 0x0A: DIRECT_MEM(DEC8); break; // DEC (Direct)
case 0x0B: ILLEGAL(); break; // ILLEGAL
case 0x0C: DIRECT_MEM(INC8); break; // INC (Direct)
case 0x0D: DIRECT_MEM(TST); break; // TST (Direct)
case 0x0E: JMP_DIR_(); break; // JMP (Direct)
case 0x0F: DIRECT_MEM(CLR); break; // CLR (Direct)
case 0x10: PAGE_2(); break; // Page 2
case 0x11: PAGE_3(); break; // Page 3
case 0x12: NOP_(); break; // NOP (Inherent)
case 0x13: SYNC_(); break; // SYNC (Inherent)
case 0x14: ILLEGAL(); break; // ILLEGAL
case 0x15: ILLEGAL(); break; // ILLEGAL
case 0x16: LBR_(true); break; // LBRA (Relative)
case 0x17: LBSR_(); break; // LBSR (Relative)
case 0x18: ILLEGAL(); break; // ILLEGAL
case 0x19: REG_OP(DA, A); break; // DAA (Inherent)
case 0x1A: REG_OP_IMD_CC(OR8); break; // ORCC (Immediate)
case 0x1B: ILLEGAL(); break; // ILLEGAL
case 0x1C: REG_OP_IMD_CC(AND8); break; // ANDCC (Immediate)
case 0x1D: REG_OP(SEX, A); break; // SEX (Inherent)
case 0x1E: EXG_(); break; // EXG (Immediate)
case 0x1F: TFR_(); break; // TFR (Immediate)
case 0x20: BR_(true); break; // BRA (Relative)
case 0x21: BR_(false); break; // BRN (Relative)
case 0x22: BR_(!(FlagC | FlagZ)); break; // BHI (Relative)
case 0x23: BR_(FlagC | FlagZ); break; // BLS (Relative)
case 0x24: BR_(!FlagC); break; // BHS , BCC (Relative)
case 0x25: BR_(FlagC); break; // BLO , BCS (Relative)
case 0x26: BR_(!FlagZ); break; // BNE (Relative)
case 0x27: BR_(FlagZ); break; // BEQ (Relative)
case 0x28: BR_(!FlagV); break; // BVC (Relative)
case 0x29: BR_(FlagV); break; // BVS (Relative)
case 0x2A: BR_(!FlagN); break; // BPL (Relative)
case 0x2B: BR_(FlagN); break; // BMI (Relative)
case 0x2C: BR_(FlagN == FlagV); break; // BGE (Relative)
case 0x2D: BR_(FlagN ^ FlagV); break; // BLT (Relative)
case 0x2E: BR_((!FlagZ) & (FlagN == FlagV)); break; // BGT (Relative)
case 0x2F: BR_(FlagZ | (FlagN ^ FlagV)); break; // BLE (Relative)
case 0x30: INDEX_OP(LEAX); break; // LEAX (Indexed)
case 0x31: INDEX_OP(LEAY); break; // LEAY (Indexed)
case 0x32: INDEX_OP(LEAS); break; // LEAS (Indexed)
case 0x33: INDEX_OP(LEAU); break; // LEAU (Indexed)
case 0x34: PSH(SP); break; // PSHS (Immediate)
case 0x35: PUL(SP); break; // PULS (Immediate)
case 0x36: PSH(US); break; // PSHU (Immediate)
case 0x37: PUL(US); break; // PULU (Immediate)
case 0x38: ILLEGAL(); break; // ILLEGAL
case 0x39: RTS(); break; // RTS (Inherent)
case 0x3A: ABX_(); break; // ABX (Inherent)
case 0x3B: RTI(); break; // RTI (Inherent)
case 0x3C: CWAI_(); break; // CWAI (Inherent)
case 0x3D: MUL_(); break; // MUL (Inherent)
case 0x3E: ILLEGAL(); break; // ILLEGAL
case 0x3F: SWI1(); break; // SWI (Inherent)
case 0x40: REG_OP(NEG, A); break; // NEGA (Inherent)
case 0x41: ILLEGAL(); break; // ILLEGAL
case 0x42: ILLEGAL(); break; // ILLEGAL
case 0x43: REG_OP(COM, A); break; // COMA (Inherent)
case 0x44: REG_OP(LSR, A); break; // LSRA (Inherent)
case 0x45: ILLEGAL(); break; // ILLEGAL
case 0x46: REG_OP(ROR, A); break; // RORA (Inherent)
case 0x47: REG_OP(ASR, A); break; // ASRA (Inherent)
case 0x48: REG_OP(ASL, A); break; // ASLA , LSLA (Inherent)
case 0x49: REG_OP(ROL, A); break; // ROLA (Inherent)
case 0x4A: REG_OP(DEC8, A); break; // DECA (Inherent)
case 0x4B: ILLEGAL(); break; // ILLEGAL
case 0x4C: REG_OP(INC8, A); break; // INCA (Inherent)
case 0x4D: REG_OP(TST, A); break; // TSTA (Inherent)
case 0x4E: ILLEGAL(); break; // ILLEGAL
case 0x4F: REG_OP(CLR, A); break; // CLRA (Inherent)
case 0x50: REG_OP(NEG, B); break; // NEGB (Inherent)
case 0x51: ILLEGAL(); break; // ILLEGAL
case 0x52: ILLEGAL(); break; // ILLEGAL
case 0x53: REG_OP(COM, B); break; // COMB (Inherent)
case 0x54: REG_OP(LSR, B); break; // LSRB (Inherent)
case 0x55: ILLEGAL(); break; // ILLEGAL
case 0x56: REG_OP(ROR, B); break; // RORB (Inherent)
case 0x57: REG_OP(ASR, B); break; // ASRB (Inherent)
case 0x58: REG_OP(ASL, B); break; // ASLB , LSLB (Inherent)
case 0x59: REG_OP(ROL, B); break; // ROLB (Inherent)
case 0x5A: REG_OP(DEC8, B); break; // DECB (Inherent)
case 0x5B: ILLEGAL(); break; // ILLEGAL
case 0x5C: REG_OP(INC8, B); break; // INCB (Inherent)
case 0x5D: REG_OP(TST, B); break; // TSTB (Inherent)
case 0x5E: ILLEGAL(); break; // ILLEGAL
case 0x5F: REG_OP(CLR, B); break; // CLRB (Inherent)
case 0x60: INDEX_OP(I_NEG); break; // NEG (Indexed)
case 0x61: ILLEGAL(); break; // ILLEGAL
case 0x62: ILLEGAL(); break; // ILLEGAL
case 0x63: INDEX_OP(I_COM); break; // COM (Indexed)
case 0x64: INDEX_OP(I_LSR); break; // LSR (Indexed)
case 0x65: ILLEGAL(); break; // ILLEGAL
case 0x66: INDEX_OP(I_ROR); break; // ROR (Indexed)
case 0x67: INDEX_OP(I_ASR); break; // ASR (Indexed)
case 0x68: INDEX_OP(I_ASL); break; // ASL , LSL (Indexed)
case 0x69: INDEX_OP(I_ROL); break; // ROL (Indexed)
case 0x6A: INDEX_OP(I_DEC); break; // DEC (Indexed)
case 0x6B: ILLEGAL(); break; // ILLEGAL
case 0x6C: INDEX_OP(I_INC); break; // INC (Indexed)
case 0x6D: INDEX_OP(I_TST); break; // TST (Indexed)
case 0x6E: INDEX_OP(I_JMP); break; // JMP (Indexed)
case 0x6F: INDEX_OP(I_CLR); break; // CLR (Indexed)
case 0x70: EXT_MEM(NEG); break; // NEG (Extended)
case 0x71: ILLEGAL(); break; // ILLEGAL
case 0x72: ILLEGAL(); break; // ILLEGAL
case 0x73: EXT_MEM(COM); break; // COM (Extended)
case 0x74: EXT_MEM(LSR); break; // LSR (Extended)
case 0x75: ILLEGAL(); break; // ILLEGAL
case 0x76: EXT_MEM(ROR); break; // ROR (Extended)
case 0x77: EXT_MEM(ASR); break; // ASR (Extended)
case 0x78: EXT_MEM(ASL); break; // ASL , LSL (Extended)
case 0x79: EXT_MEM(ROL); break; // ROL (Extended)
case 0x7A: EXT_MEM(DEC8); break; // DEC (Extended)
case 0x7B: ILLEGAL(); break; // ILLEGAL
case 0x7C: EXT_MEM(INC8); break; // INC (Extended)
case 0x7D: EXT_MEM(TST); break; // TST (Extended)
case 0x7E: JMP_EXT_(); break; // JMP (Extended)
case 0x7F: EXT_MEM(CLR); break; // CLR (Extended)
case 0x80: REG_OP_IMD(SUB8, A); break; // SUBA (Immediate)
case 0x81: REG_OP_IMD(CMP8, A); break; // CMPA (Immediate)
case 0x82: REG_OP_IMD(SBC8, A); break; // SBCA (Immediate)
case 0x83: IMD_OP_D(SUB16, D); break; // SUBD (Immediate)
case 0x84: REG_OP_IMD(AND8, A); break; // ANDA (Immediate)
case 0x85: REG_OP_IMD(BIT, A); break; // BITA (Immediate)
case 0x86: REG_OP_IMD(LD_8, A); break; // LDA (Immediate)
case 0x87: ILLEGAL(); break; // ILLEGAL
case 0x88: REG_OP_IMD(XOR8, A); break; // EORA (Immediate)
case 0x89: REG_OP_IMD(ADC8, A); break; // ADCA (Immediate)
case 0x8A: REG_OP_IMD(OR8, A); break; // ORA (Immediate)
case 0x8B: REG_OP_IMD(ADD8, A); break; // ADDA (Immediate)
case 0x8C: IMD_CMP_16(CMP16, X); break; // CMPX (Immediate)
case 0x8D: BSR_(); break; // BSR (Relative)
case 0x8E: REG_OP_LD_16(X); break; // LDX (Immediate)
case 0x8F: ILLEGAL(); break; // ILLEGAL
case 0x90: DIRECT_MEM_4(SUB8, A); break; // SUBA (Direct)
case 0x91: DIRECT_MEM_4(CMP8, A); break; // CMPA (Direct)
case 0x92: DIRECT_MEM_4(SBC8, A); break; // SBCA (Direct)
case 0x93: DIR_OP_D(SUB16, D); break; // SUBD (Direct)
case 0x94: DIRECT_MEM_4(AND8, A); break; // ANDA (Direct)
case 0x95: DIRECT_MEM_4(BIT, A); break; // BITA (Direct)
case 0x96: DIRECT_MEM_4(LD_8, A); break; // LDA (Direct)
case 0x97: DIRECT_ST_4(A); break; // STA (Direct)
case 0x98: DIRECT_MEM_4(XOR8, A); break; // EORA (Direct)
case 0x99: DIRECT_MEM_4(ADC8, A); break; // ADCA (Direct)
case 0x9A: DIRECT_MEM_4(OR8, A); break; // ORA (Direct)
case 0x9B: DIRECT_MEM_4(ADD8, A); break; // ADDA (Direct)
case 0x9C: DIR_CMP_16(CMP16, X); break; // CMPX (Direct)
case 0x9D: JSR_(); break; // JSR (Direct)
case 0x9E: DIR_OP_LD_16(X); break; // LDX (Direct)
case 0x9F: DIR_OP_ST_16(X); break; // STX (Direct)
case 0xA0: INDEX_OP_REG(I_SUB, A); break; // SUBA (Indexed)
case 0xA1: INDEX_OP_REG(I_CMP, A); break; // CMPA (Indexed)
case 0xA2: INDEX_OP_REG(I_SBC, A); break; // SBCA (Indexed)
case 0xA3: INDEX_OP_REG(I_SUBD, D); break; // SUBD (Indexed)
case 0xA4: INDEX_OP_REG(I_AND, A); break; // ANDA (Indexed)
case 0xA5: INDEX_OP_REG(I_BIT, A); break; // BITA (Indexed)
case 0xA6: INDEX_OP_REG(I_LD, A); break; // LDA (Indexed)
case 0xA7: INDEX_OP_REG(I_ST, A); break; // STA (Indexed)
case 0xA8: INDEX_OP_REG(I_XOR, A); break; // EORA (Indexed)
case 0xA9: INDEX_OP_REG(I_ADC, A); break; // ADCA (Indexed)
case 0xAA: INDEX_OP_REG(I_OR, A); break; // ORA (Indexed)
case 0xAB: INDEX_OP_REG(I_ADD, A); break; // ADDA (Indexed)
case 0xAC: INDEX_OP_REG(I_CMP16, X); break; // CMPX (Indexed)
case 0xAD: INDEX_OP(I_JSR); break; // JSR (Indexed)
case 0xAE: INDEX_OP_REG(I_LD16, X); break; // LDX (Indexed)
case 0xAF: INDEX_OP_REG(I_ST16, X); break; // STX (Indexed)
case 0xB0: EXT_REG(SUB8, A); break; // SUBA (Extended)
case 0xB1: EXT_REG(CMP8, A); break; // CMPA (Extended)
case 0xB2: EXT_REG(SBC8, A); break; // SBCA (Extended)
case 0xB3: EXT_OP_D(SUB16, D); break; // SUBD (Extended)
case 0xB4: EXT_REG(AND8, A); break; // ANDA (Extended)
case 0xB5: EXT_REG(BIT, A); break; // BITA (Extended)
case 0xB6: EXT_REG(LD_8, A); break; // LDA (Extended)
case 0xB7: EXT_ST(A); break; // STA (Extended)
case 0xB8: EXT_REG(XOR8, A); break; // EORA (Extended)
case 0xB9: EXT_REG(ADC8, A); break; // ADCA (Extended)
case 0xBA: EXT_REG(OR8, A); break; // ORA (Extended)
case 0xBB: EXT_REG(ADD8, A); break; // ADDA (Extended)
case 0xBC: EXT_CMP_16(CMP16, X); break; // CMPX (Extended)
case 0xBD: JSR_EXT(); break; // JSR (Extended)
case 0xBE: EXT_OP_LD_16(X); break; // LDX (Extended)
case 0xBF: EXT_OP_ST_16(X); break; // STX (Extended)
case 0xC0: REG_OP_IMD(SUB8, B); break; // SUBB (Immediate)
case 0xC1: REG_OP_IMD(CMP8, B); break; // CMPB (Immediate)
case 0xC2: REG_OP_IMD(SBC8, B); break; // SBCB (Immediate)
case 0xC3: IMD_OP_D(ADD16, D); break; // ADDD (Immediate)
case 0xC4: REG_OP_IMD(AND8, B); break; // ANDB (Immediate)
case 0xC5: REG_OP_IMD(BIT, B); break; // BITB (Immediate)
case 0xC6: REG_OP_IMD(LD_8, B); break; // LDB (Immediate)
case 0xC7: ILLEGAL(); break; // ILLEGAL
case 0xC8: REG_OP_IMD(XOR8, B); break; // EORB (Immediate)
case 0xC9: REG_OP_IMD(ADC8, B); break; // ADCB (Immediate)
case 0xCA: REG_OP_IMD(OR8, B); break; // ORB (Immediate)
case 0xCB: REG_OP_IMD(ADD8, B); break; // ADDB (Immediate)
case 0xCC: REG_OP_LD_16D(); break; // LDD (Immediate)
case 0xCD: ILLEGAL(); break; // ILLEGAL
case 0xCE: REG_OP_LD_16(US); break; // LDU (Immediate)
case 0xCF: ILLEGAL(); break; // ILLEGAL
case 0xD0: DIRECT_MEM_4(SUB8, B); break; // SUBB (Direct)
case 0xD1: DIRECT_MEM_4(CMP8, B); break; // CMPB (Direct)
case 0xD2: DIRECT_MEM_4(SBC8, B); break; // SBCB (Direct)
case 0xD3: DIR_OP_D(ADD16, D); break; // ADDD (Direct)
case 0xD4: DIRECT_MEM_4(AND8, B); break; // ANDB (Direct)
case 0xD5: DIRECT_MEM_4(BIT, B); break; // BITB (Direct)
case 0xD6: DIRECT_MEM_4(LD_8, B); break; // LDB (Direct)
case 0xD7: DIRECT_ST_4(B); break; // STB (Direct)
case 0xD8: DIRECT_MEM_4(XOR8, B); break; // EORB (Direct)
case 0xD9: DIRECT_MEM_4(ADC8, B); break; // ADCB (Direct)
case 0xDA: DIRECT_MEM_4(OR8, B); break; // ORB (Direct)
case 0xDB: DIRECT_MEM_4(ADD8, B); break; // ADDB (Direct)
case 0xDC: DIR_OP_LD_16D(); break; // LDD (Direct)
case 0xDD: DIR_OP_ST_16D(); break; // STD (Direct)
case 0xDE: DIR_OP_LD_16(US); break; // LDU (Direct)
case 0xDF: DIR_OP_ST_16(US); break; // STU (Direct)
case 0xE0: INDEX_OP_REG(I_SUB, B); break; // SUBB (Indexed)
case 0xE1: INDEX_OP_REG(I_CMP, B); break; // CMPB (Indexed)
case 0xE2: INDEX_OP_REG(I_SBC, B); break; // SBCB (Indexed)
case 0xE3: INDEX_OP_REG(I_ADDD, D); break; // ADDD (Indexed)
case 0xE4: INDEX_OP_REG(I_AND, B); break; // ANDB (Indexed)
case 0xE5: INDEX_OP_REG(I_BIT, B); break; // BITB (Indexed)
case 0xE6: INDEX_OP_REG(I_LD, B); break; // LDB (Indexed)
case 0xE7: INDEX_OP_REG(I_ST, B); break; // STB (Indexed)
case 0xE8: INDEX_OP_REG(I_XOR, B); break; // EORB (Indexed)
case 0xE9: INDEX_OP_REG(I_ADC, B); break; // ADCB (Indexed)
case 0xEA: INDEX_OP_REG(I_OR, B); break; // ORB (Indexed)
case 0xEB: INDEX_OP_REG(I_ADD, B); break; // ADDB (Indexed)
case 0xEC: INDEX_OP_REG(I_LD16D, D); break; // LDD (Indexed)
case 0xED: INDEX_OP_REG(I_ST16D, D); break; // STD (Indexed)
case 0xEE: INDEX_OP_REG(I_LD16, US); break; // LDU (Indexed)
case 0xEF: INDEX_OP_REG(I_ST16, US); break; // STU (Indexed)
case 0xF0: EXT_REG(SUB8, B); break; // SUBB (Extended)
case 0xF1: EXT_REG(CMP8, B); break; // CMPB (Extended)
case 0xF2: EXT_REG(SBC8, B); break; // SBCB (Extended)
case 0xF3: EXT_OP_D(ADD16, D); break; // ADDD (Extended)
case 0xF4: EXT_REG(AND8, B); break; // ANDB (Extended)
case 0xF5: EXT_REG(BIT, B); break; // BITB (Extended)
case 0xF6: EXT_REG(LD_8, B); break; // LDB (Extended)
case 0xF7: EXT_ST(B); break; // STB (Extended)
case 0xF8: EXT_REG(XOR8, B); break; // EORB (Extended)
case 0xF9: EXT_REG(ADC8, B); break; // ADCB (Extended)
case 0xFA: EXT_REG(OR8, B); break; // ORB (Extended)
case 0xFB: EXT_REG(ADD8, B); break; // ADDB (Extended)
case 0xFC: EXT_OP_LD_16D(); break; // LDD (Extended)
case 0xFD: EXT_OP_ST_16D(); break; // STD (Extended)
case 0xFE: EXT_OP_LD_16(US); break; // LDU (Extended)
case 0xFF: EXT_OP_ST_16(US); break; // STU (Extended)
}
}
public void FetchInstruction2(byte opcode)
{
opcode_see = opcode;
switch (opcode)
{
case 0x21: LBR_(false); break; // BRN (Relative)
case 0x22: LBR_(!(FlagC | FlagZ)); break; // BHI (Relative)
case 0x23: LBR_(FlagC | FlagZ); break; // BLS (Relative)
case 0x24: LBR_(!FlagC); break; // BHS , BCC (Relative)
case 0x25: LBR_(FlagC); break; // BLO , BCS (Relative)
case 0x26: LBR_(!FlagZ); break; // BNE (Relative)
case 0x27: LBR_(FlagZ); break; // BEQ (Relative)
case 0x28: LBR_(!FlagV); break; // BVC (Relative)
case 0x29: LBR_(FlagV); break; // BVS (Relative)
case 0x2A: LBR_(!FlagN); break; // BPL (Relative)
case 0x2B: LBR_(FlagN); break; // BMI (Relative)
case 0x2C: LBR_(FlagN == FlagV); break; // BGE (Relative)
case 0x2D: LBR_(FlagN ^ FlagV); break; // BLT (Relative)
case 0x2E: LBR_((!FlagZ) & (FlagN == FlagV)); break; // BGT (Relative)
case 0x2F: LBR_(FlagZ | (FlagN ^ FlagV)); break; // BLE (Relative)
case 0x3F: SWI2_3(2); break; // SWI2 (Inherent)
case 0x83: IMD_OP_D(CMP16D, D); break; // CMPD (Immediate)
case 0x8C: IMD_CMP_16(CMP16, Y); break; // CMPY (Immediate)
case 0x8E: REG_OP_LD_16(Y); break; // LDY (Immediate)
case 0x93: DIR_OP_D(CMP16D, D); break; // CMPD (Direct)
case 0x9C: DIR_CMP_16(CMP16, Y); break; // CMPY (Direct)
case 0x9E: DIR_OP_LD_16(Y); break; // LDY (Direct)
case 0x9F: DIR_OP_ST_16(Y); break; // STY (Direct)
case 0xA3: INDEX_OP_REG(I_CMP16D, D); break; // CMPD (Indexed)
case 0xAC: INDEX_OP_REG(I_CMP16, Y); break; // CMPY (Indexed)
case 0xAE: INDEX_OP_REG(I_LD16, Y); break; // LDY (Indexed)
case 0xAF: INDEX_OP_REG(I_ST16, Y); break; // STY (Indexed)
case 0xB3: EXT_OP_D(CMP16D, D); break; // CMPD (Extended)
case 0xBC: EXT_CMP_16(CMP16, Y); break; // CMPY (Extended)
case 0xBE: EXT_OP_LD_16(Y); break; // LDY (Extended)
case 0xBF: EXT_OP_ST_16(Y); break; // STY (Extended)
case 0xCE: REG_OP_LD_16(SP); break; // LDS (Immediate)
case 0xDE: DIR_OP_LD_16(SP); break; // LDS (Direct)
case 0xDF: DIR_OP_ST_16(SP); break; // STS (Direct)
case 0xEE: INDEX_OP_REG(I_LD16, SP); break; // LDS (Indexed)
case 0xEF: INDEX_OP_REG(I_ST16, SP); break; // STS (Indexed)
case 0xFE: EXT_OP_LD_16(SP); break; // LDS (Extended)
case 0xFF: EXT_OP_ST_16(SP); break; // STS (Extended)
default: ILLEGAL(); break;
}
}
public void FetchInstruction3(byte opcode)
{
opcode_see = opcode;
switch (opcode)
{
case 0x3F: SWI2_3(3); break; // SWI3 (Inherent)
case 0x83: IMD_CMP_16(CMP16, US); break; // CMPU (Immediate)
case 0x8C: IMD_CMP_16(CMP16, SP); break; // CMPS (Immediate)
case 0x93: DIR_CMP_16(CMP16, US); break; // CMPU (Direct)
case 0x9C: DIR_CMP_16(CMP16, SP); break; // CMPS (Direct)
case 0xA3: INDEX_OP_REG(I_CMP16, US); break; // CMPU (Indexed)
case 0xAC: INDEX_OP_REG(I_CMP16, SP); break; // CMPS (Indexed)
case 0xB3: EXT_CMP_16(CMP16, US); break; // CMPU (Extended)
case 0xBC: EXT_CMP_16(CMP16, SP); break; // CMPS (Extended)
default: ILLEGAL(); break;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using CocosSharp;
using CocosDenshion;
using System.Diagnostics;
namespace tests
{
public class CocosDenshionTest : CCLayer
{
static readonly string EFFECT_FILE = "Sounds/effect1";
static readonly string MUSIC_FILE = "Sounds/background";
const int LINE_SPACE = 40;
CCMenu testMenu;
List<CCMenuItem> testMenuItems;
CCPoint beginPos;
int soundId;
#region Constructors
public CocosDenshionTest()
{
testMenu = null;
beginPos = new CCPoint(0,0);
soundId = 0;
string[] testItems = {
"Play background music",
"Stop background music",
"Pause background music",
"Resume background music",
"Rewind background music",
"Is background music playing",
"Play effect",
"Play effect repeatly",
"Stop effect",
"Unload effect",
"Add background music volume",
"Sub background music volume",
"Add effects volume",
"Sub effects volume"
};
testMenu = new CCMenu(null);
testMenuItems = new List<CCMenuItem>();
for(int i=0; i < testItems.Count(); ++i)
{
CCLabelTtf label = new CCLabelTtf(testItems[i], "arial", 24);
CCMenuItemLabelTTF menuItem = new CCMenuItemLabelTTF(label, MenuCallback);
testMenu.AddChild(menuItem, i + 10000);
testMenuItems.Add(menuItem);
}
AddChild(testMenu);
// preload background music and effect
CCSimpleAudioEngine.SharedEngine.PreloadBackgroundMusic(CCFileUtils.FullPathFromRelativePath(MUSIC_FILE));
CCSimpleAudioEngine.SharedEngine.PreloadEffect(CCFileUtils.FullPathFromRelativePath(EFFECT_FILE));
// set default volume
CCSimpleAudioEngine.SharedEngine.EffectsVolume = 0.5f;
CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume = 0.5f;
Camera = AppDelegate.SharedCamera;
}
#endregion Constructors
#region Setup content
public override void OnEnter()
{
base.OnEnter(); CCSize windowSize = Layer.VisibleBoundsWorldspace.Size;
// Layout content
int testCount = testMenuItems.Count();
testMenu.ContentSize = new CCSize(windowSize.Width, (testCount + 1) * LINE_SPACE);
testMenu.Position = new CCPoint(0,0);
for(int i=0; i < testCount; ++i)
{
testMenuItems[i].Position
= new CCPoint( windowSize.Width / 2, (windowSize.Height - (i + 1) * LINE_SPACE));
}
// Register touch events
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesBegan = OnTouchesBegan;
touchListener.OnTouchesMoved = OnTouchesMoved;
AddEventListener(touchListener);
}
#endregion Setup content
public override void OnExit()
{
base.OnExit();
CCSimpleAudioEngine.SharedEngine.End();
}
public void MenuCallback(object sender)
{
// get the userdata, it's the index of the menu item clicked
CCMenuItem menuItem = (CCMenuItem)(sender);
int nIdx = menuItem.ZOrder - 10000;
switch(nIdx)
{
// play background music
case 0:
CCSimpleAudioEngine.SharedEngine.PlayBackgroundMusic(CCFileUtils.FullPathFromRelativePath(MUSIC_FILE), true);
break;
// stop background music
case 1:
CCSimpleAudioEngine.SharedEngine.StopBackgroundMusic();
break;
// pause background music
case 2:
CCSimpleAudioEngine.SharedEngine.PauseBackgroundMusic();
break;
// resume background music
case 3:
CCSimpleAudioEngine.SharedEngine.ResumeBackgroundMusic();
break;
// rewind background music
case 4:
CCSimpleAudioEngine.SharedEngine.RewindBackgroundMusic();
break;
// is background music playing
case 5:
if(CCSimpleAudioEngine.SharedEngine.BackgroundMusicPlaying)
{
CCLog.Log("background music is playing");
}
else
{
CCLog.Log("background music is not playing");
}
break;
// play effect
case 6:
soundId = CCSimpleAudioEngine.SharedEngine.PlayEffect(CCFileUtils.FullPathFromRelativePath(EFFECT_FILE));
break;
// play effect
case 7:
soundId = CCSimpleAudioEngine.SharedEngine.PlayEffect(CCFileUtils.FullPathFromRelativePath(EFFECT_FILE), true);
break;
// stop effect
case 8:
CCSimpleAudioEngine.SharedEngine.StopEffect(soundId);
break;
// unload effect
case 9:
CCSimpleAudioEngine.SharedEngine.UnloadEffect(CCFileUtils.FullPathFromRelativePath(EFFECT_FILE));
break;
// add bakcground music volume
case 10:
CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume = CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume + 0.1f;
break;
// sub backgroud music volume
case 11:
CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume = CCSimpleAudioEngine.SharedEngine.BackgroundMusicVolume - 0.1f;
break;
// add effects volume
case 12:
CCSimpleAudioEngine.SharedEngine.EffectsVolume = CCSimpleAudioEngine.SharedEngine.EffectsVolume + 0.1f;
break;
// sub effects volume
case 13:
CCSimpleAudioEngine.SharedEngine.EffectsVolume = CCSimpleAudioEngine.SharedEngine.EffectsVolume - 0.1f;
break;
}
}
#region Event handling
void OnTouchesBegan(List<CCTouch> touches, CCEvent touchEvent)
{
CCTouch touch = touches.FirstOrDefault();
var beginPos = touch.LocationOnScreen;
}
void OnTouchesMoved(List<CCTouch> touches, CCEvent touchEvent)
{
CCTouch touch = touches.FirstOrDefault();
CCPoint touchLocation = Layer.ScreenToWorldspace(touch.LocationOnScreen);
float nMoveY = touchLocation.Y - beginPos.Y;
CCPoint curPos = testMenu.Position;
CCPoint nextPos = new CCPoint(curPos.X, curPos.Y + nMoveY);
CCSize winSize = Layer.VisibleBoundsWorldspace.Size;
if (nextPos.Y < 0.0f)
{
testMenu.Position = new CCPoint(0,0);
return;
}
int testCount = testMenuItems.Count();
if (nextPos.Y > ((testCount + 1)* LINE_SPACE - winSize.Height))
{
testMenu.Position = new CCPoint(0, ((testCount + 1)* LINE_SPACE - winSize.Height));
return;
}
testMenu.Position = nextPos;
beginPos = touchLocation;
}
#endregion Event handling
}
public class CocosDenshionTestScene : TestScene
{
public override void runThisTest()
{
CCLayer layer = new CocosDenshionTest();
AddChild(layer);
Director.ReplaceScene(this);
}
}
}
| |
// Project : ACTORS
// Contacts : Pixeye - [email protected]
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using Unity.IL2CPP.CompilerServices;
using UnityEngine.Scripting;
namespace Pixeye.Actors
{
[Flags]
public enum Op
{
Add = 1,
Remove = 2,
All = Add | Remove
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public abstract class GroupCore : IEnumerable, IEquatable<GroupCore>, IDisposable
{
public ent[] entities = new ent[LayerKernel.Settings.SizeEntities];
public int length;
internal bool initialized;
internal ProcessorEcs processorEcs;
internal Layer layer;
#if ACTORS_EVENTS_MANUAL
public ents added = new ents();
public ents removed = new ents();
internal bool hasEventAdd;
internal bool hasEventRemove;
#else
public ents added = new ents(LayerKernel.Settings.SizeEntities);
public ents removed = new ents(LayerKernel.Settings.SizeEntities);
#endif
protected internal Composition composition;
internal int id;
int position;
bool flagChanged;
public ref ent this[int index]
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref entities[index];
}
public bool changed
{
get
{
if (flagChanged)
{
flagChanged = false;
return true;
}
return false;
}
}
public void Release(int index)
{
if (length == 0) return;
entities[index].Release();
}
#if ACTORS_EVENTS_MANUAL
internal void SetSelf(Op op, Processor pr)
{
if ((op & Op.Add) == Op.Add)
{
if (added == null)
added = new ents(LayerKernel.Settings.SizeEntities);
hasEventAdd = true;
}
if ((op & Op.Remove) == Op.Remove)
{
if (removed == null)
removed = new ents(LayerKernel.Settings.SizeEntities);
hasEventRemove = true;
}
}
#endif
internal virtual GroupCore Initialize(Composition composition, Layer layer)
{
this.layer = layer;
this.composition = composition;
processorEcs = layer.processorEcs;
#if ACTORS_TAGS_CHECKS
HelperTags.RegisterGroup(this);
#endif
for (var i = 0; i < composition.excluded.Length; i++)
{
ref var m = ref composition.excluded[i];
Storage.All[m.id].groups[layer.id].Add(this);
}
return this;
}
//===============================//
// Insert
//===============================//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Insert(in ent entity)
{
var left = 0;
var index = 0;
var right = length++;
if (entity.id >= entities.Length)
{
var l = entity.id + entity.id / 5;
Array.Resize(ref entities, l);
#if ACTORS_EVENTS_MANUAL
if (hasEventAdd)
Array.Resize(ref added.source, l);
if (hasEventRemove)
Array.Resize(ref removed.source, l);
#else
Array.Resize(ref added.source, l);
Array.Resize(ref removed.source, l);
#endif
}
else if (length >= entities.Length)
{
var l = length + length / 5;
Array.Resize(ref entities, l);
#if ACTORS_EVENTS_MANUAL
if (hasEventAdd)
Array.Resize(ref added.source, l);
if (hasEventRemove)
Array.Resize(ref removed.source, l);
#else
Array.Resize(ref added.source, l);
Array.Resize(ref removed.source, l);
#endif
}
var consitionSort = right - 1;
if (consitionSort > -1 && entity.id < entities[consitionSort].id)
{
while (right > left)
{
var midIndex = (right + left) / 2;
if (entities[midIndex].id == entity.id)
{
index = midIndex;
break;
}
if (entities[midIndex].id < entity.id)
left = midIndex + 1;
else
right = midIndex;
index = left;
}
Array.Copy(entities, index, entities, index + 1, length - index);
entities[index] = entity;
#if ACTORS_EVENTS_MANUAL
if (hasEventAdd)
added.source[added.length++] = entity;
#else
added.source[added.length++] = entity;
#endif
}
else
{
entities[right] = entity;
#if ACTORS_EVENTS_MANUAL
if (hasEventAdd)
added.source[added.length++] = entity;
#else
added.source[added.length++] = entity;
#endif
}
flagChanged = true;
}
//===============================//
// Try Remove
//===============================//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool TryRemove(int entityID)
{
if (length == 0) return false;
var i = HelperArray.BinarySearch(ref entities, entityID, 0, length - 1);
if (i == -1) return false;
#if ACTORS_EVENTS_MANUAL
if (hasEventRemove)
removed.source[removed.length++] = entities[i];
#else
removed.source[removed.length++] = entities[i];
#endif
if (i < --length)
Array.Copy(entities, i + 1, entities, i, length - i);
return flagChanged = true;
//return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void RemoveFast(int entityID)
{
var i = HelperArray.BinarySearch(ref entities, entityID, 0, length - 1);
#if ACTORS_EVENTS_MANUAL
if (hasEventRemove)
removed.source[removed.length++] = entities[i];
#else
removed.source[removed.length++] = entities[i];
#endif
if (i < --length)
Array.Copy(entities, i + 1, entities, i, length - i);
flagChanged = true;
}
//===============================//
// Remove
//===============================//
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal void Remove(int i)
{
#if ACTORS_EVENTS_MANUAL
if (hasEventRemove)
removed.source[removed.length++] = entities[i];
#else
removed.source[removed.length++] = entities[i];
#endif
if (i < --length)
Array.Copy(entities, i + 1, entities, i, length - i);
flagChanged = true;
}
public virtual void Dispose()
{
initialized = false;
#if ACTORS_EVENTS_MANUAL
hasEventAdd = false;
hasEventRemove = false;
added = default;
removed = default;
#else
added = new ents(LayerKernel.Settings.SizeEntities);
removed = new ents(LayerKernel.Settings.SizeEntities);
#endif
length = 0;
//parallel
if (segmentGroups != null)
for (int i = 0; i < segmentGroups.Length; i++)
{
var d = segmentGroups[i];
d.thread.Interrupt();
d.thread.Join(5);
syncs[i].Close();
segmentGroups[i] = null;
}
segmentGroupLocal = null;
}
//===============================//
// Concurrent
//===============================//
SegmentGroup segmentGroupLocal;
SegmentGroup[] segmentGroups;
ManualResetEvent[] syncs;
int threadsAmount = Environment.ProcessorCount - 1;
int entitiesPerThreadMin = 5000;
int entitiesPerThread;
HandleSegmentGroup jobAction;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void MakeConcurrent(int minEntities, int threads, HandleSegmentGroup jobAction)
{
this.jobAction = jobAction;
segmentGroupLocal = new SegmentGroup();
segmentGroupLocal.source = this;
segmentGroups = new SegmentGroup[threadsAmount];
syncs = new ManualResetEvent[threadsAmount];
for (int i = 0; i < threadsAmount; i++)
{
ref var nextSegment = ref segmentGroups[i];
nextSegment = new SegmentGroup();
nextSegment.thread = new Thread(HandleThread);
nextSegment.thread.IsBackground = true;
nextSegment.HasWork = new ManualResetEvent(false);
nextSegment.WorkDone = new ManualResetEvent(true);
nextSegment.source = this;
syncs[i] = nextSegment.WorkDone;
nextSegment.thread.Start(nextSegment);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Execute(float delta)
{
if (length > 0)
{
var entitiesNext = 0;
var threadsInWork = 0;
var entitiesPerThread = length / (threadsAmount + 1);
if (entitiesPerThread > entitiesPerThreadMin)
{
threadsInWork = threadsAmount + 1;
}
else
{
threadsInWork = length / entitiesPerThreadMin;
entitiesPerThread = entitiesPerThreadMin;
}
for (var i = 0; i < threadsInWork - 1; i++)
{
var nextSegmentGroup = segmentGroups[i];
nextSegmentGroup.delta = delta;
nextSegmentGroup.indexFrom = entitiesNext;
nextSegmentGroup.indexTo = entitiesNext += entitiesPerThread;
nextSegmentGroup.WorkDone.Reset();
nextSegmentGroup.HasWork.Set();
}
segmentGroupLocal.indexFrom = entitiesNext;
segmentGroupLocal.indexTo = length;
segmentGroupLocal.delta = delta;
jobAction(segmentGroupLocal);
for (var i = 0; i < syncs.Length; i++)
{
syncs[i].WaitOne();
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Execute()
{
if (length > 0)
{
var entitiesNext = 0;
int threadsInWork;
var entitiesPerThread = length / (threadsAmount + 1);
if (entitiesPerThread > entitiesPerThreadMin)
{
threadsInWork = threadsAmount + 1;
}
else
{
threadsInWork = length / entitiesPerThreadMin;
entitiesPerThread = entitiesPerThreadMin;
}
for (var i = 0; i < threadsInWork - 1; i++)
{
var nextSegmentGroup = segmentGroups[i];
nextSegmentGroup.indexFrom = entitiesNext;
nextSegmentGroup.indexTo = entitiesNext += entitiesPerThread;
nextSegmentGroup.WorkDone.Reset();
nextSegmentGroup.HasWork.Set();
}
segmentGroupLocal.indexFrom = entitiesNext;
segmentGroupLocal.indexTo = length;
jobAction(segmentGroupLocal);
for (var i = 0; i < syncs.Length; i++)
{
syncs[i].WaitOne();
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
protected void HandleThread(object objSegmentGroup)
{
var segmentGroup = (SegmentGroup) objSegmentGroup;
try
{
while (Thread.CurrentThread.IsAlive)
{
segmentGroup.HasWork.WaitOne();
segmentGroup.HasWork.Reset();
jobAction(segmentGroup);
segmentGroup.WorkDone.Set();
}
}
catch
{
}
}
#region EQUALS
public bool Equals(GroupCore other)
{
return id == other.id;
}
public bool Equals(int other)
{
return id == other;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == GetType() && Equals((GroupCore) obj);
}
public override int GetHashCode()
{
return id;
}
#endregion
#region ENUMERATOR
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public struct Enumerator : IEnumerator<ent>
{
GroupCore groupEntities;
int position;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(GroupCore groupEntities)
{
this.groupEntities = groupEntities;
position = -1;
groupEntities.processorEcs.Execute();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
// if (++position < groupEntities.length)
// {
// groupEntities.processorEcs.Execute();
// return true;
// }
return ++position < groupEntities.length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
position = -1;
}
object IEnumerator.Current => Current;
public ent Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => groupEntities.entities[position];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
groupEntities = null;
}
}
#endregion
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O, P> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
Storage<P>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
Storage<P>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O, P, A> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
Storage<P>.Instance.groups[layer.id].Add(this);
Storage<A>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
Storage<P>.Instance.groups[layer.id].Remove(this);
Storage<A>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O, P, A, S> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
Storage<P>.Instance.groups[layer.id].Add(this);
Storage<A>.Instance.groups[layer.id].Add(this);
Storage<S>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
Storage<P>.Instance.groups[layer.id].Remove(this);
Storage<A>.Instance.groups[layer.id].Remove(this);
Storage<S>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O, P, A, S, D> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
Storage<P>.Instance.groups[layer.id].Add(this);
Storage<A>.Instance.groups[layer.id].Add(this);
Storage<S>.Instance.groups[layer.id].Add(this);
Storage<D>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
Storage<P>.Instance.groups[layer.id].Remove(this);
Storage<A>.Instance.groups[layer.id].Remove(this);
Storage<S>.Instance.groups[layer.id].Remove(this);
Storage<D>.Instance.groups[layer.id].Remove(this);
}
}
[Preserve]
[Il2CppSetOption(Option.NullChecks, false)]
[Il2CppSetOption(Option.ArrayBoundsChecks, false)]
[Il2CppSetOption(Option.DivideByZeroChecks, false)]
public class Group<T, Y, U, I, O, P, A, S, D, F> : GroupCore
{
internal override GroupCore Initialize(Composition composition, Layer layer)
{
var gr = base.Initialize(composition, layer);
Storage<T>.Instance.groups[layer.id].Add(this);
Storage<Y>.Instance.groups[layer.id].Add(this);
Storage<U>.Instance.groups[layer.id].Add(this);
Storage<I>.Instance.groups[layer.id].Add(this);
Storage<O>.Instance.groups[layer.id].Add(this);
Storage<P>.Instance.groups[layer.id].Add(this);
Storage<A>.Instance.groups[layer.id].Add(this);
Storage<S>.Instance.groups[layer.id].Add(this);
Storage<D>.Instance.groups[layer.id].Add(this);
Storage<F>.Instance.groups[layer.id].Add(this);
return gr;
}
public override void Dispose()
{
base.Dispose();
Storage<T>.Instance.groups[layer.id].Remove(this);
Storage<Y>.Instance.groups[layer.id].Remove(this);
Storage<U>.Instance.groups[layer.id].Remove(this);
Storage<I>.Instance.groups[layer.id].Remove(this);
Storage<O>.Instance.groups[layer.id].Remove(this);
Storage<P>.Instance.groups[layer.id].Remove(this);
Storage<A>.Instance.groups[layer.id].Remove(this);
Storage<S>.Instance.groups[layer.id].Remove(this);
Storage<D>.Instance.groups[layer.id].Remove(this);
Storage<F>.Instance.groups[layer.id].Remove(this);
}
}
public delegate void HandleSegmentGroup(SegmentGroup segment);
public sealed class SegmentGroup
{
public GroupCore source;
public float delta;
public int indexFrom;
public int indexTo;
internal Thread thread;
internal ManualResetEvent HasWork;
internal ManualResetEvent WorkDone;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Enumerator GetEnumerator()
{
return new Enumerator(indexFrom, indexTo);
}
public struct Enumerator : IEnumerator<int>
{
readonly int length;
int position;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Enumerator(int from, int to)
{
position = from - 1;
length = to;
}
public int Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return position; }
}
object IEnumerator.Current => Current;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
return ++position < length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
position = -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.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public partial class FileStream : Stream
{
internal const int DefaultBufferSize = 4096;
private const FileShare DefaultShare = FileShare.Read;
private const bool DefaultUseAsync = true;
private const bool DefaultIsAsync = false;
private FileStreamBase _innerStream;
internal FileStream(FileStreamBase innerStream)
{
if (innerStream == null)
{
throw new ArgumentNullException("innerStream");
}
this._innerStream = innerStream;
}
public FileStream(Microsoft.Win32.SafeHandles.SafeFileHandle handle, FileAccess access) :
this(handle, access, DefaultBufferSize)
{
}
public FileStream(string path, System.IO.FileMode mode) :
this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access) :
this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share) :
this(path, mode, access, share, DefaultBufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize) :
this(path, mode, access, share, bufferSize, DefaultUseAsync)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) :
this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None)
{ }
public FileStream(string path, System.IO.FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
Init(path, mode, access, share, bufferSize, options);
}
private void Init(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
{
if (path == null)
throw new ArgumentNullException("path", SR.ArgumentNull_Path);
if (path.Length == 0)
throw new ArgumentException(SR.Argument_EmptyPath, "path");
// don't include inheritable in our bounds check for share
FileShare tempshare = share & ~FileShare.Inheritable;
String badArg = null;
if (mode < FileMode.CreateNew || mode > FileMode.Append)
badArg = "mode";
else if (access < FileAccess.Read || access > FileAccess.ReadWrite)
badArg = "access";
else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete))
badArg = "share";
if (badArg != null)
throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum);
// NOTE: any change to FileOptions enum needs to be matched here in the error validation
if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0)
throw new ArgumentOutOfRangeException("options", SR.ArgumentOutOfRange_Enum);
if (bufferSize <= 0)
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedPosNum);
// Write access validation
if ((access & FileAccess.Write) == 0)
{
if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append)
{
// No write access, mode and access disagree but flag access since mode comes first
throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), "access");
}
}
string fullPath = Path.GetFullPath(path);
ValidatePath(fullPath, "path");
if ((access & FileAccess.Read) != 0 && mode == FileMode.Append)
throw new ArgumentException(SR.Argument_InvalidAppendMode, "access");
this._innerStream = FileSystem.Current.Open(fullPath, mode, access, share, bufferSize, options, this);
}
static partial void ValidatePath(string fullPath, string paramName);
// InternalOpen, InternalCreate, and InternalAppend:
// Factory methods for FileStream used by File, FileInfo, and ReadLinesIterator
// Specifies default access and sharing options for FileStreams created by those classes
internal static FileStream InternalOpen(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, useAsync);
}
internal static FileStream InternalCreate(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
}
internal static FileStream InternalAppend(String path, int bufferSize = DefaultBufferSize, bool useAsync = DefaultUseAsync)
{
return new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read, bufferSize, useAsync);
}
#region FileStream members
public virtual bool IsAsync { get { return this._innerStream.IsAsync; } }
public string Name { get { return this._innerStream.Name; } }
public virtual Microsoft.Win32.SafeHandles.SafeFileHandle SafeFileHandle { get { return this._innerStream.SafeFileHandle; } }
public virtual void Flush(bool flushToDisk)
{
this._innerStream.Flush(flushToDisk);
}
#endregion
#region Stream members
#region Properties
public override bool CanRead
{
get { return _innerStream.CanRead; }
}
public override bool CanSeek
{
get { return _innerStream.CanSeek; }
}
public override bool CanWrite
{
get { return _innerStream.CanWrite; }
}
public override long Length
{
get { return _innerStream.Length; }
}
public override long Position
{
get { return _innerStream.Position; }
set { _innerStream.Position = value; }
}
public override int ReadTimeout
{
get { return _innerStream.ReadTimeout; }
set { _innerStream.ReadTimeout = value; }
}
public override bool CanTimeout
{
get { return _innerStream.CanTimeout; }
}
public override int WriteTimeout
{
get { return _innerStream.WriteTimeout; }
set { _innerStream.WriteTimeout = value; }
}
#endregion Properties
#region Methods
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
return _innerStream.CopyToAsync(destination, bufferSize, cancellationToken);
}
protected override void Dispose(bool disposing)
{
if (_innerStream != null)
{
// called even during finalization
_innerStream.DisposeInternal(disposing);
}
base.Dispose(disposing);
}
public override void Flush()
{
_innerStream.Flush();
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overridden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.FlushAsync(cancellationToken);
return _innerStream.FlushAsync(cancellationToken);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _innerStream.Read(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() or ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/ReadAsync) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.ReadAsync(buffer, offset, count, cancellationToken);
return _innerStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override int ReadByte()
{
return _innerStream.ReadByte();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _innerStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
_innerStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
_innerStream.Write(buffer, offset, count);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() or WriteAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write/WriteAsync) when we are not sure.
if (this.GetType() != typeof(FileStream))
return base.WriteAsync(buffer, offset, count, cancellationToken);
return _innerStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override void WriteByte(byte value)
{
_innerStream.WriteByte(value);
}
#endregion Methods
#endregion Stream members
[Security.SecuritySafeCritical]
~FileStream()
{
// Preserved for compatibility since FileStream has defined a
// finalizer in past releases and derived classes may depend
// on Dispose(false) call.
Dispose(false);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="VideoOverlayProvider.cs" company="Google">
//
// 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.
//
// </copyright>
//-----------------------------------------------------------------------
namespace Tango
{
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Rendering;
/// <summary>
/// C API wrapper for the Tango video overlay interface.
/// </summary>
public class VideoOverlayProvider
{
#if UNITY_EDITOR
/// <summary>
/// INTERNAL USE: Dimension of simulated color camera textures.
/// </summary>
internal const int EMULATED_CAMERA_PACKED_WIDTH = 1280 / 4;
/// <summary>
/// INTERNAL USE: Dimension of simulated color camera Y texture.
/// </summary>
internal const int EMULATED_CAMERA_PACKED_Y_HEIGHT = 720;
/// <summary>
/// INTERNAL USE: Dimension of simulated color camera CbCr texture.
/// </summary>
internal const int EMULATED_CAMERA_PACKED_UV_HEIGHT = 720 / 2;
/// <summary>
/// INTERNAL USE: Flag set to true whenever emulated values have been updated.
/// </summary>
internal static bool m_emulationIsDirty;
private const int EMULATED_CAMERA_WIDTH = 1280;
private const int EMULATED_CAMERA_HEIGHT = 720;
private const string EMULATED_RGB2YUV_Y_SHADERNAME = "Hidden/Tango/RGB2YUV_Y";
private const string EMULATED_RGB2YUV_CBCR_SHADERNAME = "Hidden/Tango/RGB2YUV_CbCr";
private const string EMULATED_RGB_ARSCREEN_SHADERNAME = "Hidden/Tango/RGB_ARScreen";
#endif
private static readonly string CLASS_NAME = "VideoOverlayProvider";
#if UNITY_EDITOR
/// <summary>
/// Render target used to render environment for Tango emulation on PC.
/// </summary>
private static RenderTexture m_emulatedColorRenderTexture = null;
/// <summary>
/// Underlying Y texture when using experimental texture-ID method.
/// </summary>
private static RenderTexture m_emulatedExpId_Y = null;
/// <summary>
/// Underlying Y texture when using experimental texture-ID method.
/// </summary>
private static RenderTexture m_emulatedExpId_CbCr = null;
/// <summary>
/// Underlying RGB texture for the AR Screen.
/// </summary>
private static RenderTexture m_emulatedARScreenTexture = null;
/// <summary>
/// Textures used to capture emulated color feed from render target.
/// (First texture is Y component, second is CbCr).
/// </summary>
private static Texture2D[] m_emulationByteBufferCaptureTextures = null;
/// <summary>
/// Post-process filter used to turn an RGB texture into a texture
/// containing the Y-component data expected by experimental texture-ID method.
/// </summary>
private static Material m_yuvFilterY;
/// <summary>
/// Post-process filter used to turn an RGB texture into a texture
/// containing the Cb/Cr component data expected by experimental texture-ID method.
/// </summary>
private static Material m_yuvFilterCbCr;
/// <summary>
/// Simple material that emulates the AR Screen.
/// </summary>
private static Material m_emulationArScreenMaterial;
/// <summary>
/// The theoretical capture time of most recent emulated color frame.
/// </summary>
private static float m_lastColorEmulationTime;
/// <summary>
/// Whether resources needed for emulation have been created.
/// </summary>
private static bool m_emulationIsInitialized = false;
#endif
/// <summary>
/// Tango video overlay C callback function signature.
/// </summary>
/// <param name="context">Callback context.</param>
/// <param name="cameraId">Camera ID.</param>
/// <param name="image">Image buffer.</param>
/// <param name="cameraMetadata">Camera metadata.</param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void APIOnImageAvailable(
IntPtr context, TangoEnums.TangoCameraId cameraId, ref TangoImage image,
ref TangoCameraMetadata cameraMetadata);
/// <summary>
/// Tango camera texture C callback function signature.
/// </summary>
/// <param name="context">Callback context.</param>
/// <param name="cameraId">Camera ID.</param>
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void APIOnTextureAvailable(IntPtr context, TangoEnums.TangoCameraId cameraId);
/// <summary>
/// DEPRECATED: Update the texture that has been connected to camera referenced by TangoCameraId with the latest image
/// from the camera.
/// </summary>
/// <returns>The timestamp of the image that has been pushed to the connected texture.</returns>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <c>TANGO_CAMERA_COLOR</c> is supported.
/// </param>
public static double RenderLatestFrame(TangoEnums.TangoCameraId cameraId)
{
#if UNITY_EDITOR
if (m_emulatedExpId_Y != null && m_emulatedExpId_CbCr != null)
{
m_emulatedExpId_Y.DiscardContents();
m_emulatedExpId_CbCr.DiscardContents();
Graphics.Blit(m_emulatedColorRenderTexture, m_emulatedExpId_Y, m_yuvFilterY);
Graphics.Blit(m_emulatedColorRenderTexture, m_emulatedExpId_CbCr, m_yuvFilterCbCr);
}
return m_lastColorEmulationTime;
#else
double timestamp = 0.0;
int returnValue = API.TangoService_updateTexture(cameraId, ref timestamp);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("VideoOverlayProvider.UpdateTexture() Texture was not updated by camera!");
}
return timestamp;
#endif
}
/// <summary>
/// Create a command buffer that renders the AR screen full screen at the right time.
/// </summary>
/// <returns>The AR screen command buffer.</returns>
public static CommandBuffer CreateARScreenCommandBuffer()
{
CommandBuffer buf = new CommandBuffer();
#if UNITY_EDITOR
_InternResourcesForEmulation();
buf.Blit((Texture)m_emulatedARScreenTexture, BuiltinRenderTextureType.CurrentActive,
m_emulationArScreenMaterial);
#else
IntPtr func = API.TangoUnity_getRenderTextureFunction();
buf.IssuePluginEvent(func, 0);
#endif
return buf;
}
/// <summary>
/// Set the AR screen rendering UVs. This affects how much of the screen is visible.
/// </summary>
/// <param name="uv">
/// Array of four UV coordinates in order: bottom left, top left, bottom right, top right.
/// </param>
public static void SetARScreenUVs(Vector2[] uv)
{
#if UNITY_EDITOR
if (m_emulationArScreenMaterial != null)
{
m_emulationArScreenMaterial.SetVector("_UVBottomLeft", new Vector4(uv[0].x, uv[0].y, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVTopLeft", new Vector4(uv[1].x, uv[1].y, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVBottomRight", new Vector4(uv[2].x, uv[2].y, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVTopRight", new Vector4(uv[3].x, uv[3].y, 0, 0));
}
#else
API.TangoUnity_setRenderTextureUVs(uv);
#endif
}
/// <summary>
/// Set the AR screen rendering distortion parameters. This affects correcting for the curvature of the lens.
/// </summary>
/// <param name="rectifyImage">If <c>true</c>, rectify the AR screen image when rendering.</param>
public static void SetARScreenDistortion(bool rectifyImage)
{
#if UNITY_EDITOR
// There is no distortion in emulation.
#else
if (!rectifyImage)
{
API.TangoUnity_setRenderTextureDistortion(null);
}
else
{
TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics();
GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics);
API.TangoUnity_setRenderTextureDistortion(intrinsics);
}
#endif
}
/// <summary>
/// Update the AR screen's texture to the most recent state of the specified camera.
/// </summary>
/// <returns>The timestamp of the image that has been pushed to the AR screen's texture.</returns>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <c>TANGO_CAMERA_COLOR</c> is supported.
/// </param>
public static double UpdateARScreen(TangoEnums.TangoCameraId cameraId)
{
#if UNITY_EDITOR
if (m_emulatedARScreenTexture != null)
{
m_emulatedARScreenTexture.DiscardContents();
Graphics.Blit(m_emulatedColorRenderTexture, m_emulatedARScreenTexture);
}
return m_lastColorEmulationTime;
#else
double timestamp = 0.0;
uint tex = API.TangoUnity_getArTexture();
int returnValue = API.TangoService_updateTextureExternalOes(cameraId, tex, out timestamp);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("Unable to update texture. " + Environment.StackTrace);
}
// Rendering the latest frame changes a bunch of OpenGL state. Ensure Unity knows the current OpenGL
// state.
GL.InvalidateState();
return timestamp;
#endif
}
/// <summary>
/// Get the intrinsic calibration parameters for a given camera, this also aligns the camera intrinsics based
/// on device orientation.
///
/// For example, if the device orientation is portrait and camera intrinsics is in
/// landscape. This function will inverse the intrinsic x and y, and report intrinsics in portrait mode.
///
/// The intrinsics are as specified by the TangoCameraIntrinsics struct and are accessed via the API.
/// </summary>
/// <param name="cameraId">The camera ID to retrieve the calibration intrinsics for.</param>
/// <param name="alignedIntrinsics">
/// A TangoCameraIntrinsics filled with calibration intrinsics for the camera, this intrinsics is also
/// aligned with device orientation.
/// </param>
public static void GetDeviceOrientationAlignedIntrinsics(TangoEnums.TangoCameraId cameraId,
TangoCameraIntrinsics alignedIntrinsics)
{
TangoCameraIntrinsics intrinsics = new TangoCameraIntrinsics();
GetIntrinsics(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, intrinsics);
float intrinsicsRatio = (float)intrinsics.width / (float)intrinsics.height;
Tango.OrientationManager.Rotation rotation = TangoSupport.RotateFromAToB(
AndroidHelper.GetDisplayRotation(),
AndroidHelper.GetColorCameraRotation());
switch (rotation)
{
case Tango.OrientationManager.Rotation.ROTATION_90:
alignedIntrinsics.cx = intrinsics.cy;
alignedIntrinsics.cy = intrinsics.width - intrinsics.cx;
alignedIntrinsics.fx = intrinsics.fy;
alignedIntrinsics.fy = intrinsics.fx;
alignedIntrinsics.width = intrinsics.height;
alignedIntrinsics.height = intrinsics.width;
break;
case Tango.OrientationManager.Rotation.ROTATION_180:
alignedIntrinsics.cx = intrinsics.width - intrinsics.cx;
alignedIntrinsics.cy = intrinsics.height - intrinsics.cy;
alignedIntrinsics.fx = intrinsics.fx;
alignedIntrinsics.fy = intrinsics.fy;
alignedIntrinsics.width = intrinsics.width;
alignedIntrinsics.height = intrinsics.height;
break;
case Tango.OrientationManager.Rotation.ROTATION_270:
alignedIntrinsics.cx = intrinsics.height - intrinsics.cy;
alignedIntrinsics.cy = intrinsics.cx;
alignedIntrinsics.fx = intrinsics.fy;
alignedIntrinsics.fy = intrinsics.fx;
alignedIntrinsics.width = intrinsics.height;
alignedIntrinsics.height = intrinsics.width;
break;
default:
alignedIntrinsics.cx = intrinsics.cx;
alignedIntrinsics.cy = intrinsics.cy;
alignedIntrinsics.fx = intrinsics.fx;
alignedIntrinsics.fy = intrinsics.fy;
alignedIntrinsics.width = intrinsics.width;
alignedIntrinsics.height = intrinsics.height;
break;
}
alignedIntrinsics.distortion0 = intrinsics.distortion0;
alignedIntrinsics.distortion1 = intrinsics.distortion1;
alignedIntrinsics.distortion2 = intrinsics.distortion2;
alignedIntrinsics.distortion3 = intrinsics.distortion3;
alignedIntrinsics.distortion4 = intrinsics.distortion4;
alignedIntrinsics.camera_id = intrinsics.camera_id;
alignedIntrinsics.calibration_type = intrinsics.calibration_type;
}
/// <summary>
/// Get the intrinsic calibration parameters for a given camera.
///
/// The intrinsics are as specified by the TangoCameraIntrinsics struct and are accessed via the API.
/// </summary>
/// <param name="cameraId">The camera ID to retrieve the calibration intrinsics for.</param>
/// <param name="intrinsics">A TangoCameraIntrinsics filled with calibration intrinsics for the camera.</param>
public static void GetIntrinsics(TangoEnums.TangoCameraId cameraId, TangoCameraIntrinsics intrinsics)
{
int returnValue = API.TangoService_getCameraIntrinsics(cameraId, intrinsics);
#if UNITY_EDITOR
// In editor, base 'intrinsics' off of properties of emulation camera.
if (cameraId == TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR && EmulatedEnvironmentRenderHelper.m_emulationCamera != null)
{
// Instantiate any resources that we haven't yet.
_InternResourcesForEmulation();
EmulatedEnvironmentRenderHelper.m_emulationCamera.targetTexture = m_emulatedColorRenderTexture;
intrinsics.width = (uint)EMULATED_CAMERA_WIDTH;
intrinsics.height = (uint)EMULATED_CAMERA_HEIGHT;
float fov = EmulatedEnvironmentRenderHelper.m_emulationCamera.fieldOfView;
float focalLengthInPixels = (1 / Mathf.Tan(fov * 0.5f * Mathf.Deg2Rad)) * (intrinsics.height * 0.5f);
intrinsics.fy = intrinsics.fx = focalLengthInPixels;
intrinsics.cx = intrinsics.width / 2f;
intrinsics.cy = intrinsics.height / 2f;
}
#endif
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("IntrinsicsProviderAPI.TangoService_getCameraIntrinsics() failed!");
}
}
/// <summary>
/// DEPRECATED: Connect a Texture IDs to a camera.
///
/// The camera is selected via TangoCameraId. Currently only TANGO_CAMERA_COLOR is supported. The texture
/// handles will be regenerated by the API on startup after which the application can use them, and will be
/// packed RGBA8888 data containing bytes of the image (so a single RGBA8888 will pack 4 neighboring pixels).
/// If the config flag experimental_image_pixel_format is set to HAL_PIXEL_FORMAT_YCrCb_420_SP, texture_y will
/// pack 1280x720 pixels into a 320x720 RGBA8888 texture. texture_Cb and texture_Cr will contain copies of
/// the 2x2 downsampled interleaved UV planes packed similarly. If experimental_image_pixel_format is set to
/// HAL_PIXEL_FORMAT_YV12 then texture_y will have a stride of 1536 containing 1280 columns of data, packed
/// similarly in a RGBA8888 texture. texture_Cb and texture_Cr will be 2x2 downsampled versions of the same.
/// See YV12 and NV21 formats for details.
///
/// Note: The first scan-line of the color image is reserved for metadata instead of image pixels.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only TANGO_CAMERA_COLOR and TANGO_CAMERA_FISHEYE are
/// supported.
/// </param>
/// <param name="textures">The texture IDs to use for the Y, Cb, and Cr planes.</param>
/// <param name="callback">Callback method.</param>
internal static void ExperimentalConnectTexture(
TangoEnums.TangoCameraId cameraId, YUVTexture textures, APIOnTextureAvailable callback)
{
#if UNITY_EDITOR
if (cameraId == TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR)
{
m_emulatedExpId_Y = (RenderTexture)textures.m_videoOverlayTextureY;
m_emulatedExpId_CbCr = (RenderTexture)textures.m_videoOverlayTextureCb;
}
#else
int returnValue = API.TangoService_Experimental_connectTextureIdUnity(
cameraId,
(uint)textures.m_videoOverlayTextureY.GetNativeTexturePtr().ToInt64(),
(uint)textures.m_videoOverlayTextureCb.GetNativeTexturePtr().ToInt64(),
(uint)textures.m_videoOverlayTextureCr.GetNativeTexturePtr().ToInt64(),
IntPtr.Zero,
callback);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log("VideoOverlayProvider.ConnectTexture() Texture was not connected to camera!");
}
#endif
}
/// <summary>
/// Connect a callback to a camera for access to the pixels.
///
/// This is not recommended for display but for applications requiring access to the
/// <code>HAL_PIXEL_FORMAT_YV12</code> pixel data. The camera is selected via TangoCameraId. Currently only
/// <code>TANGO_CAMERA_COLOR</code> and <code>TANGO_CAMERA_FISHEYE</code> are supported.
///
/// The <i>onImageAvailable</i> callback will be called when a new frame is available from the camera. The
/// Enable Video Overlay option must be enabled for this to succeed.
///
/// Note: The first scan-line of the color image is reserved for metadata instead of image pixels.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and
/// <code>TANGO_CAMERA_FISHEYE</code> are supported.
/// </param>
/// <param name="callback">Function called when a new frame is available from the camera.</param>
internal static void SetCallback(TangoEnums.TangoCameraId cameraId, APIOnImageAvailable callback)
{
int returnValue = API.TangoService_connectOnImageAvailable(cameraId, IntPtr.Zero, callback);
bool success = returnValue == Common.ErrorType.TANGO_SUCCESS;
Debug.LogFormat("{0}.SetCallback(OnImageAvailable) Callback was {1}set.",
CLASS_NAME, success ? string.Empty : "not ");
}
/// <summary>
/// Connect a callback to a camera for texture updates.
/// </summary>
/// <param name="cameraId">
/// The ID of the camera to connect this texture to. Only <code>TANGO_CAMERA_COLOR</code> and
/// <code>TANGO_CAMERA_FISHEYE</code> are supported.
/// </param>
/// <param name="callback">Function called when a new frame is available from the camera.</param>
internal static void SetCallback(TangoEnums.TangoCameraId cameraId, APIOnTextureAvailable callback)
{
int returnValue = API.TangoService_connectOnTextureAvailable(cameraId, IntPtr.Zero, callback);
if (returnValue == Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".SetCallback(OnTextureAvailable) Callback was set.");
}
else
{
Debug.Log(CLASS_NAME + ".SetCallback(OnTextureAvailable) Callback was not set!");
}
}
/// <summary>
/// Clear all camera callbacks.
/// </summary>
/// <param name="cameraId">Camera identifier.</param>
internal static void ClearCallback(TangoEnums.TangoCameraId cameraId)
{
int returnValue = API.TangoService_Experimental_connectTextureIdUnity(cameraId, 0, 0, 0,
IntPtr.Zero, null);
if (returnValue == Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".ClearCallback() Unity callback was cleared.");
}
else
{
Debug.Log(CLASS_NAME + ".ClearCallback() Unity callback was not cleared!");
}
returnValue = API.TangoService_connectOnImageAvailable(cameraId, IntPtr.Zero, null);
if (returnValue == Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".ClearCallback() Frame callback was cleared.");
}
else
{
Debug.Log(CLASS_NAME + ".ClearCallback() Frame callback was not cleared!");
}
returnValue = API.TangoService_connectOnTextureAvailable(cameraId, IntPtr.Zero, null);
if (returnValue == Common.ErrorType.TANGO_SUCCESS)
{
Debug.Log(CLASS_NAME + ".ClearCallback() Texture callback was cleared.");
}
else
{
Debug.Log(CLASS_NAME + ".ClearCallback() Texture callback was not cleared!");
}
}
#if UNITY_EDITOR
/// <summary>
/// INTERNAL USE: Update the Tango emulation state for color camera data.
/// </summary>
/// <param name="useByteBufferMethod">Whether to update emulation for byte-buffer method.</param>
internal static void UpdateTangoEmulation(bool useByteBufferMethod)
{
// Get emulated position and rotation in Unity space.
TangoPoseData poseData = new TangoPoseData();
TangoCoordinateFramePair pair;
pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE;
pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE;
if (!PoseProvider.GetTimestampForColorEmulation(out m_lastColorEmulationTime))
{
Debug.LogError("Couldn't get a valid timestamp with which to emulate color camera. "
+ "Color camera emulation will be skipped this frame.");
return;
}
PoseProvider.GetPoseAtTime(poseData, m_lastColorEmulationTime, pair);
if (poseData.status_code != TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID)
{
return;
}
Vector3 position;
Quaternion rotation;
TangoSupport.TangoPoseToWorldTransform(poseData, out position, out rotation);
// Instantiate any resources that we haven't yet.
_InternResourcesForEmulation();
// Render.
EmulatedEnvironmentRenderHelper.RenderEmulatedEnvironment(m_emulatedColorRenderTexture,
EmulatedEnvironmentRenderHelper.EmulatedDataType.COLOR_CAMERA,
position, rotation);
m_emulationIsDirty = true;
}
/// <summary>
/// INTERNAL USE: Fill out most recent color data for Tango emulation.
/// NOTE: Does not emulate first line of metadata in color buffer.
/// </summary>
/// <param name="colorImageData">TangoUnityImageData structure to update with emulated data.</param>
internal static void GetTangoEmulation(TangoUnityImageData colorImageData)
{
int yDataSize = EMULATED_CAMERA_WIDTH * EMULATED_CAMERA_HEIGHT;
int cbCrDataSize = yDataSize / 2;
int dataSize = yDataSize + cbCrDataSize;
if (colorImageData.data == null || colorImageData.data.Length != dataSize)
{
colorImageData.data = new byte[dataSize];
}
RenderTexture yRT = RenderTexture.GetTemporary(EMULATED_CAMERA_PACKED_WIDTH,
EMULATED_CAMERA_PACKED_Y_HEIGHT,
0, RenderTextureFormat.ARGB32);
RenderTexture cbCrRT = RenderTexture.GetTemporary(EMULATED_CAMERA_PACKED_WIDTH,
EMULATED_CAMERA_PACKED_UV_HEIGHT,
0, RenderTextureFormat.ARGB32);
Graphics.Blit(m_emulatedColorRenderTexture, yRT, m_yuvFilterY);
m_emulationByteBufferCaptureTextures[0].ReadPixels(new Rect(0, 0, yRT.width, yRT.height), 0, 0);
Graphics.Blit(m_emulatedColorRenderTexture, cbCrRT, m_yuvFilterCbCr);
m_emulationByteBufferCaptureTextures[1].ReadPixels(new Rect(0, 0, cbCrRT.width, cbCrRT.height), 0, 0);
Color32[] colors = m_emulationByteBufferCaptureTextures[0].GetPixels32();
for (int i = 0; i < yDataSize / 4; i++)
{
colorImageData.data[(i * 4)] = colors[i].r;
colorImageData.data[(i * 4) + 1] = colors[i].g;
colorImageData.data[(i * 4) + 2] = colors[i].b;
colorImageData.data[(i * 4) + 3] = colors[i].a;
}
int startOffset = colors.Length * 4;
colors = m_emulationByteBufferCaptureTextures[1].GetPixels32();
for (int i = 0; i < cbCrDataSize / 4; i++)
{
colorImageData.data[(i * 4) + startOffset] = colors[i].r;
colorImageData.data[(i * 4) + startOffset + 1] = colors[i].g;
colorImageData.data[(i * 4) + startOffset + 2] = colors[i].b;
colorImageData.data[(i * 4) + startOffset + 3] = colors[i].a;
}
RenderTexture.ReleaseTemporary(yRT);
RenderTexture.ReleaseTemporary(cbCrRT);
colorImageData.format = TangoEnums.TangoImageFormatType.TANGO_HAL_PIXEL_FORMAT_YV12;
colorImageData.width = EMULATED_CAMERA_WIDTH;
colorImageData.height = EMULATED_CAMERA_HEIGHT;
colorImageData.stride = EMULATED_CAMERA_WIDTH;
colorImageData.timestamp = m_lastColorEmulationTime;
}
/// <summary>
/// Create any resources needed for emulation.
/// </summary>
private static void _InternResourcesForEmulation()
{
if(m_emulationIsInitialized)
{
return;
}
// Create textures:
m_emulatedColorRenderTexture = new RenderTexture(EMULATED_CAMERA_WIDTH, EMULATED_CAMERA_HEIGHT, 24,
RenderTextureFormat.ARGB32);
m_emulatedARScreenTexture = new RenderTexture(EMULATED_CAMERA_WIDTH, EMULATED_CAMERA_HEIGHT, 0,
RenderTextureFormat.ARGB32);
m_emulationByteBufferCaptureTextures = new Texture2D[2];
m_emulationByteBufferCaptureTextures[0] = new Texture2D(EMULATED_CAMERA_PACKED_WIDTH,
EMULATED_CAMERA_PACKED_Y_HEIGHT,
TextureFormat.ARGB32, false);
m_emulationByteBufferCaptureTextures[1] = new Texture2D(EMULATED_CAMERA_PACKED_WIDTH,
EMULATED_CAMERA_PACKED_UV_HEIGHT,
TextureFormat.ARGB32, false);
// Find shaders by searching for them:
if (EmulatedEnvironmentRenderHelper.CreateMaterialFromShaderName(EMULATED_RGB2YUV_Y_SHADERNAME,
out m_yuvFilterY))
{
m_yuvFilterY.SetFloat("_TexWidth", EMULATED_CAMERA_WIDTH);
}
else
{
Debug.LogError("Could not find shader "
+ EMULATED_RGB2YUV_Y_SHADERNAME
+ ". Tango color camera emulation will not work correctly.");
}
if (EmulatedEnvironmentRenderHelper.CreateMaterialFromShaderName(EMULATED_RGB2YUV_CBCR_SHADERNAME,
out m_yuvFilterCbCr))
{
m_yuvFilterCbCr.SetFloat("_TexWidth", EMULATED_CAMERA_WIDTH);
}
else
{
Debug.LogError("Could not find shader "
+ EMULATED_RGB2YUV_CBCR_SHADERNAME
+ ". Tango color camera emulation will not work correctly.");
}
if (EmulatedEnvironmentRenderHelper.CreateMaterialFromShaderName(EMULATED_RGB_ARSCREEN_SHADERNAME,
out m_emulationArScreenMaterial))
{
m_emulationArScreenMaterial.SetVector("_UVBottomLeft", new Vector4(0, 0, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVBottomRight", new Vector4(0, 1, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVTopLeft", new Vector4(1, 0, 0, 0));
m_emulationArScreenMaterial.SetVector("_UVTopRight", new Vector4(1, 1, 0, 0));
}
else
{
Debug.LogError("Could not find shader "
+ EMULATED_RGB_ARSCREEN_SHADERNAME
+ ". Tango color camera emulation will not work correctly.");
}
m_emulationIsInitialized = true;
}
#endif
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "C API Wrapper.")]
private struct API
{
#if UNITY_ANDROID && !UNITY_EDITOR
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_updateTexture(
TangoEnums.TangoCameraId cameraId, ref double timestamp);
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_updateTextureExternalOes(
TangoEnums.TangoCameraId cameraId, UInt32 glTextureId, out double timestamp);
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_getCameraIntrinsics(
TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics);
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_connectOnImageAvailable(
TangoEnums.TangoCameraId cameraId, IntPtr context,
[In, Out] APIOnImageAvailable callback);
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_connectOnTextureAvailable(
TangoEnums.TangoCameraId cameraId, IntPtr ContextMenu, APIOnTextureAvailable callback);
[DllImport(Common.TANGO_CLIENT_API_DLL)]
public static extern int TangoService_Experimental_connectTextureIdUnity(
TangoEnums.TangoCameraId id, UInt32 texture_y, UInt32 texture_Cb, UInt32 texture_Cr, IntPtr context,
APIOnTextureAvailable callback);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern UInt32 TangoUnity_getArTexture();
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern void TangoUnity_setRenderTextureUVs(Vector2[] uv);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern void TangoUnity_setRenderTextureDistortion(TangoCameraIntrinsics intrinsics);
[DllImport(Common.TANGO_UNITY_DLL)]
public static extern IntPtr TangoUnity_getRenderTextureFunction();
#else
public static int TangoService_updateTexture(TangoEnums.TangoCameraId cameraId, ref double timestamp)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_updateTextureExternalOes(
TangoEnums.TangoCameraId cameraId, UInt32 glTextureId, out double timestamp)
{
timestamp = 0;
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_getCameraIntrinsics(
TangoEnums.TangoCameraId cameraId, [Out] TangoCameraIntrinsics intrinsics)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_connectOnImageAvailable(
TangoEnums.TangoCameraId cameraId, IntPtr context,
[In, Out] APIOnImageAvailable callback)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_connectOnTextureAvailable(
TangoEnums.TangoCameraId cameraId, IntPtr context, APIOnTextureAvailable callback)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoService_Experimental_connectTextureIdUnity(
TangoEnums.TangoCameraId id, UInt32 texture_y, UInt32 texture_Cb, UInt32 texture_Cr,
IntPtr context, APIOnTextureAvailable callback)
{
return Common.ErrorType.TANGO_SUCCESS;
}
public static UInt32 TangoUnity_getArTexture()
{
return 0;
}
public static void TangoUnity_setRenderTextureUVs(Vector2[] uv)
{
}
public static void TangoUnity_setRenderTextureDistortion(TangoCameraIntrinsics intrinsics)
{
}
public static IntPtr TangoUnity_getRenderTextureFunction()
{
return IntPtr.Zero;
}
#endif
}
}
/// <summary>
/// DEPRECATED: Wraps separate textures for Y, U, and V planes.
/// </summary>
public class YUVTexture
{
/// <summary>
/// The m_video overlay texture y.
/// Columns 1280/4 [bytes packed in RGBA channels]
/// Rows 720
/// This size is for a 1280x720 screen.
/// </summary>
public readonly Texture m_videoOverlayTextureY;
/// <summary>
/// The m_video overlay texture cb.
/// Columns 640/4 [bytes packed in RGBA channels]
/// Rows 360
/// This size is for a 1280x720 screen.
/// </summary>
public readonly Texture m_videoOverlayTextureCb;
/// <summary>
/// The m_video overlay texture cr.
/// Columns 640 * 2 / 4 [bytes packed in RGBA channels]
/// Rows 360
/// This size is for a 1280x720 screen.
/// </summary>
public readonly Texture m_videoOverlayTextureCr;
/// <summary>
/// Initializes a new instance of the <see cref="YUVTexture"/> class.
/// NOTE : Texture resolutions will be reset by the API. The sizes passed
/// into the constructor are not guaranteed to persist when running on device.
/// </summary>
/// <param name="yPlaneWidth">Y plane width.</param>
/// <param name="yPlaneHeight">Y plane height.</param>
/// <param name="uvPlaneWidth">UV plane width.</param>
/// <param name="uvPlaneHeight">UV plane height.</param>
/// <param name="format">Texture format.</param>
/// <param name="mipmap">If set to <c>true</c> mipmap.</param>
public YUVTexture(int yPlaneWidth, int yPlaneHeight,
int uvPlaneWidth, int uvPlaneHeight,
TextureFormat format, bool mipmap)
{
#if UNITY_EDITOR
// We always know the simulated 'camera resolution' in the Editor, so we can also do away with the width/height options:
yPlaneWidth = VideoOverlayProvider.EMULATED_CAMERA_PACKED_WIDTH;
yPlaneHeight = VideoOverlayProvider.EMULATED_CAMERA_PACKED_Y_HEIGHT;
uvPlaneWidth = VideoOverlayProvider.EMULATED_CAMERA_PACKED_WIDTH;
uvPlaneHeight = VideoOverlayProvider.EMULATED_CAMERA_PACKED_UV_HEIGHT;
// Format needs to be ARGB32 in editor to use Texture2D.ReadPixels() in emulation
// in Unity 4.6.
RenderTexture Y = new RenderTexture(yPlaneWidth, yPlaneHeight, 0, RenderTextureFormat.ARGB32);
RenderTexture CbCr = new RenderTexture(uvPlaneWidth, uvPlaneHeight, 0, RenderTextureFormat.ARGB32);
Y.Create();
CbCr.Create();
m_videoOverlayTextureY = Y;
m_videoOverlayTextureCb = CbCr;
m_videoOverlayTextureCr = CbCr;
#else
m_videoOverlayTextureY = new Texture2D(yPlaneWidth, yPlaneHeight, format, mipmap);
m_videoOverlayTextureCb = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
m_videoOverlayTextureCr = new Texture2D(uvPlaneWidth, uvPlaneHeight, format, mipmap);
#endif
m_videoOverlayTextureY.filterMode = FilterMode.Point;
m_videoOverlayTextureCb.filterMode = FilterMode.Point;
m_videoOverlayTextureCr.filterMode = FilterMode.Point;
}
/// <summary>
/// Resizes all YUV texture planes.
/// </summary>
/// <param name="yPlaneWidth">Y plane width.</param>
/// <param name="yPlaneHeight">Y plane height.</param>
/// <param name="uvPlaneWidth">UV plane width.</param>
/// <param name="uvPlaneHeight">UV plane height.</param>
public void ResizeAll(int yPlaneWidth, int yPlaneHeight,
int uvPlaneWidth, int uvPlaneHeight)
{
#if !UNITY_EDITOR
((Texture2D)m_videoOverlayTextureY).Resize(yPlaneWidth, yPlaneHeight);
((Texture2D)m_videoOverlayTextureCb).Resize(uvPlaneWidth, uvPlaneHeight);
((Texture2D)m_videoOverlayTextureCr).Resize(uvPlaneWidth, uvPlaneHeight);
#endif
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Globalization;
using System.Net.Security;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Text;
using System.Xml;
namespace System.ServiceModel.Channels
{
public abstract class SecurityBindingElement : BindingElement
{
internal const bool defaultIncludeTimestamp = true;
internal const bool defaultAllowInsecureTransport = false;
internal const bool defaultRequireSignatureConfirmation = false;
internal const bool defaultEnableUnsecuredResponse = false;
internal const bool defaultProtectTokens = false;
private SupportingTokenParameters _endpointSupportingTokenParameters;
private bool _includeTimestamp;
private LocalClientSecuritySettings _localClientSettings;
private MessageSecurityVersion _messageSecurityVersion;
private SecurityHeaderLayout _securityHeaderLayout;
private long _maxReceivedMessageSize = TransportDefaults.MaxReceivedMessageSize;
private XmlDictionaryReaderQuotas _readerQuotas;
private bool _protectTokens = defaultProtectTokens;
internal SecurityBindingElement()
: base()
{
_messageSecurityVersion = MessageSecurityVersion.Default;
_includeTimestamp = defaultIncludeTimestamp;
_localClientSettings = new LocalClientSecuritySettings();
_endpointSupportingTokenParameters = new SupportingTokenParameters();
_securityHeaderLayout = SecurityProtocolFactory.defaultSecurityHeaderLayout;
}
internal SecurityBindingElement(SecurityBindingElement elementToBeCloned)
: base(elementToBeCloned)
{
if (elementToBeCloned == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("elementToBeCloned");
_includeTimestamp = elementToBeCloned._includeTimestamp;
_messageSecurityVersion = elementToBeCloned._messageSecurityVersion;
_securityHeaderLayout = elementToBeCloned._securityHeaderLayout;
_endpointSupportingTokenParameters = elementToBeCloned._endpointSupportingTokenParameters.Clone();
_localClientSettings = elementToBeCloned._localClientSettings.Clone();
_maxReceivedMessageSize = elementToBeCloned._maxReceivedMessageSize;
_readerQuotas = elementToBeCloned._readerQuotas;
}
public SupportingTokenParameters EndpointSupportingTokenParameters
{
get
{
return _endpointSupportingTokenParameters;
}
}
public SecurityHeaderLayout SecurityHeaderLayout
{
get
{
return _securityHeaderLayout;
}
set
{
if (!SecurityHeaderLayoutHelper.IsDefined(value))
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value"));
_securityHeaderLayout = value;
}
}
public MessageSecurityVersion MessageSecurityVersion
{
get
{
return _messageSecurityVersion;
}
set
{
if (value == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value"));
_messageSecurityVersion = value;
}
}
public bool IncludeTimestamp
{
get
{
return _includeTimestamp;
}
set
{
_includeTimestamp = value;
}
}
public LocalClientSecuritySettings LocalClientSettings
{
get
{
return _localClientSettings;
}
}
internal virtual bool SessionMode
{
get { return false; }
}
internal virtual bool SupportsDuplex
{
get { return false; }
}
internal virtual bool SupportsRequestReply
{
get { return false; }
}
internal long MaxReceivedMessageSize
{
get { return _maxReceivedMessageSize; }
set { _maxReceivedMessageSize = value; }
}
internal XmlDictionaryReaderQuotas ReaderQuotas
{
get { return _readerQuotas; }
set { _readerQuotas = value; }
}
private void GetSupportingTokensCapabilities(ICollection<SecurityTokenParameters> parameters, out bool supportsClientAuth, out bool supportsWindowsIdentity)
{
supportsClientAuth = false;
supportsWindowsIdentity = false;
foreach (SecurityTokenParameters p in parameters)
{
if (p.SupportsClientAuthentication)
supportsClientAuth = true;
if (p.SupportsClientWindowsIdentity)
supportsWindowsIdentity = true;
}
}
private void GetSupportingTokensCapabilities(SupportingTokenParameters requirements, out bool supportsClientAuth, out bool supportsWindowsIdentity)
{
supportsClientAuth = false;
supportsWindowsIdentity = false;
bool tmpSupportsClientAuth;
bool tmpSupportsWindowsIdentity;
this.GetSupportingTokensCapabilities(requirements.Endorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
this.GetSupportingTokensCapabilities(requirements.SignedEndorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
this.GetSupportingTokensCapabilities(requirements.SignedEncrypted, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity);
supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth;
supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity;
}
internal void GetSupportingTokensCapabilities(out bool supportsClientAuth, out bool supportsWindowsIdentity)
{
this.GetSupportingTokensCapabilities(this.EndpointSupportingTokenParameters, out supportsClientAuth, out supportsWindowsIdentity);
}
protected static void SetIssuerBindingContextIfRequired(SecurityTokenParameters parameters, BindingContext issuerBindingContext)
{
throw ExceptionHelper.PlatformNotSupported("SetIssuerBindingContextIfRequired is not supported.");
}
internal bool RequiresChannelDemuxer(SecurityTokenParameters parameters)
{
throw ExceptionHelper.PlatformNotSupported("RequiresChannelDemuxer is not supported.");
}
internal virtual bool RequiresChannelDemuxer()
{
foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.Endorsing)
{
if (RequiresChannelDemuxer(parameters))
{
return true;
}
}
foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.SignedEndorsing)
{
if (RequiresChannelDemuxer(parameters))
{
return true;
}
}
return false;
}
public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
if (!this.CanBuildChannelFactory<TChannel>(context))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.ChannelTypeNotSupported, typeof(TChannel)), "TChannel"));
}
_readerQuotas = context.GetInnerProperty<XmlDictionaryReaderQuotas>();
if (_readerQuotas == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.EncodingBindingElementDoesNotHandleReaderQuotas)));
}
TransportBindingElement transportBindingElement = null;
if (context.RemainingBindingElements != null)
transportBindingElement = context.RemainingBindingElements.Find<TransportBindingElement>();
if (transportBindingElement != null)
_maxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize;
IChannelFactory<TChannel> result = this.BuildChannelFactoryCore<TChannel>(context);
return result;
}
protected abstract IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context);
public override bool CanBuildChannelFactory<TChannel>(BindingContext context)
{
if (context == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CanBuildChannelFactory is not supported.");
}
private bool CanBuildSessionChannelFactory<TChannel>(BindingContext context)
{
if (!(context.CanBuildInnerChannelFactory<IRequestChannel>()
|| context.CanBuildInnerChannelFactory<IRequestSessionChannel>()
|| context.CanBuildInnerChannelFactory<IDuplexChannel>()
|| context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()))
{
return false;
}
if (typeof(TChannel) == typeof(IRequestSessionChannel))
{
return (context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>());
}
else if (typeof(TChannel) == typeof(IDuplexSessionChannel))
{
return (context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>());
}
else
{
return false;
}
}
public virtual void SetKeyDerivation(bool requireDerivedKeys)
{
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.SetKeyDerivation is not supported.");
}
internal virtual bool IsSetKeyDerivation(bool requireDerivedKeys)
{
if (!this.EndpointSupportingTokenParameters.IsSetKeyDerivation(requireDerivedKeys))
return false;
return true;
}
public override T GetProperty<T>(BindingContext context)
{
if (context == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
}
if (typeof(T) == typeof(ISecurityCapabilities))
{
return (T)(object)GetSecurityCapabilities(context);
}
else if (typeof(T) == typeof(IdentityVerifier))
{
return (T)(object)_localClientSettings.IdentityVerifier;
}
else
{
return context.GetInnerProperty<T>();
}
}
internal abstract ISecurityCapabilities GetIndividualISecurityCapabilities();
private ISecurityCapabilities GetSecurityCapabilities(BindingContext context)
{
ISecurityCapabilities thisSecurityCapability = this.GetIndividualISecurityCapabilities();
ISecurityCapabilities lowerSecurityCapability = context.GetInnerProperty<ISecurityCapabilities>();
if (lowerSecurityCapability == null)
{
return thisSecurityCapability;
}
else
{
bool supportsClientAuth = thisSecurityCapability.SupportsClientAuthentication;
bool supportsClientWindowsIdentity = thisSecurityCapability.SupportsClientWindowsIdentity;
bool supportsServerAuth = thisSecurityCapability.SupportsServerAuthentication || lowerSecurityCapability.SupportsServerAuthentication;
ProtectionLevel requestProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedRequestProtectionLevel, lowerSecurityCapability.SupportedRequestProtectionLevel);
ProtectionLevel responseProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedResponseProtectionLevel, lowerSecurityCapability.SupportedResponseProtectionLevel);
return new SecurityCapabilities(supportsClientAuth, supportsServerAuth, supportsClientWindowsIdentity, requestProtectionLevel, responseProtectionLevel);
}
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsMutualCertificateBinding() method.
static public SecurityBindingElement CreateMutualCertificateBindingElement()
{
return CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11);
}
// this method reverses CreateMutualCertificateBindingElement() logic
internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe)
{
return IsMutualCertificateBinding(sbe, false);
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsMutualCertificateBinding() method.
static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version)
{
return CreateMutualCertificateBindingElement(version, false);
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsMutualCertificateBinding() method.
static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version, bool allowSerializedSigningTokenOnReply)
{
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
}
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateMutualCertificateBindingElement is not supported.");
}
// this method reverses CreateMutualCertificateBindingElement() logic
internal static bool IsMutualCertificateBinding(SecurityBindingElement sbe, bool allowSerializedSigningTokenOnReply)
{
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.IsMutualCertificateBinding is not supported.");
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsUserNameOverTransportBinding() method.
static public TransportSecurityBindingElement CreateUserNameOverTransportBindingElement()
{
TransportSecurityBindingElement result = new TransportSecurityBindingElement();
result.EndpointSupportingTokenParameters.SignedEncrypted.Add(
new UserNameSecurityTokenParameters());
result.IncludeTimestamp = true;
return result;
}
// this method reverses CreateMutualCertificateBindingElement() logic
internal static bool IsUserNameOverTransportBinding(SecurityBindingElement sbe)
{
// do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
if (!sbe.IncludeTimestamp)
return false;
if (!(sbe is TransportSecurityBindingElement))
return false;
SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 1 || parameters.Endorsing.Count != 0 || parameters.SignedEndorsing.Count != 0)
return false;
UserNameSecurityTokenParameters userNameParameters = parameters.SignedEncrypted[0] as UserNameSecurityTokenParameters;
if (userNameParameters == null)
return false;
return true;
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsCertificateOverTransportBinding() method.
static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement(MessageSecurityVersion version)
{
if (version == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
}
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateCertificateOverTransportBindingElement is not supported.");
}
// this method reverses CreateMutualCertificateBindingElement() logic
internal static bool IsCertificateOverTransportBinding(SecurityBindingElement sbe)
{
// do not check local settings: sbe.LocalServiceSettings and sbe.LocalClientSettings
if (!sbe.IncludeTimestamp)
return false;
if (!(sbe is TransportSecurityBindingElement))
return false;
SupportingTokenParameters parameters = sbe.EndpointSupportingTokenParameters;
if (parameters.Signed.Count != 0 || parameters.SignedEncrypted.Count != 0 || parameters.Endorsing.Count != 1 || parameters.SignedEndorsing.Count != 0)
return false;
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.IsCertificateOverTransportBinding is not supported.");
}
// If any changes are made to this method, please make sure that they are
// reflected in the corresponding IsSecureConversationBinding() method.
static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity)
{
throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateSecureConversatationBindingElement is not supported.");
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "{0}:", this.GetType().ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "IncludeTimestamp: {0}", _includeTimestamp.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "MessageSecurityVersion: {0}", this.MessageSecurityVersion.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "SecurityHeaderLayout: {0}", _securityHeaderLayout.ToString()));
sb.AppendLine(String.Format(CultureInfo.InvariantCulture, "ProtectTokens: {0}", _protectTokens.ToString()));
sb.AppendLine("EndpointSupportingTokenParameters:");
sb.AppendLine(" " + this.EndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n "));
return sb.ToString().Trim();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
using System.IO;
using DeadCode.WME.Global;
namespace DeadCode.WME.StringTableMgr
{
#region Delegates
public delegate void ProgressChangeDelegate(object sender, ProgressChangeEventArgs e);
public class ProgressChangeEventArgs : EventArgs
{
public readonly int CurrentItem;
public readonly int TotalItems;
public readonly string Description;
public ProgressChangeEventArgs(int CurrentItem, int TotalItems, string Description)
{
this.CurrentItem = CurrentItem;
this.TotalItems = TotalItems;
this.Description = Description;
}
};
public enum LogSeverity
{
Information, Warning, Error
};
public delegate void AddLogDelegate(object sender, AddLogEventArgs e);
public class AddLogEventArgs : EventArgs
{
public readonly LogSeverity Severity;
public readonly string Message;
public AddLogEventArgs(LogSeverity Severity, string Message)
{
this.Severity = Severity;
this.Message = Message;
}
};
#endregion
public class StringItem
{
public string ID;
public string Value;
public string Filename;
public int Line;
public bool Ignored;
public IgnoreReason IgnoreReason;
public string OriginalString;
public bool IsScriptItem;
public int Order;
public bool SavedOk = false;
//////////////////////////////////////////////////////////////////////////
public static int CompareByLine(StringItem p1, StringItem p2)
{
if (p1 == null)
{
if (p2 == null) return 0;
else return -1;
}
else
{
if (p2 == null) return 1;
else
{
if (p1.Line < p2.Line) return -1;
else if (p1.Line > p2.Line) return 1;
else return 0;
}
}
}
};
public enum IgnoreReason
{
InIgnoreList,
AlreadyInTable,
KnownCodePattern,
IsFilename,
SelectedByUser,
}
//////////////////////////////////////////////////////////////////////////
public class StringTableMgr
{
public string ProjectFile;
public string StringTableFile;
public bool BackupOldFiles = true;
public List<string> IgnoreList = new List<string>();
//////////////////////////////////////////////////////////////////////////
public StringTableMgr()
{
IgnoreList.Add("savegame:");
IgnoreList.Add(",g");
}
public event ProgressChangeDelegate OnProgressChange;
//////////////////////////////////////////////////////////////////////////
public void ReportProgress(int CurrentItem, int TotalItems, string Description)
{
if (OnProgressChange != null)
OnProgressChange(this, new ProgressChangeEventArgs(CurrentItem, TotalItems, Description));
}
public event AddLogDelegate OnAddLog;
//////////////////////////////////////////////////////////////////////////
public void AddLog(LogSeverity Severity, string Message, bool NewLine)
{
if (OnAddLog != null)
OnAddLog(this, new AddLogEventArgs(Severity, Message + (NewLine?"\n":"")));
}
//////////////////////////////////////////////////////////////////////////
public void AddLog(string Message, bool NewLine)
{
AddLog(LogSeverity.Information, Message, NewLine);
}
//////////////////////////////////////////////////////////////////////////
public void AddLog(string Message)
{
AddLog(Message, true);
}
public List<StringItem> ProjectStrings;
public List<StringItem> IgnoredStrings;
public List<StringItem> TableStrings;
//////////////////////////////////////////////////////////////////////////
public bool ScanProject()
{
// load project strings
AddLog("Scanning project...", false);
ProjectStrings = new List<StringItem>();
StringExtractor se = new StringExtractor(this);
bool Ret = se.ExtractProjectStrings(this.ProjectFile, "*.script;*.inc", "*.scene;*.entity;*.actor;*.window;*.items;*.game");
if (!Ret) return false;
int Order = 0;
foreach(StringLocation Str in se.Strings)
{
Order++;
StringItem Item = new StringItem();
ExtractStringParts(Str.Value, out Item.ID, out Item.Value);
Item.Line = Str.Line;
Item.Filename = Str.Filename;
Item.OriginalString = Str.Value;
Item.IsScriptItem = (Str.Type == StringLocation.StringType.ScriptFile);
Item.Order = Order;
Item.Value = Item.Value.Replace("~n", "|");
Item.Value = Item.Value.Replace("~\"", "\"");
ProjectStrings.Add(Item);
}
AddLog(ProjectStrings.Count.ToString() + " strings found");
// load string table string
AddLog("Reading string table...", false);
LoadStringTable(StringTableFile);
AddLog(TableStrings.Count.ToString() + " strings found");
if (StringTableUsingUtf8) AddLog("String table is using UTF-8 format");
// perform initial string classification
ClassifyStrings();
return true;
}
private bool StringTableUsingUtf8 = true;
//////////////////////////////////////////////////////////////////////////
private bool LoadStringTable(string Filename)
{
TableStrings = new List<StringItem>();
StringTableUsingUtf8 = true;
try
{
using(FileStream Stream = new FileStream(Filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
StreamReader Reader = new StreamReader(Stream, Encoding.Default, true);
string Line;
int LineNum = 0;
while ((Line = Reader.ReadLine()) != null)
{
LineNum++;
if (Line.StartsWith(";")) continue;
string[] LineSplit = Line.Split(new char[] { '\t' });
if (LineSplit.Length != 2) continue;
StringItem Item = new StringItem();
Item.ID = LineSplit[0];
Item.Value = LineSplit[1];
Item.Filename = Filename;
Item.Line = LineNum;
TableStrings.Add(Item);
}
StringTableUsingUtf8 = (Reader.CurrentEncoding == Encoding.UTF8);
return true;
}
}
catch
{
return false;
}
}
//////////////////////////////////////////////////////////////////////////
private void ClassifyStrings()
{
AddLog("Classifying strings...", false);
IgnoredStrings = new List<StringItem>();
int CurrentIndex = 0;
foreach(StringItem Item in ProjectStrings)
{
CurrentIndex++;
ReportProgress(CurrentIndex, ProjectStrings.Count, Item.Value);
Item.Ignored = false;
// remove strings already present in the string table
if(Item.ID != string.Empty && IsIDInTable(Item.ID))
{
Item.Ignored = true;
Item.IgnoreReason = IgnoreReason.AlreadyInTable;
continue;
}
// keep strings with ID
if (Item.ID != string.Empty) continue;
// keep non-script strings
if (!Item.IsScriptItem) continue;
// remove strings in ignore list
if(IsStringIgnored(Item.Value))
{
Item.Ignored = true;
Item.IgnoreReason = IgnoreReason.InIgnoreList;
continue;
}
// remove filenames
WmeProject Project = new WmeProject(this.ProjectFile);
if(Project.ContainsFile(Item.Value))
{
Item.Ignored = true;
Item.IgnoreReason = IgnoreReason.IsFilename;
continue;
}
// check one-word terms against well known code patterns
if (Item.Value.IndexOf(' ') < 0 && IsWellKnownPattern(Item))
{
Item.Ignored = true;
Item.IgnoreReason = IgnoreReason.KnownCodePattern;
continue;
}
}
for(int i=0; i<ProjectStrings.Count; i++)
{
StringItem Item = ProjectStrings[i];
if(Item.Ignored)
{
IgnoredStrings.Add(Item);
ProjectStrings.RemoveAt(i);
i--;
}
}
ReportProgress(0, 0, "");
AddLog(IgnoredStrings.Count.ToString() + " strings automatically ignored");
}
private string[] ScriptPatterns = new string[]
{
".SelectedItem=\"%string%\"",
".SelectedItem==\"%string%\"",
".SelectedItem!=\"%string%\"",
".CanHandleEvent(\"%string%\")",
".CanHandleMethod(\"%string%\")",
".ApplyEvent(\"%string%\")",
".GetNode(\"%string%\")",
".GetLayer(\"%string%\")",
".GetControl(\"%string%\")",
".GetWidget(\"%string%\")",
".GetItem(\"%string%\")",
".TakeItem(\"%string%\")",
".DropItem(\"%string%\")",
".QueryItem(\"%string%\")",
".IsItemTaken(\"%string%\")",
".HasItem(\"%string%\")",
".Type==\"%string%\"",
".Type!=\"%string%\"",
".Name==\"%string%\"",
".Name!=\"%string%\"",
".PrevScene==\"%string%\"",
".PrevScene!=\"%string%\"",
"case\"%string%\":",
".CreateEntity(\"%string%\")",
".CreateWindow(\"%string%\")",
".CreateButton(\"%string%\")",
".CreateStatic(\"%string%\")",
".CreateEditor(\"%string%\")",
".StickToRegion(\"%string%\")",
".RegReadString(\"%string%\"",
".RegReadNumber(\"%string%\"",
".RegWriteString(\"%string%\"",
".RegWriteNumber(\"%string%\"",
".PlayAnim(\"%string%\")",
".PlayAnimAsync(\"%string%\")",
"Game.StartDlgBranch(\"%string%\")",
"Game.EndDlgBranch(\"%string%\")",
};
//////////////////////////////////////////////////////////////////////////
private bool IsWellKnownPattern(StringItem Item)
{
string ScriptLine = GetFileLine(Item.Filename, Item.Line);
ScriptLine = ScriptLine.ToUpper();
ScriptLine = ScriptLine.Replace(" ", "");
ScriptLine = ScriptLine.Replace("\t", "");
foreach(string ScriptPattern in ScriptPatterns)
{
string Pattern = ScriptPattern.Replace("%string%", Item.OriginalString);
Pattern = Pattern.ToUpper();
if (ScriptLine.IndexOf(Pattern) >= 0) return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
private bool IsStringIgnored(string Str)
{
return IgnoreList.Contains(Str);
}
//////////////////////////////////////////////////////////////////////////
private bool IsIDInTable(string ID)
{
foreach(StringItem Item in TableStrings)
{
if (string.Compare(ID, Item.ID, true)==0) return true;
}
return false;
}
//////////////////////////////////////////////////////////////////////////
private void ExtractStringParts(string Str, out string ID, out string Value)
{
ID = "";
Value = Str;
if(Str.Length > 2 && Str.StartsWith("/"))
{
int i = Str.IndexOf('/', 1);
if(i>=0)
{
ID = Str.Substring(1, i - 1);
Value = Str.Substring(i + 1);
}
}
}
//////////////////////////////////////////////////////////////////////////
private string GetFileLine(string Filename, int Line)
{
try
{
using (StreamReader sr = new StreamReader(Filename, Encoding.Default, true))
{
string ReadLine;
int LineNum = 0;
while ((ReadLine = sr.ReadLine()) != null)
{
LineNum++;
if (LineNum == Line) return ReadLine;
}
}
return "";
}
catch
{
return "";
}
}
//////////////////////////////////////////////////////////////////////////
public class StringID : IComparable<StringID>
{
public string ID;
public int MaxNum;
public StringID(string ID, int MaxNum)
{
this.ID = ID;
this.MaxNum = MaxNum;
}
public int CompareTo(StringID o)
{
return string.Compare(this.ID, o.ID);
}
};
//////////////////////////////////////////////////////////////////////////
public StringID[] GetUsedIDs()
{
List<StringID> IdList = new List<StringID>();
foreach(StringItem StrItem in ProjectStrings)
AddID(IdList, StrItem);
foreach (StringItem StrItem in TableStrings)
AddID(IdList, StrItem);
return IdList.ToArray();
}
//////////////////////////////////////////////////////////////////////////
private void AddID(List<StringID> IdList, StringItem StrItem)
{
if (StrItem.ID == string.Empty) return;
string StrID;
int MaxNum;
GetIDBase(StrItem.ID, out StrID, out MaxNum);
if (StrID == string.Empty) return;
StringID ID = new StringID(StrID, MaxNum);
int Index = IdList.BinarySearch(ID);
if (Index < 0)
{
IdList.Add(ID);
IdList.Sort();
}
else IdList[Index].MaxNum = Math.Max(IdList[Index].MaxNum, MaxNum);
}
//////////////////////////////////////////////////////////////////////////
public void GetIDBase(string ID, out string IdBase, out int MaxNum)
{
IdBase = "";
string Num = "";
bool InId = true;
for (int i = 0; i < ID.Length; i++)
{
char c = ID[i];
if (InId)
{
if (char.IsLetter(c)) IdBase += c;
else
{
InId = false;
if (char.IsDigit(c)) Num += c;
}
}
else
{
if (char.IsDigit(c)) Num += c;
}
}
IdBase = IdBase.ToLower();
if (Num != string.Empty) MaxNum = int.Parse(Num);
else MaxNum = 0;
}
private class FileToChange : IComparable<FileToChange>
{
public string Filename;
public List<StringItem> Items;
public FileToChange(string Filename)
{
this.Filename = Filename;
this.Items = new List<StringItem>();
}
public int CompareTo(FileToChange o)
{
return string.Compare(this.Filename, o.Filename, true);
}
};
//////////////////////////////////////////////////////////////////////////
public bool SaveChanges()
{
bool Ret = true;
List<FileToChange> Files = new List<FileToChange>();
AddLog("Preparing file list...");
ReportProgress(0, 0, "Preparing file list...");
foreach(StringItem StrItem in ProjectStrings)
{
if (StrItem.ID == string.Empty) continue;
FileToChange File;
int Index = Files.BinarySearch(new FileToChange(StrItem.Filename));
if (Index < 0)
{
File = new FileToChange(StrItem.Filename);
Files.Add(File);
Files.Sort();
}
else File = Files[Index];
File.Items.Add(StrItem);
}
AddLog("Modifying files...");
int CurrentFile = 0;
foreach(FileToChange File in Files)
{
CurrentFile++;
ReportProgress(CurrentFile, Files.Count, File.Filename);
if (!ProcessFile(File)) Ret = false;
}
AddLog("Adding new items to string table...");
ReportProgress(0, 0, "");
if (!ProcessStringTable()) Ret = false;
if(Ret) AddLog("Done.");
else AddLog("Done with errors.");
ReportProgress(0, 0, "");
return Ret;
}
//////////////////////////////////////////////////////////////////////////
private bool ProcessStringTable()
{
try
{
if (this.BackupOldFiles) BackupFile(StringTableFile);
using (StreamWriter sw = new StreamWriter(StringTableFile, true, StringTableUsingUtf8?Encoding.UTF8:Encoding.Default))
{
foreach (StringItem StrItem in ProjectStrings)
{
if (!StrItem.SavedOk) continue;
if (StrItem.ID == string.Empty) continue;
sw.WriteLine(StrItem.ID + "\t" + StrItem.Value);
}
}
return true;
}
catch(Exception e)
{
AddLog("Error modifying string table '" + StringTableFile + "':");
AddLog(e.Message);
return false;
}
}
//////////////////////////////////////////////////////////////////////////
private bool ProcessFile(FileToChange File)
{
try
{
if (this.BackupOldFiles) BackupFile(File.Filename);
Encoding FileEncoding = Encoding.Default;
List<string> Lines = new List<string>();
// read original file
using (StreamReader sr = new StreamReader(File.Filename, Encoding.Default, true))
{
string ReadLine;
int LineNum = 0;
while ((ReadLine = sr.ReadLine()) != null)
{
LineNum++;
Lines.Add(ProcessLine(LineNum, ReadLine, File));
}
FileEncoding = sr.CurrentEncoding;
}
// save new file
using (StreamWriter sw = new StreamWriter(File.Filename, false, FileEncoding))
{
foreach(string Line in Lines)
{
sw.WriteLine(Line);
}
}
// mark items as saved ok
foreach(StringItem Str in File.Items)
{
Str.SavedOk = true;
}
return true;
}
catch(Exception e)
{
AddLog("Error modifying file '" + File.Filename + "':");
AddLog(e.Message);
// mark items as NOT saved ok
foreach (StringItem Str in File.Items)
{
Str.SavedOk = false;
}
return false;
}
}
//////////////////////////////////////////////////////////////////////////
private string ProcessLine(int LineNum, string Line, FileToChange File)
{
string OutLine = Line;
foreach(StringItem StrItem in File.Items)
{
if(StrItem.Line == LineNum)
{
string OldString = "\"" + StrItem.OriginalString + "\"";
string NewString = StrItem.Value;
NewString = NewString.Replace("|", "~n");
NewString = NewString.Replace("\"", "~\"");
NewString = "\"/" + StrItem.ID + "/" + NewString + "\"";
if(OutLine.IndexOf(OldString) < 0)
{
AddLog("Cannot find original string " + OldString);
AddLog("(file: " + File.Filename + ", line: " + LineNum.ToString() + ")");
}
else OutLine = OutLine.Replace(OldString, NewString);
}
}
return OutLine;
}
//////////////////////////////////////////////////////////////////////////
private void BackupFile(string Filename)
{
if (!File.Exists(Filename)) return;
string BackupFilename;
int Counter = 0;
do
{
BackupFilename = Filename + ".bak" + (Counter == 0 ? "" : Counter.ToString());
Counter++;
}
while (File.Exists(BackupFilename));
File.Copy(Filename, BackupFilename);
}
#region Settings loading/saving
//////////////////////////////////////////////////////////////////////////
public void SaveSettings(SettingsNode RootNode)
{
SettingsNode Section = RootNode.GetNode("StringTableMgr", true, true);
if (Section == null) return;
Section.Clear();
Section.SetValue("ProjectFile", ProjectFile);
Section.SetValue("StringTableFile", StringTableFile);
Section.SetValue("BackupOldFiles", BackupOldFiles);
SettingsNode IgnoreItems = new SettingsNode("IgnoreList");
foreach (string Item in IgnoreList)
{
IgnoreItems.Children.Add(new SettingsNode("Item", Item));
}
Section.Children.Add(IgnoreItems);
}
//////////////////////////////////////////////////////////////////////////
public void LoadSettings(SettingsNode RootNode)
{
SettingsNode Section = RootNode.GetNode("StringTableMgr", true);
if (Section == null) return;
ProjectFile = Section.GetString("ProjectFile");
StringTableFile = Section.GetString("StringTableFile");
BackupOldFiles = Section.GetBool("BackupOldFiles");
IgnoreList.Clear();
SettingsNode IgnoreItems = Section.GetNode("IgnoreList");
if (IgnoreItems != null)
{
foreach (SettingsNode Node in IgnoreItems.Children)
{
IgnoreList.Add(Node.GetString());
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall.IO;
namespace FlatRedBall.Gui
{
#region XML Docs
/// <summary>
/// A TextBox-like window which allows the user to browse the folder structure and select a
/// file. The selected file will appear in the TextBox.
/// </summary>
#endregion
public class FileTextBox : Window
{
#region Fields
Button mButton;
TextBox mTextBox;
bool mKeepFilesRelative = false;
List<string> mFileTypes = new List<string>();
string mDefaultDirectory = "";
#endregion
#region Properties
public string DefaultDirectory
{
get { return mDefaultDirectory; }
set { mDefaultDirectory = value; }
}
public bool KeepFilesRelative
{
get { return mKeepFilesRelative; }
set { mKeepFilesRelative = value; }
}
public override float ScaleX
{
get
{
return mScaleX;
}
set
{
mScaleX = value;
mButton.SetPositionTL(2*value - 1.3f, mScaleY);
mTextBox.ScaleX = value - 1.4f;
mTextBox.SetPositionTL(mScaleX -.9f, mScaleY);
}
}
public string Text
{
get { return mTextBox.Text; }
set { mTextBox.Text = value; }
}
public TextBox TextBox
{
get { return mTextBox; }
}
#endregion
#region Events
public event GuiMessage FileSelect;
#endregion
#region Event Methods
private void FileWindowOkClick(Window callingWindow)
{
#if !SILVERLIGHT
mTextBox.Text = ((FileWindow)callingWindow).Results[0];
if (mKeepFilesRelative)
{
mTextBox.Text = FileManager.MakeRelative(mTextBox.Text);
}
if (FileSelect != null)
{
FileSelect(this);
}
#endif
}
private void OpenFileWindow(Window callingWindow)
{
#if !SILVERLIGHT
FileWindow fileWindow = GuiManager.AddFileWindow();
fileWindow.SetToLoad();
if (string.IsNullOrEmpty(mDefaultDirectory) == false)
{
fileWindow.SetDirectory(mDefaultDirectory);
}
fileWindow.OkClick += FileWindowOkClick;
fileWindow.SetFileType(mFileTypes);
if (!string.IsNullOrEmpty(Text))
{
try
{
string directory = FileManager.GetDirectory(Text);
if (System.IO.Directory.Exists(directory))
{
fileWindow.SetDirectory(directory);
}
}
catch
{
// don't worry about it, this is just for convenience.
}
}
#endif
}
#endregion
#region Methods
#region Constructor
public FileTextBox(Cursor cursor)
: base(cursor)
{
mTextBox = new TextBox(mCursor);
AddWindow(mTextBox);
mTextBox.fixedLength = false;
mButton = new Button(mCursor);
AddWindow(mButton);
mButton.Text = "...";
mButton.ScaleX = .9f;
mButton.Click += OpenFileWindow;
this.ScaleY = 1.4f;
ScaleX = 8;
}
#endregion
#region Public Methods
/// <summary>
/// Sets the filetype that the FileWindow can view.
/// </summary>
/// <remarks>
/// This method also clears all types. Setting a filter then calling SetFileType clears the filter.
///
/// Setting the filetype as "graphic" sets all of the file types that FRB can load.
/// <seealso cref="FlatRedBall.Gui.FileWindow.Filter"/>
/// </remarks>
/// <param name="FileType">The file types specified by extension. </param>
public void SetFileType(string fileType)
{
mFileTypes.Clear();
if (fileType == "graphic")
{
AddFileType("bmp");
AddFileType("png");
AddFileType("jpg");
AddFileType("tga");
AddFileType("dds");
}
else if (fileType == "graphic and animation")
{
AddFileType("bmp");
AddFileType("png");
AddFileType("jpg");
AddFileType("tga");
AddFileType("dds");
AddFileType("ach");
AddFileType("achx");
}
else
AddFileType(fileType);
}
public void SetFileType(List<string> FileType)
{
mFileTypes = FileType;
}
#endregion
#region Private Methods
private void AddFileType(string type)
{
if (mFileTypes.Contains(type) == false)
this.mFileTypes.Add(type);
}
#endregion
#endregion
}
}
| |
//! \file ImageMI4.cs
//! \date Sun Jul 12 15:40:39 2015
//! \brief ShiinaRio engine image format.
//
// Copyright (C) 2015 by morkt
//
// 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.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
namespace GameRes.Formats.ShiinaRio
{
[Export(typeof(ImageFormat))]
public class Mi4Format : ImageFormat
{
public override string Tag { get { return "MI4"; } }
public override string Description { get { return "ShiinaRio image format"; } }
public override uint Signature { get { return 0x3449414D; } } // 'MAI4'
public override ImageMetaData ReadMetaData (IBinaryStream file)
{
file.Position = 8;
uint width = file.ReadUInt32();
uint height = file.ReadUInt32();
return new ImageMetaData
{
Width = width,
Height = height,
BPP = 24,
};
}
public override ImageData Read (IBinaryStream stream, ImageMetaData info)
{
var reader = new Reader (stream, (int)info.Width, (int)info.Height);
try
{
reader.Unpack (MaiVersion.Second);
}
catch
{
reader.Unpack (MaiVersion.First);
}
return ImageData.Create (info, PixelFormats.Bgr24, null, reader.Data, reader.Stride);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("Mi4Format.Write not implemented");
}
internal enum MaiVersion
{
First, Second
}
internal sealed class Reader
{
IBinaryStream m_input;
byte[] m_output;
int m_stride;
public byte[] Data { get { return m_output; } }
public int Stride { get { return m_stride; } }
public Reader (IBinaryStream file, int width, int height)
{
m_input = file;
m_stride = width * 3;
m_output = new byte[m_stride*height];
}
public void Unpack (MaiVersion version = MaiVersion.First)
{
m_input.Position = 0x10;
m_bit_count = 0;
LoadBits();
if (MaiVersion.First == version)
UnpackV1();
else
UnpackV2();
}
int m_bit_count;
uint m_bits;
void LoadBits ()
{
for (int i = 0; i < 4; ++i)
{
int b = m_input.ReadByte();
if (-1 == b)
break;
m_bits = (m_bits >> 8) | (uint)(b << 24);
m_bit_count += 8;
}
}
uint GetBit ()
{
uint bit = m_bits >> 31;
m_bits <<= 1;
if (0 == --m_bit_count)
{
LoadBits();
}
return bit;
}
uint GetBits (int count)
{
int avail_bits = Math.Min (count, m_bit_count);
uint bits = m_bits >> (32 - avail_bits);
m_bits <<= avail_bits;
m_bit_count -= avail_bits;
count -= avail_bits;
if (0 == m_bit_count)
{
LoadBits();
if (count > 0)
{
bits = bits << count | m_bits >> (32 - count);
m_bits <<= count;
m_bit_count -= count;
}
}
return bits;
}
void UnpackV1 ()
{
int dst = 0;
byte b = 0, g = 0, r = 0;
while (dst < m_output.Length)
{
if (GetBit() == 0)
{
if (GetBit() != 0)
{
b = m_input.ReadUInt8();
g = m_input.ReadUInt8();
r = m_input.ReadUInt8();
}
else if (GetBit() != 0)
{
byte v = (byte)GetBits (2);
if (3 == v)
{
b = m_output[dst - m_stride];
g = m_output[dst - m_stride + 1];
r = m_output[dst - m_stride + 2];
}
else
{
b += (byte)(v - 1);
g += (byte)(GetBits(2) - 1);
r += (byte)(GetBits(2) - 1);
}
}
else if (GetBit() != 0)
{
byte v = (byte)(GetBits(3));
if (7 == v)
{
b = m_output[dst - m_stride + 3];
g = m_output[dst - m_stride + 4];
r = m_output[dst - m_stride + 5];
}
else
{
b += (byte)(v - 3);
g += (byte)(GetBits(3) - 3);
r += (byte)(GetBits(3) - 3);
}
}
else if (GetBit() != 0)
{
byte v = (byte)GetBits (4);
if (0xF == v)
{
b = m_output[dst - m_stride - 3];
g = m_output[dst - m_stride - 2];
r = m_output[dst - m_stride - 1];
}
else
{
b += (byte)(v - 7);
g += (byte)(GetBits(4) - 7);
r += (byte)(GetBits(4) - 7);
}
}
else
{
b += (byte)(GetBits(5) - 15);
g += (byte)(GetBits(5) - 15);
r += (byte)(GetBits(5) - 15);
}
}
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
}
}
void UnpackV2 ()
{
int dst = 0;
byte b = 0, g = 0, r = 0;
while (dst < m_output.Length)
{
if (GetBit() == 0)
{
if (GetBit() != 0)
{
if (m_input.PeekByte() != -1)
{
b = m_input.ReadUInt8();
g = m_input.ReadUInt8();
r = m_input.ReadUInt8();
}
}
else if (GetBit() != 0)
{
byte v = (byte)(GetBits(2));
if (3 == v)
{
b = m_output[dst - m_stride];
g = m_output[dst - m_stride + 1];
r = m_output[dst - m_stride + 2];
}
else
{
b += (byte)(v - 1);
v = (byte)GetBits (2);
if (3 == v)
{
if (GetBit() != 0)
{
b = m_output[dst - m_stride - 3];
g = m_output[dst - m_stride - 2];
r = m_output[dst - m_stride - 1];
}
else
{
b = m_output[dst - m_stride + 3];
g = m_output[dst - m_stride + 4];
r = m_output[dst - m_stride + 5];
}
}
else
{
g += (byte)(v - 1);
r += (byte)(GetBits(2) - 1);
}
}
}
else if (GetBit() != 0)
{
byte v = (byte)(GetBits(3));
if (7 == v)
{
b = m_output[dst - m_stride];
g = m_output[dst - m_stride + 1];
r = m_output[dst - m_stride + 2];
b += (byte)(GetBits(3) - 3);
g += (byte)(GetBits(3) - 3);
r += (byte)(GetBits(3) - 3);
}
else
{
b += (byte)(v - 3);
g += (byte)(GetBits(3) - 3);
r += (byte)(GetBits(3) - 3);
}
}
else if (GetBit() != 0)
{
b += (byte)(GetBits(4) - 7);
g += (byte)(GetBits(4) - 7);
r += (byte)(GetBits(4) - 7);
}
else
{
b += (byte)(GetBits(5) - 15);
g += (byte)(GetBits(5) - 15);
r += (byte)(GetBits(5) - 15);
}
}
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
}
}
}
}
}
| |
/***************************************************************************
copyright : (C) 2005 by Brian Nickel
email : [email protected]
based on : id3v1tag.cpp from TagLib
***************************************************************************/
/***************************************************************************
* This library is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License version *
* 2.1 as published by the Free Software Foundation. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
* USA *
***************************************************************************/
using System.Collections;
using System;
namespace TagLib.Id3v1
{
public class Tag : TagLib.Tag
{
//////////////////////////////////////////////////////////////////////////
// private properties
//////////////////////////////////////////////////////////////////////////
File file;
long tag_offset;
private string title;
private string artist;
private string album;
private string year;
private string comment;
private byte track;
private byte genre;
private static StringHandler string_handler = new StringHandler ();
//////////////////////////////////////////////////////////////////////////
// public static fields
//////////////////////////////////////////////////////////////////////////
public static readonly ByteVector FileIdentifier = "TAG";
public static StringHandler DefaultStringHandler
{
set {string_handler = value;}
}
//////////////////////////////////////////////////////////////////////////
// public methods
//////////////////////////////////////////////////////////////////////////
public Tag ()
{
file = null;
tag_offset = -1;
title = artist = album = year = comment = "";
track = 0;
genre = 255;
}
public Tag (File file, long tag_offset)
{
this.file = file;
this.tag_offset = tag_offset;
Read ();
}
public ByteVector Render ()
{
ByteVector data = new ByteVector ();
data.Add (FileIdentifier);
data.Add (string_handler.Render (title ).Resize (30));
data.Add (string_handler.Render (artist ).Resize (30));
data.Add (string_handler.Render (album ).Resize (30));
data.Add (string_handler.Render (year ).Resize ( 4));
data.Add (string_handler.Render (comment).Resize (28));
data.Add ((byte) 0);
data.Add (track);
data.Add (genre);
return data;
}
//////////////////////////////////////////////////////////////////////////
// public properties
//////////////////////////////////////////////////////////////////////////
public override string Title
{
get {return title;}
set {title = value != null ? value.Trim () : "";}
}
public override string [] AlbumArtists
{
get {return new string [] {artist};}
set {artist = (new StringList (value)).ToString (",").Trim ();}
}
public override string Album
{
get {return album;}
set {album = value != null ? value.Trim () : "";}
}
public override string Comment
{
get {return comment;}
set {comment = value != null ? value.Trim () : "";}
}
public override string [] Genres
{
get
{
string genre_name = GenreList.Genre (genre);
return (genre_name != null) ? new string [] {genre_name} : new string [] {};
}
set {genre = (value != null && value.Length > 0) ? GenreList.GenreIndex (value [0].Trim ()) : (byte) 255;}
}
public override uint Year
{
get
{
try {return System.UInt32.Parse (year);}
catch {return 0;}
}
set {year = value > 0 ? value.ToString () : "";}
}
public override uint Track
{
get {return track;}
set {track = (byte) (value < 256 ? value : 0);}
}
//////////////////////////////////////////////////////////////////////////
// protected methods
//////////////////////////////////////////////////////////////////////////
protected void Read ()
{
file.Seek (tag_offset);
// read the tag -- always 128 bytes
ByteVector data = file.ReadBlock (128);
// some initial sanity checking
if (data.Count != 128 || !data.StartsWith ("TAG"))
throw new CorruptFileException ("ID3v1 tag is not valid or could "
+ " not be read at the specified "
+ "offset.");
int offset = 3;
title = string_handler.Parse (data.Mid (offset, 30));
offset += 30;
artist = string_handler.Parse (data.Mid (offset, 30));
offset += 30;
album = string_handler.Parse (data.Mid (offset, 30));
offset += 30;
year = string_handler.Parse (data.Mid (offset, 4));
offset += 4;
// Check for ID3v1.1 -- Note that ID3v1 *does not* support "track zero" -- this
// is not a bug in TagLib. Since a zeroed byte is what we would expect to
// indicate the end of a C-String, specifically the comment string, a value of
// zero must be assumed to be just that.
if (data [offset + 28] == 0 && data[offset + 29] != 0)
{
// ID3v1.1 detected
comment = string_handler.Parse (data.Mid (offset, 28));
track = data [offset + 29];
}
else
comment = string_handler.Parse (data.Mid (offset, 30));
offset += 30;
genre = data [offset];
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012;
using System;
using System.Collections;
using System.IO;
using System.Globalization;
using System.Reflection;
using System.Resources;
using Microsoft.CSharp.RuntimeBinder;
public enum ErrorElementId
{
None,
SK_METHOD, // method
SK_CLASS, // type
SK_NAMESPACE, // namespace
SK_FIELD, // field
SK_PROPERTY, // property
SK_UNKNOWN, // element
SK_VARIABLE, // variable
SK_EVENT, // event
SK_TYVAR, // type parameter
SK_ALIAS, // using alias
ERRORSYM, // <error>
NULL, // <null>
GlobalNamespace, // <global namespace>
MethodGroup, // method group
AnonMethod, // anonymous method
Lambda, // lambda expression
AnonymousType, // anonymous type
}
public enum ErrorMessageId
{
None,
BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}'
IntDivByZero, // Division by constant zero
BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}'
BadIndexCount, // Wrong number of indices inside []; expected '{0}'
BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}'
NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}'
NoExplicitConv, // Cannot convert type '{0}' to '{1}'
ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}'
AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'
AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}'
ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type
WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}'
NoSuchMember, // '{0}' does not contain a definition for '{1}'
ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}'
AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}'
BadAccess, // '{0}' is inaccessible due to its protection level
MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}'
AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer
NoConstructors, // The type '{0}' has no constructors defined
BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor
PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor
ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead
AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer)
RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor)
AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only
AbstractBaseCall, // Cannot call an abstract base member: '{0}'
RefProperty, // A property or indexer may not be passed as an out or ref parameter
ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}')
FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression
UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers
BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters
MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false
CheckedOverflow, // The operation overflows at compile time in checked mode
ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override)
AmbigMember, // Ambiguity between '{0}' and '{1}'
SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf)
FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}'
CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available.
CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor.
BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression
NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?)
InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible
InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible
BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments
BadTypeArgument, // The type '{0}' may not be used as a type argument
TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments
HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments
NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}'
GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'.
GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints.
GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'.
GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'.
TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead.
BadRetType, // '{1} {0}' has the wrong return type
CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly.
MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method?
RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}'
ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}'
CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}'
BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}'
ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}'
AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}'
PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported
PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly
BindToBogus, // '{0}' is not supported by the language
CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor
BogusType, // '{0}' is a type not supported by the language
MissingPredefinedMember, // Missing compiler required member '{0}.{1}'
LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type
UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions
ConvertToStaticClass, // Cannot convert to static type '{0}'
GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments
PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer
NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?)
ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates
BadArgCount, // No overload for method '{0}' takes '{1}' arguments
BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments
BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}'
RefLvalueExpected, // A ref or out argument must be an assignable variable
BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it)
BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}'
BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}'
BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments
BadDelArgTypes, // Delegate '{0}' has some invalid arguments
AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only
RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only
ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable
BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword
// DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED)
BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword
AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer)
RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor)
AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer)
RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor)
AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}'
RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}'
ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead.
DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>'
BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments
BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments
BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}'
BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments
InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method.
NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified
BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}'
BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}'
DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times
NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given
}
public enum RuntimeErrorId
{
None,
// RuntimeBinderInternalCompilerException
InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation
// ArgumentException
BindRequireArguments, // Cannot bind call with no calling object
// RuntimeBinderException
BindCallFailedOverloadResolution, // Overload resolution failed
// ArgumentException
BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments
// ArgumentException
BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument
// RuntimeBinderException
BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property
// RuntimeBinderException
BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -=
// RuntimeBinderException
BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type
// ArgumentException
BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument
// ArgumentException
BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument
// ArgumentException
BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument
// RuntimeBinderException
BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference
// RuntimeBinderException
NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference
// RuntimeBinderException
BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute
// RuntimeBinderException
BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object'
// EE?
EmptyDynamicView, // No further information on this object could be discovered
// MissingMemberException
GetValueonWriteOnlyProperty, // Write Only properties are not supported
}
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(23,23\).*CS0649</Expects>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
get
{
return 1;
}
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
try
{
var rez = f[d];
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param014.param014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier;
using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param014.param014;
// <Title>Call methods that have different parameter modifiers with dynamic</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public struct myStruct
{
public int Field;
}
public class Foo
{
public int this[params int[] x]
{
get
{
return 1;
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
dynamic d = "foo";
dynamic d2 = 3;
try
{
var rez = f[d2, d];
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
return 0;
}
return 1;
}
}
// </Code>
}
| |
// file: core/math/math_2d.h
// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451
// file: core/math/math_2d.cpp
// commit: 7ad14e7a3e6f87ddc450f7e34621eb5200808451
// file: core/variant_call.cpp
// commit: 5ad9be4c24e9d7dc5672fdc42cea896622fe5685
using System;
using System.Runtime.InteropServices;
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
namespace Godot
{
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
public real_t x;
public real_t y;
public real_t this[int index]
{
get
{
switch (index)
{
case 0:
return x;
case 1:
return y;
default:
throw new IndexOutOfRangeException();
}
}
set
{
switch (index)
{
case 0:
x = value;
return;
case 1:
y = value;
return;
default:
throw new IndexOutOfRangeException();
}
}
}
internal void Normalize()
{
real_t length = x * x + y * y;
if (length != 0f)
{
length = Mathf.Sqrt(length);
x /= length;
y /= length;
}
}
public real_t Cross(Vector2 b)
{
return x * b.y - y * b.x;
}
public Vector2 Abs()
{
return new Vector2(Mathf.Abs(x), Mathf.Abs(y));
}
public real_t Angle()
{
return Mathf.Atan2(y, x);
}
public real_t AngleTo(Vector2 to)
{
return Mathf.Atan2(Cross(to), Dot(to));
}
public real_t AngleToPoint(Vector2 to)
{
return Mathf.Atan2(y - to.y, x - to.x);
}
public real_t Aspect()
{
return x / y;
}
public Vector2 Bounce(Vector2 n)
{
return -Reflect(n);
}
public Vector2 Ceil()
{
return new Vector2(Mathf.Ceil(x), Mathf.Ceil(y));
}
public Vector2 Clamped(real_t length)
{
var v = this;
real_t l = Length();
if (l > 0 && length < l)
{
v /= l;
v *= length;
}
return v;
}
public Vector2 CubicInterpolate(Vector2 b, Vector2 preA, Vector2 postB, real_t t)
{
var p0 = preA;
var p1 = this;
var p2 = b;
var p3 = postB;
real_t t2 = t * t;
real_t t3 = t2 * t;
return 0.5f * (p1 * 2.0f +
(-p0 + p2) * t +
(2.0f * p0 - 5.0f * p1 + 4 * p2 - p3) * t2 +
(-p0 + 3.0f * p1 - 3.0f * p2 + p3) * t3);
}
public Vector2 DirectionTo(Vector2 b)
{
return new Vector2(b.x - x, b.y - y).Normalized();
}
public real_t DistanceSquaredTo(Vector2 to)
{
return (x - to.x) * (x - to.x) + (y - to.y) * (y - to.y);
}
public real_t DistanceTo(Vector2 to)
{
return Mathf.Sqrt((x - to.x) * (x - to.x) + (y - to.y) * (y - to.y));
}
public real_t Dot(Vector2 with)
{
return x * with.x + y * with.y;
}
public Vector2 Floor()
{
return new Vector2(Mathf.Floor(x), Mathf.Floor(y));
}
public bool IsNormalized()
{
return Mathf.Abs(LengthSquared() - 1.0f) < Mathf.Epsilon;
}
public real_t Length()
{
return Mathf.Sqrt(x * x + y * y);
}
public real_t LengthSquared()
{
return x * x + y * y;
}
public Vector2 LinearInterpolate(Vector2 b, real_t t)
{
var res = this;
res.x += t * (b.x - x);
res.y += t * (b.y - y);
return res;
}
public Vector2 Normalized()
{
var result = this;
result.Normalize();
return result;
}
public Vector2 Project(Vector2 onNormal)
{
return onNormal * (Dot(onNormal) / onNormal.LengthSquared());
}
public Vector2 Reflect(Vector2 n)
{
return 2.0f * n * Dot(n) - this;
}
public Vector2 Rotated(real_t phi)
{
real_t rads = Angle() + phi;
return new Vector2(Mathf.Cos(rads), Mathf.Sin(rads)) * Length();
}
public Vector2 Round()
{
return new Vector2(Mathf.Round(x), Mathf.Round(y));
}
public void Set(real_t x, real_t y)
{
this.x = x;
this.y = y;
}
public void Set(Vector2 v)
{
x = v.x;
y = v.y;
}
public Vector2 Slerp(Vector2 b, real_t t)
{
real_t theta = AngleTo(b);
return Rotated(theta * t);
}
public Vector2 Slide(Vector2 n)
{
return this - n * Dot(n);
}
public Vector2 Snapped(Vector2 by)
{
return new Vector2(Mathf.Stepify(x, by.x), Mathf.Stepify(y, by.y));
}
public Vector2 Tangent()
{
return new Vector2(y, -x);
}
// Constants
private static readonly Vector2 _zero = new Vector2(0, 0);
private static readonly Vector2 _one = new Vector2(1, 1);
private static readonly Vector2 _negOne = new Vector2(-1, -1);
private static readonly Vector2 _inf = new Vector2(Mathf.Inf, Mathf.Inf);
private static readonly Vector2 _up = new Vector2(0, -1);
private static readonly Vector2 _down = new Vector2(0, 1);
private static readonly Vector2 _right = new Vector2(1, 0);
private static readonly Vector2 _left = new Vector2(-1, 0);
public static Vector2 Zero { get { return _zero; } }
public static Vector2 NegOne { get { return _negOne; } }
public static Vector2 One { get { return _one; } }
public static Vector2 Inf { get { return _inf; } }
public static Vector2 Up { get { return _up; } }
public static Vector2 Down { get { return _down; } }
public static Vector2 Right { get { return _right; } }
public static Vector2 Left { get { return _left; } }
// Constructors
public Vector2(real_t x, real_t y)
{
this.x = x;
this.y = y;
}
public Vector2(Vector2 v)
{
x = v.x;
y = v.y;
}
public static Vector2 operator +(Vector2 left, Vector2 right)
{
left.x += right.x;
left.y += right.y;
return left;
}
public static Vector2 operator -(Vector2 left, Vector2 right)
{
left.x -= right.x;
left.y -= right.y;
return left;
}
public static Vector2 operator -(Vector2 vec)
{
vec.x = -vec.x;
vec.y = -vec.y;
return vec;
}
public static Vector2 operator *(Vector2 vec, real_t scale)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2 operator *(real_t scale, Vector2 vec)
{
vec.x *= scale;
vec.y *= scale;
return vec;
}
public static Vector2 operator *(Vector2 left, Vector2 right)
{
left.x *= right.x;
left.y *= right.y;
return left;
}
public static Vector2 operator /(Vector2 vec, real_t scale)
{
vec.x /= scale;
vec.y /= scale;
return vec;
}
public static Vector2 operator /(Vector2 left, Vector2 right)
{
left.x /= right.x;
left.y /= right.y;
return left;
}
public static bool operator ==(Vector2 left, Vector2 right)
{
return left.Equals(right);
}
public static bool operator !=(Vector2 left, Vector2 right)
{
return !left.Equals(right);
}
public static bool operator <(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y < right.y;
}
return left.x < right.x;
}
public static bool operator >(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y > right.y;
}
return left.x > right.x;
}
public static bool operator <=(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y <= right.y;
}
return left.x <= right.x;
}
public static bool operator >=(Vector2 left, Vector2 right)
{
if (left.x.Equals(right.x))
{
return left.y >= right.y;
}
return left.x >= right.x;
}
public override bool Equals(object obj)
{
if (obj is Vector2)
{
return Equals((Vector2)obj);
}
return false;
}
public bool Equals(Vector2 other)
{
return x == other.x && y == other.y;
}
public override int GetHashCode()
{
return y.GetHashCode() ^ x.GetHashCode();
}
public override string ToString()
{
return String.Format("({0}, {1})", new object[]
{
x.ToString(),
y.ToString()
});
}
public string ToString(string format)
{
return String.Format("({0}, {1})", new object[]
{
x.ToString(format),
y.ToString(format)
});
}
}
}
| |
using NSubstitute;
using NuKeeper.Abstractions;
using NuKeeper.Abstractions.CollaborationModels;
using NuKeeper.Abstractions.CollaborationPlatform;
using NuKeeper.Abstractions.Configuration;
using NuKeeper.Abstractions.Git;
using NuKeeper.Abstractions.Inspections.Files;
using NuKeeper.Abstractions.Logging;
using NuKeeper.Abstractions.NuGet;
using NuKeeper.Abstractions.RepositoryInspection;
using NuKeeper.Engine;
using NuKeeper.Engine.Packages;
using NuKeeper.Inspection;
using NuKeeper.Inspection.Report;
using NuKeeper.Inspection.Sources;
using NuKeeper.Update;
using NuKeeper.Update.Process;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NuKeeper.Tests.Engine
{
[TestFixture]
public class RepositoryUpdaterTests
{
[Test]
public async Task WhenThereAreNoUpdates_CountIsZero()
{
var updateSelection = Substitute.For<IPackageUpdateSelection>();
UpdateSelectionAll(updateSelection);
var (repoUpdater, packageUpdater) = MakeRepositoryUpdater(
updateSelection,
new List<PackageUpdateSet>());
var git = Substitute.For<IGitDriver>();
var repo = MakeRepositoryData();
var count = await repoUpdater.Run(git, repo, MakeSettings());
Assert.That(count, Is.EqualTo(0));
await AssertDidNotReceiveMakeUpdate(packageUpdater);
}
[Test]
public async Task WhenThereIsAnUpdate_CountIsOne()
{
var updateSelection = Substitute.For<IPackageUpdateSelection>();
UpdateSelectionAll(updateSelection);
var updates = PackageUpdates.UpdateSet()
.InList();
var (repoUpdater, packageUpdater) = MakeRepositoryUpdater(
updateSelection, updates);
var git = Substitute.For<IGitDriver>();
var repo = MakeRepositoryData();
var count = await repoUpdater.Run(git, repo, MakeSettings());
Assert.That(count, Is.EqualTo(1));
await AssertReceivedMakeUpdate(packageUpdater, 1);
}
#pragma warning disable CA1801
[TestCase(0, 0, true, true, 0, 0)]
[TestCase(1, 0, true, true, 1, 0)]
[TestCase(2, 0, true, true, 2, 0)]
[TestCase(3, 0, true, true, 3, 0)]
[TestCase(1, 1, true, true, 0, 0)]
[TestCase(2, 1, true, true, 1, 0)]
[TestCase(3, 1, true, true, 2, 0)]
[TestCase(1, 0, false, true, 1, 0)]
[TestCase(1, 1, false, true, 0, 0)]
[TestCase(1, 0, true, false, 1, 1)]
[TestCase(2, 0, true, false, 2, 1)]
[TestCase(3, 0, true, false, 3, 1)]
[TestCase(1, 1, true, false, 0, 0)]
[TestCase(2, 1, true, false, 1, 1)]
[TestCase(3, 1, true, false, 2, 1)]
[TestCase(1, 0, false, false, 1, 1)]
[TestCase(1, 1, false, false, 0, 0)]
public async Task WhenThereAreUpdates_CountIsAsExpected(int numberOfUpdates, int existingCommitsPerBranch, bool consolidateUpdates, bool pullRequestExists, int expectedUpdates, int expectedPrs)
{
var updateSelection = Substitute.For<IPackageUpdateSelection>();
var collaborationFactory = Substitute.For<ICollaborationFactory>();
var gitDriver = Substitute.For<IGitDriver>();
var existingCommitFilder = Substitute.For<IExistingCommitFilter>();
UpdateSelectionAll(updateSelection);
gitDriver.GetCurrentHead().Returns("def");
gitDriver.CheckoutNewBranch(Arg.Any<string>()).Returns(true);
collaborationFactory
.CollaborationPlatform
.PullRequestExists(Arg.Any<ForkData>(), Arg.Any<string>(), Arg.Any<string>())
.Returns(pullRequestExists);
var packageUpdater = new PackageUpdater(collaborationFactory,
existingCommitFilder,
Substitute.For<IUpdateRunner>(),
Substitute.For<INuKeeperLogger>());
var updates = Enumerable.Range(1, numberOfUpdates)
.Select(_ => PackageUpdates.UpdateSet())
.ToList();
var filteredUpdates = updates.Skip(existingCommitsPerBranch).ToList().AsReadOnly();
existingCommitFilder.Filter(Arg.Any<IGitDriver>(), Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(), Arg.Any<string>(), Arg.Any<string>()).Returns(filteredUpdates);
var settings = MakeSettings(consolidateUpdates);
var (repoUpdater, _) = MakeRepositoryUpdater(
updateSelection, updates, packageUpdater);
var repo = MakeRepositoryData();
var count = await repoUpdater.Run(gitDriver, repo, settings);
Assert.That(count, Is.EqualTo(expectedUpdates), "Returned count of updates");
await collaborationFactory.CollaborationPlatform.Received(expectedPrs)
.OpenPullRequest(
Arg.Any<ForkData>(),
Arg.Any<PullRequestRequest>(),
Arg.Any<IEnumerable<string>>());
await gitDriver.Received(expectedUpdates).Commit(Arg.Any<string>());
}
#pragma warning restore CA1801
[Test]
public async Task WhenUpdatesAreFilteredOut_CountIsZero()
{
var updateSelection = Substitute.For<IPackageUpdateSelection>();
UpdateSelectionNone(updateSelection);
var twoUpdates = new List<PackageUpdateSet>
{
PackageUpdates.UpdateSet(),
PackageUpdates.UpdateSet()
};
var (repoUpdater, packageUpdater) = MakeRepositoryUpdater(
updateSelection,
twoUpdates);
var git = Substitute.For<IGitDriver>();
var repo = MakeRepositoryData();
var count = await repoUpdater.Run(git, repo, MakeSettings());
Assert.That(count, Is.EqualTo(0));
await AssertDidNotReceiveMakeUpdate(packageUpdater);
}
private static async Task AssertReceivedMakeUpdate(
IPackageUpdater packageUpdater,
int count)
{
await packageUpdater.Received(count)
.MakeUpdatePullRequests(
Arg.Any<IGitDriver>(),
Arg.Any<RepositoryData>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<NuGetSources>(),
Arg.Any<SettingsContainer>());
}
private static async Task AssertDidNotReceiveMakeUpdate(
IPackageUpdater packageUpdater)
{
await packageUpdater.DidNotReceiveWithAnyArgs()
.MakeUpdatePullRequests(
Arg.Any<IGitDriver>(),
Arg.Any<RepositoryData>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<NuGetSources>(),
Arg.Any<SettingsContainer>());
}
private static void UpdateSelectionAll(IPackageUpdateSelection updateSelection)
{
updateSelection.SelectTargets(
Arg.Any<ForkData>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<FilterSettings>())
.Returns(c => c.ArgAt<IReadOnlyCollection<PackageUpdateSet>>(1));
}
private static void UpdateSelectionNone(IPackageUpdateSelection updateSelection)
{
updateSelection.SelectTargets(
Arg.Any<ForkData>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<FilterSettings>())
.Returns(new List<PackageUpdateSet>());
}
private static SettingsContainer MakeSettings(bool consolidateUpdates = false)
{
return new SettingsContainer
{
SourceControlServerSettings = new SourceControlServerSettings(),
UserSettings = new UserSettings
{
ConsolidateUpdatesInSinglePullRequest = consolidateUpdates
},
BranchSettings = new BranchSettings()
};
}
private static
(IRepositoryUpdater repositoryUpdater, IPackageUpdater packageUpdater) MakeRepositoryUpdater(
IPackageUpdateSelection updateSelection,
List<PackageUpdateSet> updates,
IPackageUpdater packageUpdater = null)
{
var sources = Substitute.For<INuGetSourcesReader>();
var updateFinder = Substitute.For<IUpdateFinder>();
var fileRestore = Substitute.For<IFileRestoreCommand>();
var reporter = Substitute.For<IReporter>();
updateFinder.FindPackageUpdateSets(
Arg.Any<IFolder>(),
Arg.Any<NuGetSources>(),
Arg.Any<VersionChange>(),
Arg.Any<UsePrerelease>())
.Returns(updates);
if (packageUpdater == null)
{
packageUpdater = Substitute.For<IPackageUpdater>();
packageUpdater.MakeUpdatePullRequests(
Arg.Any<IGitDriver>(),
Arg.Any<RepositoryData>(),
Arg.Any<IReadOnlyCollection<PackageUpdateSet>>(),
Arg.Any<NuGetSources>(),
Arg.Any<SettingsContainer>())
.Returns(1);
}
var repoUpdater = new RepositoryUpdater(
sources, updateFinder, updateSelection, packageUpdater,
Substitute.For<INuKeeperLogger>(), new SolutionsRestore(fileRestore),
reporter);
return (repoUpdater, packageUpdater);
}
private static RepositoryData MakeRepositoryData()
{
return new RepositoryData(
new ForkData(new Uri("http://foo.com"), "me", "test"),
new ForkData(new Uri("http://foo.com"), "me", "test"));
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Web;
using System.Web.UI.HtmlControls;
namespace Contoso.Web.UI
{
/// <summary>
/// HttpPageMapperExtentions
/// </summary>
public static class HttpPageMapperExtentions
{
/// <summary>
/// HeaderControlId
/// </summary>
public class HeaderControlID
{
/// <summary>
///
/// </summary>
public const string NoIndex = "HtmlHeadNoIndex";
/// <summary>
///
/// </summary>
public const string Canonical = "HtmlHeadCanonical";
/// <summary>
///
/// </summary>
public const string Icon = "HtmlHeadIcon";
/// <summary>
///
/// </summary>
public const string ShortcutIcon = "HtmlHeadShortcutIcon";
/// <summary>
///
/// </summary>
public const string Search = "HtmlHeadSearch";
/// <summary>
///
/// </summary>
public const string Syndication = "HtmlHeadRss";
/// <summary>
///
/// </summary>
public const string Title = "HtmlHeadTitle";
/// <summary>
///
/// </summary>
public const string Keyword = "HtmlHeadKeyword";
/// <summary>
///
/// </summary>
public const string Description = "HtmlHeadDescription";
/// <summary>
///
/// </summary>
public const string Tag = "HtmlHeadTag";
/// <summary>
///
/// </summary>
public const string Author = "HtmlHeadAuthor";
/// <summary>
///
/// </summary>
public const string Copyright = "HtmlHeadCopyright";
/// <summary>
///
/// </summary>
public const string Developer = "HtmlHeadDeveloper";
}
/// <summary>
/// Maps to HTTP response.
/// </summary>
/// <param name="page">The page.</param>
/// <param name="response">The response.</param>
public static void MapToHttpResponse(this HttpPage page, HttpResponse response)
{
if (page == null)
throw new ArgumentNullException("page");
if (response == null)
throw new ArgumentNullException("response");
switch (page.CachingApproach)
{
case HttpPage.HttpPageCachingApproach.Default:
break;
case HttpPage.HttpPageCachingApproach.LastModifyDateWithoutCaching:
var lastModifyDate = page.LastModifyDate;
if (lastModifyDate != null)
{
//NOTE: adding headers instead of Response.Cache because issues with NoCache and Last-Modified header
response.AddHeader("Cache-Control", "no-cache");
response.AddHeader("Pragma", "no-cache");
response.AddHeader("Expires", "-1");
response.AddHeader("Last-Modified", lastModifyDate.Value.ToUniversalTime().ToString("R"));
}
else
response.Cache.SetCacheability(HttpCacheability.NoCache);
break;
case HttpPage.HttpPageCachingApproach.NoCache:
response.Cache.SetCacheability(HttpCacheability.NoCache);
break;
default:
throw new InvalidOperationException();
}
}
/// <summary>
/// Maps to HTML head.
/// </summary>
/// <param name="page">The page.</param>
/// <param name="htmlHead">The HTML head.</param>
public static void MapToHtmlHead(this HttpPage page, HtmlHead htmlHead)
{
if (page == null)
throw new ArgumentNullException("page");
if (htmlHead == null)
throw new ArgumentNullException("htmlHead");
var pageHead = page.Head;
if (pageHead == null)
throw new NullReferenceException("page.Head");
var htmlHeadControls = htmlHead.Controls;
HtmlLink htmlLink;
string text;
// no-index
if (pageHead.NoIndex)
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.NoIndex, Name = "robots", Content = "noindex" });
// canonical
if (!string.IsNullOrEmpty(text = pageHead.CanonicalUri))
{
htmlLink = new HtmlLink { ID = HeaderControlID.Canonical, Href = text };
htmlLink.Attributes["rel"] = "canonical";
htmlHeadControls.Add(htmlLink);
}
// icon
if (!string.IsNullOrEmpty(text = pageHead.IconUri))
{
if (string.Compare(text, "/favicon.ico", StringComparison.OrdinalIgnoreCase) != 0)
throw new InvalidOperationException(string.Format("InvalidHttpHeadIconA {0}", "/favicon.ico"));
// icon (browser type A)
htmlLink = new HtmlLink { ID = HeaderControlID.Icon, Href = text };
htmlLink.Attributes["rel"] = "icon";
htmlLink.Attributes["type"] = "image/x-icon";
htmlHeadControls.Add(htmlLink);
// shortcut icon (browser type B)
htmlLink = new HtmlLink { ID = HeaderControlID.ShortcutIcon, Href = text };
htmlLink.Attributes["rel"] = "shortcut icon";
htmlLink.Attributes["type"] = "image/x-icon";
htmlHeadControls.Add(htmlLink);
}
// search
if (!string.IsNullOrEmpty(text = pageHead.Search))
{
htmlLink = new HtmlLink { ID = HeaderControlID.Search, Href = text };
var title = pageHead.SearchTitle;
if (!string.IsNullOrEmpty(title))
htmlLink.Attributes["title"] = title;
htmlLink.Attributes["rel"] = "search";
htmlLink.Attributes["type"] = "application/opensearchdescription+xml";
htmlHeadControls.Add(htmlLink);
}
// rss/atom
var syndications = pageHead.Syndications;
if (syndications != null)
{
var id = string.Empty;
for (int syndicationIndex = 1; syndicationIndex < syndications.Length; syndicationIndex++)
{
var syndication = syndications[syndicationIndex];
htmlLink = new HtmlLink { ID = HeaderControlID.Syndication + id, Href = syndication.Uri };
var title = syndication.Title;
if (!string.IsNullOrEmpty(title))
htmlLink.Attributes["title"] = title;
htmlLink.Attributes["rel"] = "alternate";
htmlLink.Attributes["type"] = (syndication.Format == HttpPage.WebSyndicationFormat.Atom ? "application/atom+xml" : "application/rss+xml");
htmlHeadControls.Add(htmlLink);
id = (syndicationIndex++).ToString();
}
}
// page title
if (!string.IsNullOrEmpty(text = pageHead.Title))
htmlHeadControls.Add(new HtmlTitle { ID = HeaderControlID.Title, Text = HttpUtility.HtmlEncode(text) });
// page keyword
if (!string.IsNullOrEmpty(text = pageHead.Keywords))
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.Keyword, Name = "keywords", Content = text });
// page description
if (!string.IsNullOrEmpty(text = pageHead.Description))
htmlHeadControls.Add(new HtmlMeta() { ID = HeaderControlID.Description, Name = "description", Content = text });
// add search tag
if (!string.IsNullOrEmpty(text = pageHead.Tag))
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.Tag, Name = "tag", Content = text });
// author
if (!string.IsNullOrEmpty(text = pageHead.Author))
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.Author, Name = "author", Content = text });
// copyright
if (!string.IsNullOrEmpty(text = pageHead.Copyright))
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.Copyright, Name = "copyright", Content = text });
// developer
if (!string.IsNullOrEmpty(text = pageHead.Developer))
htmlHeadControls.Add(new HtmlMeta { ID = HeaderControlID.Developer, Name = "developer", Content = text });
}
/// <summary>
/// Maps to HTTP page.
/// </summary>
/// <param name="pageMetatag">The page metatag.</param>
/// <param name="page">The page.</param>
public static void MapToHttpPage(this IHttpPageMetatag pageMetatag, HttpPage page) { MapToHttpPage(pageMetatag, page, false); }
/// <summary>
/// Maps to HTTP page.
/// </summary>
/// <param name="pageMetatag">The page metatag.</param>
/// <param name="page">The page.</param>
/// <param name="forceMapping">if set to <c>true</c> [force mapping].</param>
public static void MapToHttpPage(this IHttpPageMetatag pageMetatag, HttpPage page, bool forceMapping)
{
if (pageMetatag == null)
throw new ArgumentNullException("metatag");
if (page == null)
throw new ArgumentNullException("page");
var pageHead = page.Head;
if (pageHead == null)
throw new NullReferenceException("page.Head");
//
string text;
if (!string.IsNullOrEmpty(text = pageMetatag.Description) || forceMapping)
pageHead.Description = text;
if (!string.IsNullOrEmpty(text = pageMetatag.Keywords) || forceMapping)
pageHead.Keywords = text;
if (!string.IsNullOrEmpty(text = pageMetatag.Title) || forceMapping)
pageHead.Title = text;
if (!string.IsNullOrEmpty(text = pageMetatag.Tag) || forceMapping)
pageHead.Tag = text;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException("direction", SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException("direction", SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException("transmissionMode", SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException("outBufferSize", SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
[SecuritySafeCritical]
internal void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
[SecurityCritical]
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
[SecurityCritical]
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(buffer, offset, count);
}
[SecuritySafeCritical]
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException("buffer", SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertReadWriteArgs(byte[] buffer, int offset, int count, SafePipeHandle handle)
{
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(offset <= buffer.Length - count, "offset + count is too big");
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
[ThreadStatic]
private static byte[] t_singleByteArray;
private static byte[] SingleByteArray
{
get { return t_singleByteArray ?? (t_singleByteArray = new byte[1]); }
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
[SecurityCritical]
public override int ReadByte()
{
byte[] buffer = SingleByteArray;
return Read(buffer, 0, 1) > 0 ?
buffer[0] :
-1;
}
[SecurityCritical]
public override void WriteByte(byte value)
{
byte[] buffer = SingleByteArray;
buffer[0] = value;
Write(buffer, 0, 1);
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
[SecurityCritical]
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
UninitializeAsyncHandle();
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
[SecurityCritical]
get
{
return _handle;
}
}
internal bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
[Pure]
get
{
return _canRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _canWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
[SecurityCritical]
internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Consistent with security model")]
internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFCoreEx
{
public class NFCObject : NFIObject
{
public NFCObject(NFIDENTID self, int nContainerID, int nGroupID, string strClassName, string strConfigIndex)
{
mSelf = self;
mstrClassName = strClassName;
mstrConfigIndex = strConfigIndex;
mnContainerID = nContainerID;
mnGroupID = nGroupID;
Init();
}
~NFCObject()
{
Shut();
}
public override bool Init()
{
mRecordManager = new NFCRecordManager(mSelf);
mPropertyManager = new NFCPropertyManager(mSelf);
mHeartManager = new NFCHeartBeatManager(mSelf);
mEventManager = new NFCEventManager(mSelf);
return true;
}
public override bool Shut()
{
mRecordManager = null;
mPropertyManager = null;
mHeartManager = null;
return true;
}
public override bool UpData(float fLastTime, float fAllTime)
{
//mHeartManager
return true;
}
///////////////////////////////////////////////////////////////////////
public override NFIDENTID Self()
{
return mSelf;
}
public override int ContainerID()
{
return mnContainerID;
}
public override int GroupID()
{
return mnGroupID;
}
public override string ClassName()
{
return mstrClassName;
}
public override string ConfigIndex()
{
return mstrConfigIndex;
}
// public override bool AddHeartBeat( string strHeartBeatName, HEART_BEAT_FUNC cb, NFIDataList& var, float fTime, int nCount );
public override bool FindHeartBeat(string strHeartBeatName)
{
return true;
}
public override bool RemoveHeartBeat(string strHeartBeatName)
{
return true;
}
//////////////////////////////////////////////////
//
// public override bool AddRecordCallBack( string strRecordName, RECORD_EVENT_FUNC cb );
//
// public override bool AddPropertyCallBack( string strCriticalName, PROPERTY_EVENT_FUNC cb );
/////////////////////////////////////////////////////////////////
public override bool FindProperty(string strPropertyName)
{
if (null != mPropertyManager.GetProperty(strPropertyName))
{
return true;
}
return false;
}
public override bool SetPropertyInt(string strPropertyName, Int64 nValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddInt(0);
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetInt(nValue);
return true;
}
public override bool SetPropertyFloat(string strPropertyName, float fValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddFloat(0.0f);
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetFloat(fValue);
return true;
}
public override bool SetPropertyDouble(string strPropertyName, double dwValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddDouble(0);
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetDouble(dwValue);
return true;
}
public override bool SetPropertyString(string strPropertyName, string strValue)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddString("");
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetString(strValue);
return true;
}
public override bool SetPropertyObject(string strPropertyName, NFIDENTID obj)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null == property)
{
NFIDataList valueList = new NFCDataList();
valueList.AddObject(new NFIDENTID());
property = mPropertyManager.AddProperty(strPropertyName, valueList);
}
property.SetObject(obj);
return true;
}
public override Int64 QueryPropertyInt(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryInt();
}
return 0;
}
public override float QueryPropertyFloat(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryFloat();
}
return 0.0f;
}
public override double QueryPropertyDouble(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryDouble();
}
return 0.0;
}
public override string QueryPropertyString(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryString();
}
return "";
}
public override NFIDENTID QueryPropertyObject(string strPropertyName)
{
NFIProperty property = mPropertyManager.GetProperty(strPropertyName);
if (null != property)
{
return property.QueryObject();
}
return new NFIDENTID();
}
public override bool FindRecord(string strRecordName)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return true;
}
return false;
}
public override bool SetRecordInt(string strRecordName, int nRow, int nCol, Int64 nValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetInt(nRow, nCol, nValue);
return true;
}
return false;
}
public override bool SetRecordFloat(string strRecordName, int nRow, int nCol, float fValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetFloat(nRow, nCol, fValue);
return true;
}
return false;
}
public override bool SetRecordDouble(string strRecordName, int nRow, int nCol, double dwValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetDouble(nRow, nCol, dwValue);
return true;
}
return false;
}
public override bool SetRecordString(string strRecordName, int nRow, int nCol, string strValue)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetString(nRow, nCol, strValue);
return true;
}
return false;
}
public override bool SetRecordObject(string strRecordName, int nRow, int nCol, NFIDENTID obj)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
record.SetObject(nRow, nCol, obj);
return true;
}
return false;
}
public override Int64 QueryRecordInt(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryInt(nRow, nCol);
}
return 0;
}
public override float QueryRecordFloat(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryFloat(nRow, nCol);
}
return 0.0f;
}
public override double QueryRecordDouble(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryDouble(nRow, nCol);
}
return 0.0;
}
public override string QueryRecordString(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryString(nRow, nCol);
}
return "";
}
public override NFIDENTID QueryRecordObject(string strRecordName, int nRow, int nCol)
{
NFIRecord record = mRecordManager.GetRecord(strRecordName);
if (null != record)
{
return record.QueryObject(nRow, nCol);
}
return null;
}
public override NFIRecordManager GetRecordManager()
{
return mRecordManager;
}
public override NFIHeartBeatManager GetHeartBeatManager()
{
return mHeartManager;
}
public override NFIPropertyManager GetPropertyManager()
{
return mPropertyManager;
}
public override NFIEventManager GetEventManager()
{
return mEventManager;
}
NFIDENTID mSelf;
int mnContainerID;
int mnGroupID;
string mstrClassName;
string mstrConfigIndex;
NFIRecordManager mRecordManager;
NFIPropertyManager mPropertyManager;
NFIHeartBeatManager mHeartManager;
NFIEventManager mEventManager;
}
}
| |
using System;
namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip.Compression
{
/// <summary>
/// This is the Deflater class. The deflater class compresses input
/// with the deflate algorithm described in RFC 1951. It has several
/// compression levels and three different strategies described below.
///
/// This class is <i>not</i> thread safe. This is inherent in the API, due
/// to the split of deflate and setInput.
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class Deflater
{
#region Deflater Documentation
/*
* The Deflater can do the following state transitions:
*
* (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---.
* / | (2) (5) |
* / v (5) |
* (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3)
* \ | (3) | ,--------'
* | | | (3) /
* v v (5) v v
* (1) -> BUSY_STATE ----> FINISHING_STATE
* | (6)
* v
* FINISHED_STATE
* \_____________________________________/
* | (7)
* v
* CLOSED_STATE
*
* (1) If we should produce a header we start in INIT_STATE, otherwise
* we start in BUSY_STATE.
* (2) A dictionary may be set only when we are in INIT_STATE, then
* we change the state as indicated.
* (3) Whether a dictionary is set or not, on the first call of deflate
* we change to BUSY_STATE.
* (4) -- intentionally left blank -- :)
* (5) FINISHING_STATE is entered, when flush() is called to indicate that
* there is no more INPUT. There are also states indicating, that
* the header wasn't written yet.
* (6) FINISHED_STATE is entered, when everything has been flushed to the
* internal pending output buffer.
* (7) At any time (7)
*
*/
#endregion
#region Public Constants
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
public const int BEST_COMPRESSION = 9;
/// <summary>
/// The worst but fastest compression level.
/// </summary>
public const int BEST_SPEED = 1;
/// <summary>
/// The default compression level.
/// </summary>
public const int DEFAULT_COMPRESSION = -1;
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
public const int NO_COMPRESSION = 0;
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
public const int DEFLATED = 8;
#endregion
#region Public Enum
/// <summary>
/// Compression Level as an enum for safer use
/// </summary>
public enum CompressionLevel
{
/// <summary>
/// The best and slowest compression level. This tries to find very
/// long and distant string repetitions.
/// </summary>
BEST_COMPRESSION = Deflater.BEST_COMPRESSION,
/// <summary>
/// The worst but fastest compression level.
/// </summary>
BEST_SPEED = Deflater.BEST_SPEED,
/// <summary>
/// The default compression level.
/// </summary>
DEFAULT_COMPRESSION = Deflater.DEFAULT_COMPRESSION,
/// <summary>
/// This level won't compress at all but output uncompressed blocks.
/// </summary>
NO_COMPRESSION = Deflater.NO_COMPRESSION,
/// <summary>
/// The compression method. This is the only method supported so far.
/// There is no need to use this constant at all.
/// </summary>
DEFLATED = Deflater.DEFLATED
}
#endregion
#region Local Constants
private const int IS_SETDICT = 0x01;
private const int IS_FLUSHING = 0x04;
private const int IS_FINISHING = 0x08;
private const int INIT_STATE = 0x00;
private const int SETDICT_STATE = 0x01;
// private static int INIT_FINISHING_STATE = 0x08;
// private static int SETDICT_FINISHING_STATE = 0x09;
private const int BUSY_STATE = 0x10;
private const int FLUSHING_STATE = 0x14;
private const int FINISHING_STATE = 0x1c;
private const int FINISHED_STATE = 0x1e;
private const int CLOSED_STATE = 0x7f;
#endregion
#region Constructors
/// <summary>
/// Creates a new deflater with default compression level.
/// </summary>
public Deflater() : this(DEFAULT_COMPRESSION, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION, or DEFAULT_COMPRESSION.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level) : this(level, false)
{
}
/// <summary>
/// Creates a new deflater with given compression level.
/// </summary>
/// <param name="level">
/// the compression level, a value between NO_COMPRESSION
/// and BEST_COMPRESSION.
/// </param>
/// <param name="noZlibHeaderOrFooter">
/// true, if we should suppress the Zlib/RFC1950 header at the
/// beginning and the adler checksum at the end of the output. This is
/// useful for the GZIP/PKZIP formats.
/// </param>
/// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception>
public Deflater(int level, bool noZlibHeaderOrFooter)
{
if (level == DEFAULT_COMPRESSION) {
level = 6;
} else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("level");
}
pending = new DeflaterPending();
engine = new DeflaterEngine(pending);
this.noZlibHeaderOrFooter = noZlibHeaderOrFooter;
SetStrategy(DeflateStrategy.Default);
SetLevel(level);
Reset();
}
#endregion
/// <summary>
/// Resets the deflater. The deflater acts afterwards as if it was
/// just created with the same compression level and strategy as it
/// had before.
/// </summary>
public void Reset()
{
state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE);
totalOut = 0;
pending.Reset();
engine.Reset();
}
/// <summary>
/// Gets the current adler checksum of the data that was processed so far.
/// </summary>
public int Adler {
get {
return engine.Adler;
}
}
/// <summary>
/// Gets the number of input bytes processed so far.
/// </summary>
public long TotalIn {
get {
return engine.TotalIn;
}
}
/// <summary>
/// Gets the number of output bytes so far.
/// </summary>
public long TotalOut {
get {
return totalOut;
}
}
/// <summary>
/// Flushes the current input block. Further calls to deflate() will
/// produce enough output to inflate everything in the current input
/// block. This is not part of Sun's JDK so I have made it package
/// private. It is used by DeflaterOutputStream to implement
/// flush().
/// </summary>
public void Flush()
{
state |= IS_FLUSHING;
}
/// <summary>
/// Finishes the deflater with the current input block. It is an error
/// to give more input after this method was called. This method must
/// be called to force all bytes to be flushed.
/// </summary>
public void Finish()
{
state |= (IS_FLUSHING | IS_FINISHING);
}
/// <summary>
/// Returns true if the stream was finished and no more output bytes
/// are available.
/// </summary>
public bool IsFinished {
get {
return (state == FINISHED_STATE) && pending.IsFlushed;
}
}
/// <summary>
/// Returns true, if the input buffer is empty.
/// You should then call setInput().
/// NOTE: This method can also return true when the stream
/// was finished.
/// </summary>
public bool IsNeedingInput {
get {
return engine.NeedsInput();
}
}
/// <summary>
/// Sets the data which should be compressed next. This should be only
/// called when needsInput indicates that more input is needed.
/// If you call setInput when needsInput() returns false, the
/// previous input that is still pending will be thrown away.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// This call is equivalent to <code>setInput(input, 0, input.length)</code>.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was finished() or ended().
/// </exception>
public void SetInput(byte[] input)
{
SetInput(input, 0, input.Length);
}
/// <summary>
/// Sets the data which should be compressed next. This should be
/// only called when needsInput indicates that more input is needed.
/// The given byte array should not be changed, before needsInput() returns
/// true again.
/// </summary>
/// <param name="input">
/// the buffer containing the input data.
/// </param>
/// <param name="offset">
/// the start of the data.
/// </param>
/// <param name="count">
/// the number of data bytes of input.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if the buffer was Finish()ed or if previous input is still pending.
/// </exception>
public void SetInput(byte[] input, int offset, int count)
{
if ((state & IS_FINISHING) != 0) {
throw new InvalidOperationException("Finish() already called");
}
engine.SetInput(input, offset, count);
}
/// <summary>
/// Sets the compression level. There is no guarantee of the exact
/// position of the change, but if you call this when needsInput is
/// true the change of compression level will occur somewhere near
/// before the end of the so far given input.
/// </summary>
/// <param name="level">
/// the new compression level.
/// </param>
public void SetLevel(int level)
{
if (level == DEFAULT_COMPRESSION) {
level = 6;
} else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) {
throw new ArgumentOutOfRangeException("level");
}
if (this.level != level) {
this.level = level;
engine.SetLevel(level);
}
}
/// <summary>
/// Get current compression level
/// </summary>
/// <returns>Returns the current compression level</returns>
public int GetLevel()
{
return level;
}
/// <summary>
/// Sets the compression strategy. Strategy is one of
/// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact
/// position where the strategy is changed, the same as for
/// SetLevel() applies.
/// </summary>
/// <param name="strategy">
/// The new compression strategy.
/// </param>
public void SetStrategy(DeflateStrategy strategy)
{
engine.Strategy = strategy;
}
/// <summary>
/// Deflates the current input block with to the given array.
/// </summary>
/// <param name="output">
/// The buffer where compressed data is stored
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// IsNeedingInput() or IsFinished returns true or length is zero.
/// </returns>
public int Deflate(byte[] output)
{
return Deflate(output, 0, output.Length);
}
/// <summary>
/// Deflates the current input block to the given array.
/// </summary>
/// <param name="output">
/// Buffer to store the compressed data.
/// </param>
/// <param name="offset">
/// Offset into the output array.
/// </param>
/// <param name="length">
/// The maximum number of bytes that may be stored.
/// </param>
/// <returns>
/// The number of compressed bytes added to the output, or 0 if either
/// needsInput() or finished() returns true or length is zero.
/// </returns>
/// <exception cref="System.InvalidOperationException">
/// If Finish() was previously called.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// If offset or length don't match the array length.
/// </exception>
public int Deflate(byte[] output, int offset, int length)
{
int origLength = length;
if (state == CLOSED_STATE) {
throw new InvalidOperationException("Deflater closed");
}
if (state < BUSY_STATE) {
// output header
int header = (DEFLATED +
((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8;
int level_flags = (level - 1) >> 1;
if (level_flags < 0 || level_flags > 3) {
level_flags = 3;
}
header |= level_flags << 6;
if ((state & IS_SETDICT) != 0) {
// Dictionary was set
header |= DeflaterConstants.PRESET_DICT;
}
header += 31 - (header % 31);
pending.WriteShortMSB(header);
if ((state & IS_SETDICT) != 0) {
int chksum = engine.Adler;
engine.ResetAdler();
pending.WriteShortMSB(chksum >> 16);
pending.WriteShortMSB(chksum & 0xffff);
}
state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING));
}
for (;;) {
int count = pending.Flush(output, offset, length);
offset += count;
totalOut += count;
length -= count;
if (length == 0 || state == FINISHED_STATE) {
break;
}
if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) {
switch (state) {
case BUSY_STATE:
// We need more input now
return origLength - length;
case FLUSHING_STATE:
if (level != NO_COMPRESSION) {
/* We have to supply some lookahead. 8 bit lookahead
* is needed by the zlib inflater, and we must fill
* the next byte, so that all bits are flushed.
*/
int neededbits = 8 + ((-pending.BitCount) & 7);
while (neededbits > 0) {
/* write a static tree block consisting solely of
* an EOF:
*/
pending.WriteBits(2, 10);
neededbits -= 10;
}
}
state = BUSY_STATE;
break;
case FINISHING_STATE:
pending.AlignToByte();
// Compressed data is complete. Write footer information if required.
if (!noZlibHeaderOrFooter) {
int adler = engine.Adler;
pending.WriteShortMSB(adler >> 16);
pending.WriteShortMSB(adler & 0xffff);
}
state = FINISHED_STATE;
break;
}
}
}
return origLength - length;
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>.
/// </summary>
/// <param name="dictionary">
/// the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// if SetInput () or Deflate () were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dictionary)
{
SetDictionary(dictionary, 0, dictionary.Length);
}
/// <summary>
/// Sets the dictionary which should be used in the deflate process.
/// The dictionary is a byte array containing strings that are
/// likely to occur in the data which should be compressed. The
/// dictionary is not stored in the compressed output, only a
/// checksum. To decompress the output you need to supply the same
/// dictionary again.
/// </summary>
/// <param name="dictionary">
/// The dictionary data
/// </param>
/// <param name="index">
/// The index where dictionary information commences.
/// </param>
/// <param name="count">
/// The number of bytes in the dictionary.
/// </param>
/// <exception cref="System.InvalidOperationException">
/// If SetInput () or Deflate() were already called or another dictionary was already set.
/// </exception>
public void SetDictionary(byte[] dictionary, int index, int count)
{
if (state != INIT_STATE) {
throw new InvalidOperationException();
}
state = SETDICT_STATE;
engine.SetDictionary(dictionary, index, count);
}
#region Instance Fields
/// <summary>
/// Compression level.
/// </summary>
int level;
/// <summary>
/// If true no Zlib/RFC1950 headers or footers are generated
/// </summary>
bool noZlibHeaderOrFooter;
/// <summary>
/// The current state.
/// </summary>
int state;
/// <summary>
/// The total bytes of output written.
/// </summary>
long totalOut;
/// <summary>
/// The pending output.
/// </summary>
DeflaterPending pending;
/// <summary>
/// The deflater engine.
/// </summary>
DeflaterEngine engine;
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// Uncomment to make asset Get requests for existing
// #define WAIT_ON_INPROGRESS_REQUESTS
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Timers;
using log4net;
using Nini.Config;
using Mono.Addins;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Monitoring;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
//[assembly: Addin("FlotsamAssetCache", "1.1")]
//[assembly: AddinDependency("OpenSim", "0.8.1")]
namespace OpenSim.Region.CoreModules.Asset
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "FlotsamAssetCache")]
public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled;
private const string m_ModuleName = "FlotsamAssetCache";
private const string m_DefaultCacheDirectory = "./assetcache";
private string m_CacheDirectory = m_DefaultCacheDirectory;
private readonly List<char> m_InvalidChars = new List<char>();
private int m_LogLevel = 0;
private ulong m_HitRateDisplay = 100; // How often to display hit statistics, given in requests
private static ulong m_Requests;
private static ulong m_RequestsForInprogress;
private static ulong m_DiskHits;
private static ulong m_MemoryHits;
#if WAIT_ON_INPROGRESS_REQUESTS
private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>();
private int m_WaitOnInprogressTimeout = 3000;
#else
private HashSet<string> m_CurrentlyWriting = new HashSet<string>();
#endif
private bool m_FileCacheEnabled = true;
private ExpiringCache<string, AssetBase> m_MemoryCache;
private bool m_MemoryCacheEnabled = false;
// Expiration is expressed in hours.
private const double m_DefaultMemoryExpiration = 2;
private const double m_DefaultFileExpiration = 48;
private TimeSpan m_MemoryExpiration = TimeSpan.FromHours(m_DefaultMemoryExpiration);
private TimeSpan m_FileExpiration = TimeSpan.FromHours(m_DefaultFileExpiration);
private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.FromHours(0.166);
private static int m_CacheDirectoryTiers = 1;
private static int m_CacheDirectoryTierLen = 3;
private static int m_CacheWarnAt = 30000;
private System.Timers.Timer m_CacheCleanTimer;
private IAssetService m_AssetService;
private List<Scene> m_Scenes = new List<Scene>();
public FlotsamAssetCache()
{
m_InvalidChars.AddRange(Path.GetInvalidPathChars());
m_InvalidChars.AddRange(Path.GetInvalidFileNameChars());
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return m_ModuleName; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("AssetCaching", String.Empty);
if (name == Name)
{
m_MemoryCache = new ExpiringCache<string, AssetBase>();
m_Enabled = true;
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name);
IConfig assetConfig = source.Configs["AssetCache"];
if (assetConfig == null)
{
m_log.Debug(
"[FLOTSAM ASSET CACHE]: AssetCache section missing from config (not copied config-include/FlotsamCache.ini.example? Using defaults.");
}
else
{
m_FileCacheEnabled = assetConfig.GetBoolean("FileCacheEnabled", m_FileCacheEnabled);
m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory);
m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", m_MemoryCacheEnabled);
m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration));
#if WAIT_ON_INPROGRESS_REQUESTS
m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000);
#endif
m_LogLevel = assetConfig.GetInt("LogLevel", m_LogLevel);
m_HitRateDisplay = (ulong)assetConfig.GetLong("HitRateDisplay", (long)m_HitRateDisplay);
m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration));
m_FileExpirationCleanupTimer
= TimeSpan.FromHours(
assetConfig.GetDouble("FileCleanupTimer", m_FileExpirationCleanupTimer.TotalHours));
m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", m_CacheDirectoryTiers);
m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", m_CacheDirectoryTierLen);
m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", m_CacheWarnAt);
}
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory {0}", m_CacheDirectory);
if (m_FileCacheEnabled && (m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero))
{
m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds);
m_CacheCleanTimer.AutoReset = true;
m_CacheCleanTimer.Elapsed += CleanupExpiredFiles;
lock (m_CacheCleanTimer)
m_CacheCleanTimer.Start();
}
if (m_CacheDirectoryTiers < 1)
{
m_CacheDirectoryTiers = 1;
}
else if (m_CacheDirectoryTiers > 3)
{
m_CacheDirectoryTiers = 3;
}
if (m_CacheDirectoryTierLen < 1)
{
m_CacheDirectoryTierLen = 1;
}
else if (m_CacheDirectoryTierLen > 4)
{
m_CacheDirectoryTierLen = 4;
}
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the cache. If file or memory is specified then only this cache is cleared.", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand);
MainConsole.Instance.Commands.AddCommand("Assets", true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand);
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (m_Enabled)
{
scene.RegisterModuleInterface<IImprovedAssetCache>(this);
m_Scenes.Add(scene);
}
}
public void RemoveRegion(Scene scene)
{
if (m_Enabled)
{
scene.UnregisterModuleInterface<IImprovedAssetCache>(this);
m_Scenes.Remove(scene);
}
}
public void RegionLoaded(Scene scene)
{
if (m_Enabled && m_AssetService == null)
m_AssetService = scene.RequestModuleInterface<IAssetService>();
}
////////////////////////////////////////////////////////////
// IImprovedAssetCache
//
private void UpdateMemoryCache(string key, AssetBase asset)
{
m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration);
}
private void UpdateFileCache(string key, AssetBase asset)
{
string filename = GetFileName(key);
try
{
// If the file is already cached, don't cache it, just touch it so access time is updated
if (File.Exists(filename))
{
UpdateFileLastAccessTime(filename);
}
else
{
// Once we start writing, make sure we flag that we're writing
// that object to the cache so that we don't try to write the
// same file multiple times.
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
if (m_CurrentlyWriting.ContainsKey(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename, new ManualResetEvent(false));
}
#else
if (m_CurrentlyWriting.Contains(filename))
{
return;
}
else
{
m_CurrentlyWriting.Add(filename);
}
#endif
}
Util.FireAndForget(
delegate { WriteFileCache(filename, asset); }, null, "FlotsamAssetCache.UpdateFileCache");
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[FLOTSAM ASSET CACHE]: Failed to update cache for asset {0}. Exception {1} {2}",
asset.ID, e.Message, e.StackTrace);
}
}
public void Cache(AssetBase asset)
{
// TODO: Spawn this off to some seperate thread to do the actual writing
if (asset != null)
{
//m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Caching asset with id {0}", asset.ID);
if (m_MemoryCacheEnabled)
UpdateMemoryCache(asset.ID, asset);
if (m_FileCacheEnabled)
UpdateFileCache(asset.ID, asset);
}
}
/// <summary>
/// Updates the cached file with the current time.
/// </summary>
/// <param name="filename">Filename.</param>
/// <returns><c>true</c>, if the update was successful, false otherwise.</returns>
private bool UpdateFileLastAccessTime(string filename)
{
try
{
File.SetLastAccessTime(filename, DateTime.Now);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Try to get an asset from the in-memory cache.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private AssetBase GetFromMemoryCache(string id)
{
AssetBase asset = null;
if (m_MemoryCache.TryGetValue(id, out asset))
m_MemoryHits++;
return asset;
}
private bool CheckFromMemoryCache(string id)
{
return m_MemoryCache.Contains(id);
}
/// <summary>
/// Try to get an asset from the file cache.
/// </summary>
/// <param name="id"></param>
/// <returns>An asset retrieved from the file cache. null if there was a problem retrieving an asset.</returns>
private AssetBase GetFromFileCache(string id)
{
string filename = GetFileName(id);
#if WAIT_ON_INPROGRESS_REQUESTS
// Check if we're already downloading this asset. If so, try to wait for it to
// download.
if (m_WaitOnInprogressTimeout > 0)
{
m_RequestsForInprogress++;
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
waitEvent.WaitOne(m_WaitOnInprogressTimeout);
return Get(id);
}
}
#else
// Track how often we have the problem that an asset is requested while
// it is still being downloaded by a previous request.
if (m_CurrentlyWriting.Contains(filename))
{
m_RequestsForInprogress++;
return null;
}
#endif
AssetBase asset = null;
if (File.Exists(filename))
{
try
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
BinaryFormatter bformatter = new BinaryFormatter();
asset = (AssetBase)bformatter.Deserialize(stream);
m_DiskHits++;
}
}
catch (System.Runtime.Serialization.SerializationException e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
// If there was a problem deserializing the asset, the asset may
// either be corrupted OR was serialized under an old format
// {different version of AssetBase} -- we should attempt to
// delete it and re-cache
File.Delete(filename);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to get file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
}
}
return asset;
}
private bool CheckFromFileCache(string id)
{
bool found = false;
string filename = GetFileName(id);
if (File.Exists(filename))
{
try
{
using (FileStream stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
if (stream != null)
found = true;
}
}
catch (Exception e)
{
m_log.ErrorFormat(
"[FLOTSAM ASSET CACHE]: Failed to check file {0} for asset {1}. Exception {2} {3}",
filename, id, e.Message, e.StackTrace);
}
}
return found;
}
public AssetBase Get(string id)
{
m_Requests++;
AssetBase asset = null;
if (m_MemoryCacheEnabled)
asset = GetFromMemoryCache(id);
if (asset == null && m_FileCacheEnabled)
{
asset = GetFromFileCache(id);
if (m_MemoryCacheEnabled && asset != null)
UpdateMemoryCache(id, asset);
}
if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0))
{
m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit");
GenerateCacheHitReport().ForEach(l => m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0}", l));
}
return asset;
}
public bool Check(string id)
{
if (m_MemoryCacheEnabled && CheckFromMemoryCache(id))
return true;
if (m_FileCacheEnabled && CheckFromFileCache(id))
return true;
return false;
}
public AssetBase GetCached(string id)
{
return Get(id);
}
public void Expire(string id)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}", id);
try
{
if (m_FileCacheEnabled)
{
string filename = GetFileName(id);
if (File.Exists(filename))
{
File.Delete(filename);
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Remove(id);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to expire cached file {0}. Exception {1} {2}",
id, e.Message, e.StackTrace);
}
}
public void Clear()
{
if (m_LogLevel >= 2)
m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing caches.");
if (m_FileCacheEnabled)
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
Directory.Delete(dir);
}
}
if (m_MemoryCacheEnabled)
m_MemoryCache.Clear();
}
private void CleanupExpiredFiles(object source, ElapsedEventArgs e)
{
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration);
// Purge all files last accessed prior to this point
DateTime purgeLine = DateTime.Now - m_FileExpiration;
// An asset cache may contain local non-temporary assets that are not in the asset service. Therefore,
// before cleaning up expired files we must scan the objects in the scene to make sure that we retain
// such local assets if they have not been recently accessed.
TouchAllSceneAssets(false);
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
CleanExpiredFiles(dir, purgeLine);
}
}
/// <summary>
/// Recurses through specified directory checking for asset files last
/// accessed prior to the specified purge line and deletes them. Also
/// removes empty tier directories.
/// </summary>
/// <param name="dir"></param>
/// <param name="purgeLine"></param>
private void CleanExpiredFiles(string dir, DateTime purgeLine)
{
try
{
foreach (string file in Directory.GetFiles(dir))
{
if (File.GetLastAccessTime(file) < purgeLine)
{
File.Delete(file);
}
}
// Recurse into lower tiers
foreach (string subdir in Directory.GetDirectories(dir))
{
CleanExpiredFiles(subdir, purgeLine);
}
// Check if a tier directory is empty, if so, delete it
int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length;
if (dirSize == 0)
{
Directory.Delete(dir);
}
else if (dirSize >= m_CacheWarnAt)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration",
dir, dirSize);
}
}
catch (DirectoryNotFoundException)
{
// If we get here, another node on the same box has
// already removed the directory. Continue with next.
}
catch (Exception e)
{
m_log.Warn(
string.Format("[FLOTSAM ASSET CACHE]: Could not complete clean of expired files in {0}, exception ", dir), e);
}
}
/// <summary>
/// Determines the filename for an AssetID stored in the file cache
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private string GetFileName(string id)
{
// Would it be faster to just hash the darn thing?
foreach (char c in m_InvalidChars)
{
id = id.Replace(c, '_');
}
string path = m_CacheDirectory;
for (int p = 1; p <= m_CacheDirectoryTiers; p++)
{
string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen);
path = Path.Combine(path, pathPart);
}
return Path.Combine(path, id);
}
/// <summary>
/// Writes a file to the file cache, creating any nessesary
/// tier directories along the way
/// </summary>
/// <param name="filename"></param>
/// <param name="asset"></param>
private void WriteFileCache(string filename, AssetBase asset)
{
Stream stream = null;
// Make sure the target cache directory exists
string directory = Path.GetDirectoryName(filename);
// Write file first to a temp name, so that it doesn't look
// like it's already cached while it's still writing.
string tempname = Path.Combine(directory, Path.GetRandomFileName());
try
{
try
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
stream = File.Open(tempname, FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, asset);
}
catch (IOException e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Failed to write asset {0} to temporary location {1} (final {2}) on cache in {3}. Exception {4} {5}.",
asset.ID, tempname, filename, directory, e.Message, e.StackTrace);
return;
}
finally
{
if (stream != null)
stream.Close();
}
try
{
// Now that it's written, rename it so that it can be found.
//
// File.Copy(tempname, filename, true);
// File.Delete(tempname);
//
// For a brief period, this was done as a separate copy and then temporary file delete operation to
// avoid an IOException caused by move if some competing thread had already written the file.
// However, this causes exceptions on Windows when other threads attempt to read a file
// which is still being copied. So instead, go back to moving the file and swallow any IOException.
//
// This situation occurs fairly rarely anyway. We assume in this that moves are atomic on the
// filesystem.
File.Move(tempname, filename);
if (m_LogLevel >= 2)
m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID);
}
catch (IOException)
{
// If we see an IOException here it's likely that some other competing thread has written the
// cache file first, so ignore. Other IOException errors (e.g. filesystem full) should be
// signally by the earlier temporary file writing code.
}
}
finally
{
// Even if the write fails with an exception, we need to make sure
// that we release the lock on that file, otherwise it'll never get
// cached
lock (m_CurrentlyWriting)
{
#if WAIT_ON_INPROGRESS_REQUESTS
ManualResetEvent waitEvent;
if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent))
{
m_CurrentlyWriting.Remove(filename);
waitEvent.Set();
}
#else
m_CurrentlyWriting.Remove(filename);
#endif
}
}
}
/// <summary>
/// Scan through the file cache, and return number of assets currently cached.
/// </summary>
/// <param name="dir"></param>
/// <returns></returns>
private int GetFileCacheCount(string dir)
{
int count = Directory.GetFiles(dir).Length;
foreach (string subdir in Directory.GetDirectories(dir))
{
count += GetFileCacheCount(subdir);
}
return count;
}
/// <summary>
/// This notes the last time the Region had a deep asset scan performed on it.
/// </summary>
/// <param name="regionID"></param>
private void StampRegionStatusFile(UUID regionID)
{
string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + regionID.ToString() + ".fac");
try
{
if (File.Exists(RegionCacheStatusFile))
{
File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now);
}
else
{
File.WriteAllText(
RegionCacheStatusFile,
"Please do not delete this file unless you are manually clearing your Flotsam Asset Cache.");
}
}
catch (Exception e)
{
m_log.Warn(
string.Format(
"[FLOTSAM ASSET CACHE]: Could not stamp region status file for region {0}. Exception ",
regionID),
e);
}
}
/// <summary>
/// Iterates through all Scenes, doing a deep scan through assets
/// to update the access time of all assets present in the scene or referenced by assets
/// in the scene.
/// </summary>
/// <param name="storeUncached">
/// If true, then assets scanned which are not found in cache are added to the cache.
/// </param>
/// <returns>Number of distinct asset references found in the scene.</returns>
private int TouchAllSceneAssets(bool storeUncached)
{
UuidGatherer gatherer = new UuidGatherer(m_AssetService);
Dictionary<UUID, bool> assetsFound = new Dictionary<UUID, bool>();
foreach (Scene s in m_Scenes)
{
StampRegionStatusFile(s.RegionInfo.RegionID);
s.ForEachSOG(delegate(SceneObjectGroup e)
{
gatherer.AddForInspection(e);
gatherer.GatherAll();
foreach (UUID assetID in gatherer.GatheredUuids.Keys)
{
if (!assetsFound.ContainsKey(assetID))
{
string filename = GetFileName(assetID.ToString());
if (File.Exists(filename))
{
UpdateFileLastAccessTime(filename);
}
else if (storeUncached)
{
AssetBase cachedAsset = m_AssetService.Get(assetID.ToString());
if (cachedAsset == null && gatherer.GatheredUuids[assetID] != (sbyte)AssetType.Unknown)
assetsFound[assetID] = false;
else
assetsFound[assetID] = true;
}
}
else if (!assetsFound[assetID])
{
m_log.DebugFormat(
"[FLOTSAM ASSET CACHE]: Could not find asset {0}, type {1} referenced by object {2} at {3} in scene {4} when pre-caching all scene assets",
assetID, gatherer.GatheredUuids[assetID], e.Name, e.AbsolutePosition, s.Name);
}
}
gatherer.GatheredUuids.Clear();
});
}
return assetsFound.Count;
}
/// <summary>
/// Deletes all cache contents
/// </summary>
private void ClearFileCache()
{
foreach (string dir in Directory.GetDirectories(m_CacheDirectory))
{
try
{
Directory.Delete(dir, true);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Couldn't clear asset cache directory {0} from {1}. Exception {2} {3}",
dir, m_CacheDirectory, e.Message, e.StackTrace);
}
}
foreach (string file in Directory.GetFiles(m_CacheDirectory))
{
try
{
File.Delete(file);
}
catch (Exception e)
{
m_log.WarnFormat(
"[FLOTSAM ASSET CACHE]: Couldn't clear asset cache file {0} from {1}. Exception {1} {2}",
file, m_CacheDirectory, e.Message, e.StackTrace);
}
}
}
private List<string> GenerateCacheHitReport()
{
List<string> outputLines = new List<string>();
double fileHitRate = (double)m_DiskHits / m_Requests * 100.0;
outputLines.Add(
string.Format("File Hit Rate: {0}% for {1} requests", fileHitRate.ToString("0.00"), m_Requests));
if (m_MemoryCacheEnabled)
{
double memHitRate = (double)m_MemoryHits / m_Requests * 100.0;
outputLines.Add(
string.Format("Memory Hit Rate: {0}% for {1} requests", memHitRate.ToString("0.00"), m_Requests));
}
outputLines.Add(
string.Format(
"Unnecessary requests due to requests for assets that are currently downloading: {0}",
m_RequestsForInprogress));
return outputLines;
}
#region Console Commands
private void HandleConsoleCommand(string module, string[] cmdparams)
{
ICommandConsole con = MainConsole.Instance;
if (cmdparams.Length >= 2)
{
string cmd = cmdparams[1];
switch (cmd)
{
case "status":
if (m_MemoryCacheEnabled)
con.OutputFormat("Memory Cache: {0} assets", m_MemoryCache.Count);
else
con.OutputFormat("Memory cache disabled");
if (m_FileCacheEnabled)
{
int fileCount = GetFileCacheCount(m_CacheDirectory);
con.OutputFormat("File Cache: {0} assets", fileCount);
}
else
{
con.Output("File cache disabled");
}
GenerateCacheHitReport().ForEach(l => con.Output(l));
if (m_FileCacheEnabled)
{
con.Output("Deep scans have previously been performed on the following regions:");
foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac"))
{
string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac","");
DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s);
con.OutputFormat("Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss"));
}
}
break;
case "clear":
if (cmdparams.Length < 2)
{
con.Output("Usage is fcache clear [file] [memory]");
break;
}
bool clearMemory = false, clearFile = false;
if (cmdparams.Length == 2)
{
clearMemory = true;
clearFile = true;
}
foreach (string s in cmdparams)
{
if (s.ToLower() == "memory")
clearMemory = true;
else if (s.ToLower() == "file")
clearFile = true;
}
if (clearMemory)
{
if (m_MemoryCacheEnabled)
{
m_MemoryCache.Clear();
con.Output("Memory cache cleared.");
}
else
{
con.Output("Memory cache not enabled.");
}
}
if (clearFile)
{
if (m_FileCacheEnabled)
{
ClearFileCache();
con.Output("File cache cleared.");
}
else
{
con.Output("File cache not enabled.");
}
}
break;
case "assets":
con.Output("Ensuring assets are cached for all scenes.");
WorkManager.RunInThread(delegate
{
int assetReferenceTotal = TouchAllSceneAssets(true);
con.OutputFormat("Completed check with {0} assets.", assetReferenceTotal);
}, null, "TouchAllSceneAssets");
break;
case "expire":
if (cmdparams.Length < 3)
{
con.OutputFormat("Invalid parameters for Expire, please specify a valid date & time", cmd);
break;
}
string s_expirationDate = "";
DateTime expirationDate;
if (cmdparams.Length > 3)
{
s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2);
}
else
{
s_expirationDate = cmdparams[2];
}
if (!DateTime.TryParse(s_expirationDate, out expirationDate))
{
con.OutputFormat("{0} is not a valid date & time", cmd);
break;
}
if (m_FileCacheEnabled)
CleanExpiredFiles(m_CacheDirectory, expirationDate);
else
con.OutputFormat("File cache not active, not clearing.");
break;
default:
con.OutputFormat("Unknown command {0}", cmd);
break;
}
}
else if (cmdparams.Length == 1)
{
con.Output("fcache assets - Attempt a deep cache of all assets in all scenes");
con.Output("fcache expire <datetime> - Purge assets older then the specified date & time");
con.Output("fcache clear [file] [memory] - Remove cached assets");
con.Output("fcache status - Display cache status");
}
}
#endregion
#region IAssetService Members
public AssetMetadata GetMetadata(string id)
{
AssetBase asset = Get(id);
return asset.Metadata;
}
public byte[] GetData(string id)
{
AssetBase asset = Get(id);
return asset.Data;
}
public bool Get(string id, object sender, AssetRetrieved handler)
{
AssetBase asset = Get(id);
handler(id, sender, asset);
return true;
}
public bool[] AssetsExist(string[] ids)
{
bool[] exist = new bool[ids.Length];
for (int i = 0; i < ids.Length; i++)
{
exist[i] = Check(ids[i]);
}
return exist;
}
public string Store(AssetBase asset)
{
if (asset.FullID == UUID.Zero)
{
asset.FullID = UUID.Random();
}
Cache(asset);
return asset.ID;
}
public bool UpdateContent(string id, byte[] data)
{
AssetBase asset = Get(id);
asset.Data = data;
Cache(asset);
return true;
}
public bool Delete(string id)
{
Expire(id);
return true;
}
#endregion
}
}
| |
using Bridge.Html5;
using System;
namespace Bridge.jQuery2
{
public partial class jQuery
{
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(string content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Element content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Array content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(jQuery content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(string content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(string content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(string content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(string content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Element content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Element content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Element content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Element content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Array content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Array content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Array content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(Array content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(jQuery content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(jQuery content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(jQuery content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery After(jQuery content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery After(Delegate function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery After(Func<int, string, string> function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery After(Func<int, string, Element> function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, after each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery After(Func<int, string, jQuery> function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(string content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Element content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Array content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(jQuery content)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(string content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(string content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(string content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(string content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Element content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Element content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Element content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Element content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Array content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Array content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Array content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(Array content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(jQuery content, string content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(jQuery content, Element content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(jQuery content, Array content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="content">DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.</param>
/// <param name="content2">One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.</param>
/// <returns></returns>
public virtual jQuery Before(jQuery content, jQuery content2)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Before(Delegate function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Before(Func<int, string, string> function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Before(Func<int, string, Element> function)
{
return null;
}
/// <summary>
/// Insert content, specified by the parameter, before each element in the set of matched elements.
/// </summary>
/// <param name="function">A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.</param>
/// <returns></returns>
public virtual jQuery Before(Func<int, string, jQuery> function)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertAfter(string target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertAfter(Element target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertAfter(Array target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements after the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertAfter(jQuery target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertBefore(string target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertBefore(Element target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertBefore(Array target)
{
return null;
}
/// <summary>
/// Insert every element in the set of matched elements before the target.
/// </summary>
/// <param name="target">A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.</param>
/// <returns></returns>
public virtual jQuery InsertBefore(jQuery target)
{
return null;
}
}
}
| |
// <copyright file="TFQMRTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// 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>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Solvers.Iterative
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Tests of Transpose Free Quasi-Minimal Residual iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class TFQMRTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new TFQMR();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Scale it with a funny number
matrix.Multiply(Math.PI, matrix);
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = new SparseMatrix(100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = Vector<Complex>.Build.Dense(matrix.RowCount, 1);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new TFQMR();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
Assert.LessOrEqual(Distance.Chebyshev(y, z), 2*ConvergenceBoundary);
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var vectorb = Vector<Complex>.Build.Random(order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new TFQMR();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-5);
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-5);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new TFQMR();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1.0e-5);
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1.0e-5);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
// Copyright (c) 2004 Mainsoft Co.
//
// 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 Xunit;
namespace System.Data.Tests
{
public class UniqueConstraintTest2
{
[Fact]
public void Columns()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0]);
// Columns 1
Assert.Equal(1, uc.Columns.Length);
// Columns 2
Assert.Equal(dtParent.Columns[0], uc.Columns[0]);
}
[Fact]
public void Equals_O()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
ds.Tables.Add(dtParent);
UniqueConstraint uc1, uc2;
uc1 = new UniqueConstraint(dtParent.Columns[0]);
uc2 = new UniqueConstraint(dtParent.Columns[1]);
// different columnn
Assert.False(uc1.Equals(uc2));
//Two System.Data.ForeignKeyConstraint are equal if they constrain the same columns.
// same column
uc2 = new UniqueConstraint(dtParent.Columns[0]);
Assert.True(uc1.Equals(uc2));
}
[Fact]
public void IsPrimaryKey()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0], false);
dtParent.Constraints.Add(uc);
// primary key 1
Assert.False(uc.IsPrimaryKey);
dtParent.Constraints.Remove(uc);
uc = new UniqueConstraint(dtParent.Columns[0], true);
dtParent.Constraints.Add(uc);
// primary key 2
Assert.True(uc.IsPrimaryKey);
}
[Fact]
public void Table()
{
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
ds.Tables.Add(dtParent);
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0]);
// Table
Assert.Equal(dtParent, uc.Table);
}
[Fact]
public new void ToString()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0], false);
// ToString - default
Assert.Equal(string.Empty, uc.ToString());
uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], false);
// Tostring - Constraint name
Assert.Equal("myConstraint", uc.ToString());
}
[Fact]
public void constraintName()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0]);
// default
Assert.Equal(string.Empty, uc.ConstraintName);
uc.ConstraintName = "myConstraint";
// set/get
Assert.Equal("myConstraint", uc.ConstraintName);
}
[Fact]
public void ctor_DataColumn()
{
Exception tmpEx = new Exception();
var ds = new DataSet();
DataTable dtParent = DataProvider.CreateParentDataTable();
ds.Tables.Add(dtParent);
ds.EnforceConstraints = true;
UniqueConstraint uc = null;
// DataColumn.Unique - without constraint
Assert.False(dtParent.Columns[0].Unique);
uc = new UniqueConstraint(dtParent.Columns[0]);
// Ctor
Assert.False(uc == null);
// DataColumn.Unique - with constraint
Assert.False(dtParent.Columns[0].Unique);
// Ctor - add existing column
dtParent.Rows.Add(new object[] { 99, "str1", "str2" });
dtParent.Constraints.Add(uc);
Assert.Throws<ConstraintException>(() => dtParent.Rows.Add(new object[] { 99, "str1", "str2" }));
DataTable dtChild = DataProvider.CreateChildDataTable();
uc = new UniqueConstraint(dtChild.Columns[1]);
//Column[1] is not unique, will throw exception
// ArgumentException
AssertExtensions.Throws<ArgumentException>(null, () => dtChild.Constraints.Add(uc));
//reset the table
dtParent = DataProvider.CreateParentDataTable();
// DataColumn.Unique = true, will add UniqueConstraint
dtParent.Columns[0].Unique = true;
Assert.Equal(1, dtParent.Constraints.Count);
// Check the created UniqueConstraint
dtParent.Columns[0].Unique = true;
Assert.Equal(typeof(UniqueConstraint).FullName, dtParent.Constraints[0].GetType().FullName);
// add UniqueConstarint that don't belong to the table
AssertExtensions.Throws<ArgumentException>(null, () =>
{
dtParent.Constraints.Add(uc);
});
}
[Fact]
public void ctor_DataColumnNoPrimary()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0], false);
dtParent.Constraints.Add(uc);
// Ctor
Assert.False(uc == null);
// primary key 1
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtParent.Constraints.Remove(uc);
uc = new UniqueConstraint(dtParent.Columns[0], true);
dtParent.Constraints.Add(uc);
// primary key 2
Assert.Equal(1, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_DataColumns()
{
Exception tmpEx = new Exception();
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] });
// Ctor - parent
Assert.False(uc == null);
// Ctor - add existing column
dtParent.Rows.Add(new object[] { 99, "str1", "str2" });
dtParent.Constraints.Add(uc);
Assert.Throws<ConstraintException>(() => dtParent.Rows.Add(new object[] { 99, "str1", "str2" }));
DataTable dtChild = DataProvider.CreateChildDataTable();
uc = new UniqueConstraint(new DataColumn[] { dtChild.Columns[0], dtChild.Columns[1] });
dtChild.Constraints.Add(uc);
// Ctor - child
Assert.False(uc == null);
dtChild.Constraints.Clear();
uc = new UniqueConstraint(new DataColumn[] { dtChild.Columns[1], dtChild.Columns[2] });
//target columnn are not unnique, will throw an exception
// ArgumentException - child
AssertExtensions.Throws<ArgumentException>(null, () => dtChild.Constraints.Add(uc));
}
[Fact]
public void ctor_DataColumnPrimary()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0], false);
dtParent.Constraints.Add(uc);
// Ctor
Assert.False(uc == null);
// primary key 1
Assert.Equal(0, dtParent.PrimaryKey.Length);
dtParent.Constraints.Remove(uc);
uc = new UniqueConstraint(dtParent.Columns[0], true);
dtParent.Constraints.Add(uc);
// primary key 2
Assert.Equal(1, dtParent.PrimaryKey.Length);
}
[Fact]
public void ctor_NameDataColumn()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint("myConstraint", dtParent.Columns[0]);
// Ctor
Assert.False(uc == null);
// Ctor name
Assert.Equal("myConstraint", uc.ConstraintName);
}
[Fact]
public void ctor_NameDataColumnPrimary()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], false);
dtParent.Constraints.Add(uc);
// Ctor
Assert.False(uc == null);
// primary key 1
Assert.Equal(0, dtParent.PrimaryKey.Length);
// Ctor name 1
Assert.Equal("myConstraint", uc.ConstraintName);
dtParent.Constraints.Remove(uc);
uc = new UniqueConstraint("myConstraint", dtParent.Columns[0], true);
dtParent.Constraints.Add(uc);
// primary key 2
Assert.Equal(1, dtParent.PrimaryKey.Length);
// Ctor name 2
Assert.Equal("myConstraint", uc.ConstraintName);
}
[Fact]
public void ctor_NameDataColumns()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0], dtParent.Columns[1] });
// Ctor
Assert.False(uc == null);
// Ctor name
Assert.Equal("myConstraint", uc.ConstraintName);
}
[Fact]
public void ctor_NameDataColumnsPrimary()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0] }, false);
dtParent.Constraints.Add(uc);
// Ctor
Assert.False(uc == null);
// primary key 1
Assert.Equal(0, dtParent.PrimaryKey.Length);
// Ctor name 1
Assert.Equal("myConstraint", uc.ConstraintName);
dtParent.Constraints.Remove(uc);
uc = new UniqueConstraint("myConstraint", new DataColumn[] { dtParent.Columns[0] }, true);
dtParent.Constraints.Add(uc);
// primary key 2
Assert.Equal(1, dtParent.PrimaryKey.Length);
// Ctor name 2
Assert.Equal("myConstraint", uc.ConstraintName);
}
[Fact]
public void extendedProperties()
{
DataTable dtParent = DataProvider.CreateParentDataTable();
UniqueConstraint uc = null;
uc = new UniqueConstraint(dtParent.Columns[0]);
PropertyCollection pc = uc.ExtendedProperties;
// Checking ExtendedProperties default
Assert.True(pc != null);
// Checking ExtendedProperties count
Assert.Equal(0, pc.Count);
}
}
}
| |
// 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="CampaignCriterionServiceClient"/> instances.</summary>
public sealed partial class CampaignCriterionServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="CampaignCriterionServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="CampaignCriterionServiceSettings"/>.</returns>
public static CampaignCriterionServiceSettings GetDefault() => new CampaignCriterionServiceSettings();
/// <summary>
/// Constructs a new <see cref="CampaignCriterionServiceSettings"/> object with default settings.
/// </summary>
public CampaignCriterionServiceSettings()
{
}
private CampaignCriterionServiceSettings(CampaignCriterionServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
GetCampaignCriterionSettings = existing.GetCampaignCriterionSettings;
MutateCampaignCriteriaSettings = existing.MutateCampaignCriteriaSettings;
OnCopy(existing);
}
partial void OnCopy(CampaignCriterionServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignCriterionServiceClient.GetCampaignCriterion</c> and
/// <c>CampaignCriterionServiceClient.GetCampaignCriterionAsync</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 GetCampaignCriterionSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>CampaignCriterionServiceClient.MutateCampaignCriteria</c> and
/// <c>CampaignCriterionServiceClient.MutateCampaignCriteriaAsync</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 MutateCampaignCriteriaSettings { 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="CampaignCriterionServiceSettings"/> object.</returns>
public CampaignCriterionServiceSettings Clone() => new CampaignCriterionServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="CampaignCriterionServiceClient"/> to provide simple configuration of credentials,
/// endpoint etc.
/// </summary>
internal sealed partial class CampaignCriterionServiceClientBuilder : gaxgrpc::ClientBuilderBase<CampaignCriterionServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public CampaignCriterionServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public CampaignCriterionServiceClientBuilder()
{
UseJwtAccessWithScopes = CampaignCriterionServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref CampaignCriterionServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<CampaignCriterionServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override CampaignCriterionServiceClient Build()
{
CampaignCriterionServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<CampaignCriterionServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<CampaignCriterionServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private CampaignCriterionServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return CampaignCriterionServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<CampaignCriterionServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return CampaignCriterionServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => CampaignCriterionServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => CampaignCriterionServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => CampaignCriterionServiceClient.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>CampaignCriterionService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign criteria.
/// </remarks>
public abstract partial class CampaignCriterionServiceClient
{
/// <summary>
/// The default endpoint for the CampaignCriterionService 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 CampaignCriterionService scopes.</summary>
/// <remarks>
/// The default CampaignCriterionService 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="CampaignCriterionServiceClient"/> using the default credentials,
/// endpoint and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignCriterionServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="CampaignCriterionServiceClient"/>.</returns>
public static stt::Task<CampaignCriterionServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new CampaignCriterionServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="CampaignCriterionServiceClient"/> using the default credentials, endpoint
/// and settings. To specify custom credentials or other settings, use
/// <see cref="CampaignCriterionServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="CampaignCriterionServiceClient"/>.</returns>
public static CampaignCriterionServiceClient Create() => new CampaignCriterionServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="CampaignCriterionServiceClient"/> 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="CampaignCriterionServiceSettings"/>.</param>
/// <returns>The created <see cref="CampaignCriterionServiceClient"/>.</returns>
internal static CampaignCriterionServiceClient Create(grpccore::CallInvoker callInvoker, CampaignCriterionServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
CampaignCriterionService.CampaignCriterionServiceClient grpcClient = new CampaignCriterionService.CampaignCriterionServiceClient(callInvoker);
return new CampaignCriterionServiceClientImpl(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 CampaignCriterionService client</summary>
public virtual CampaignCriterionService.CampaignCriterionServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignCriterion GetCampaignCriterion(GetCampaignCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(GetCampaignCriterionRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(GetCampaignCriterionRequest request, st::CancellationToken cancellationToken) =>
GetCampaignCriterionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignCriterion GetCampaignCriterion(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignCriterion(new GetCampaignCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignCriterionAsync(new GetCampaignCriterionRequest
{
ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(string resourceName, st::CancellationToken cancellationToken) =>
GetCampaignCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual gagvr::CampaignCriterion GetCampaignCriterion(gagvr::CampaignCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignCriterion(new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(gagvr::CampaignCriterionName resourceName, gaxgrpc::CallSettings callSettings = null) =>
GetCampaignCriterionAsync(new GetCampaignCriterionRequest
{
ResourceNameAsCampaignCriterionName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)),
}, callSettings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="resourceName">
/// Required. The resource name of the criterion to fetch.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(gagvr::CampaignCriterionName resourceName, st::CancellationToken cancellationToken) =>
GetCampaignCriterionAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateCampaignCriteriaResponse MutateCampaignCriteria(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, st::CancellationToken cancellationToken) =>
MutateCampaignCriteriaAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual MutateCampaignCriteriaResponse MutateCampaignCriteria(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignCriteria(new MutateCampaignCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, gaxgrpc::CallSettings callSettings = null) =>
MutateCampaignCriteriaAsync(new MutateCampaignCriteriaRequest
{
CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)),
Operations =
{
gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)),
},
}, callSettings);
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </summary>
/// <param name="customerId">
/// Required. The ID of the customer whose criteria are being modified.
/// </param>
/// <param name="operations">
/// Required. The list of operations to perform on individual criteria.
/// </param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(string customerId, scg::IEnumerable<CampaignCriterionOperation> operations, st::CancellationToken cancellationToken) =>
MutateCampaignCriteriaAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>CampaignCriterionService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage campaign criteria.
/// </remarks>
public sealed partial class CampaignCriterionServiceClientImpl : CampaignCriterionServiceClient
{
private readonly gaxgrpc::ApiCall<GetCampaignCriterionRequest, gagvr::CampaignCriterion> _callGetCampaignCriterion;
private readonly gaxgrpc::ApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse> _callMutateCampaignCriteria;
/// <summary>
/// Constructs a client wrapper for the CampaignCriterionService service, with the specified gRPC client and
/// settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">
/// The base <see cref="CampaignCriterionServiceSettings"/> used within this client.
/// </param>
public CampaignCriterionServiceClientImpl(CampaignCriterionService.CampaignCriterionServiceClient grpcClient, CampaignCriterionServiceSettings settings)
{
GrpcClient = grpcClient;
CampaignCriterionServiceSettings effectiveSettings = settings ?? CampaignCriterionServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callGetCampaignCriterion = clientHelper.BuildApiCall<GetCampaignCriterionRequest, gagvr::CampaignCriterion>(grpcClient.GetCampaignCriterionAsync, grpcClient.GetCampaignCriterion, effectiveSettings.GetCampaignCriterionSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName);
Modify_ApiCall(ref _callGetCampaignCriterion);
Modify_GetCampaignCriterionApiCall(ref _callGetCampaignCriterion);
_callMutateCampaignCriteria = clientHelper.BuildApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse>(grpcClient.MutateCampaignCriteriaAsync, grpcClient.MutateCampaignCriteria, effectiveSettings.MutateCampaignCriteriaSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callMutateCampaignCriteria);
Modify_MutateCampaignCriteriaApiCall(ref _callMutateCampaignCriteria);
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_GetCampaignCriterionApiCall(ref gaxgrpc::ApiCall<GetCampaignCriterionRequest, gagvr::CampaignCriterion> call);
partial void Modify_MutateCampaignCriteriaApiCall(ref gaxgrpc::ApiCall<MutateCampaignCriteriaRequest, MutateCampaignCriteriaResponse> call);
partial void OnConstruction(CampaignCriterionService.CampaignCriterionServiceClient grpcClient, CampaignCriterionServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC CampaignCriterionService client</summary>
public override CampaignCriterionService.CampaignCriterionServiceClient GrpcClient { get; }
partial void Modify_GetCampaignCriterionRequest(ref GetCampaignCriterionRequest request, ref gaxgrpc::CallSettings settings);
partial void Modify_MutateCampaignCriteriaRequest(ref MutateCampaignCriteriaRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override gagvr::CampaignCriterion GetCampaignCriterion(GetCampaignCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignCriterionRequest(ref request, ref callSettings);
return _callGetCampaignCriterion.Sync(request, callSettings);
}
/// <summary>
/// Returns the requested criterion in full detail.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [HeaderError]()
/// [InternalError]()
/// [QuotaError]()
/// [RequestError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<gagvr::CampaignCriterion> GetCampaignCriterionAsync(GetCampaignCriterionRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_GetCampaignCriterionRequest(ref request, ref callSettings);
return _callGetCampaignCriterion.Async(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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 MutateCampaignCriteriaResponse MutateCampaignCriteria(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignCriteriaRequest(ref request, ref callSettings);
return _callMutateCampaignCriteria.Sync(request, callSettings);
}
/// <summary>
/// Creates, updates, or removes criteria. Operation statuses are returned.
///
/// List of thrown errors:
/// [AdxError]()
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CampaignCriterionError]()
/// [CollectionSizeError]()
/// [ContextError]()
/// [CriterionError]()
/// [DatabaseError]()
/// [DistinctError]()
/// [FieldError]()
/// [FieldMaskError]()
/// [FunctionError]()
/// [HeaderError]()
/// [IdError]()
/// [InternalError]()
/// [MutateError]()
/// [NewResourceCreationError]()
/// [NotEmptyError]()
/// [NullError]()
/// [OperationAccessDeniedError]()
/// [OperatorError]()
/// [QuotaError]()
/// [RangeError]()
/// [RegionCodeError]()
/// [RequestError]()
/// [ResourceCountLimitExceededError]()
/// [SizeLimitError]()
/// [StringFormatError]()
/// [StringLengthError]()
/// </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<MutateCampaignCriteriaResponse> MutateCampaignCriteriaAsync(MutateCampaignCriteriaRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_MutateCampaignCriteriaRequest(ref request, ref callSettings);
return _callMutateCampaignCriteria.Async(request, callSettings);
}
}
}
| |
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.RDS.Model
{
/// <summary>
/// Container for the parameters to the CreateDBInstanceReadReplica operation.
/// <para> Creates a DB Instance that acts as a Read Replica of a source DB Instance. </para> <para> All Read Replica DB Instances are created
/// as Single-AZ deployments with backups disabled. All other DB Instance attributes (including DB Security Groups and DB Parameter Groups) are
/// inherited from the source DB Instance, except as specified below. </para> <para><b>IMPORTANT:</b> The source DB Instance must have backup
/// retention enabled. </para>
/// </summary>
/// <seealso cref="Amazon.RDS.AmazonRDS.CreateDBInstanceReadReplica"/>
public class CreateDBInstanceReadReplicaRequest : AmazonWebServiceRequest
{
private string dBInstanceIdentifier;
private string sourceDBInstanceIdentifier;
private string dBInstanceClass;
private string availabilityZone;
private int? port;
private bool? autoMinorVersionUpgrade;
private int? iops;
private string optionGroupName;
private bool? publiclyAccessible;
/// <summary>
/// The DB Instance identifier of the Read Replica. This is the unique key that identifies a DB Instance. This parameter is stored as a
/// lowercase string.
///
/// </summary>
public string DBInstanceIdentifier
{
get { return this.dBInstanceIdentifier; }
set { this.dBInstanceIdentifier = value; }
}
/// <summary>
/// Sets the DBInstanceIdentifier property
/// </summary>
/// <param name="dBInstanceIdentifier">The value to set for the DBInstanceIdentifier property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithDBInstanceIdentifier(string dBInstanceIdentifier)
{
this.dBInstanceIdentifier = dBInstanceIdentifier;
return this;
}
// Check to see if DBInstanceIdentifier property is set
internal bool IsSetDBInstanceIdentifier()
{
return this.dBInstanceIdentifier != null;
}
/// <summary>
/// The identifier of the DB Instance that will act as the source for the Read Replica. Each DB Instance can have up to five Read Replicas.
/// Constraints: Must be the identifier of an existing DB Instance that is not already a Read Replica DB Instance.
///
/// </summary>
public string SourceDBInstanceIdentifier
{
get { return this.sourceDBInstanceIdentifier; }
set { this.sourceDBInstanceIdentifier = value; }
}
/// <summary>
/// Sets the SourceDBInstanceIdentifier property
/// </summary>
/// <param name="sourceDBInstanceIdentifier">The value to set for the SourceDBInstanceIdentifier property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithSourceDBInstanceIdentifier(string sourceDBInstanceIdentifier)
{
this.sourceDBInstanceIdentifier = sourceDBInstanceIdentifier;
return this;
}
// Check to see if SourceDBInstanceIdentifier property is set
internal bool IsSetSourceDBInstanceIdentifier()
{
return this.sourceDBInstanceIdentifier != null;
}
/// <summary>
/// The compute and memory capacity of the Read Replica. Valid Values: <c>db.m1.small | db.m1.medium | db.m1.large | db.m1.xlarge | db.m2.xlarge
/// |db.m2.2xlarge | db.m2.4xlarge</c> Default: Inherits from the source DB Instance.
///
/// </summary>
public string DBInstanceClass
{
get { return this.dBInstanceClass; }
set { this.dBInstanceClass = value; }
}
/// <summary>
/// Sets the DBInstanceClass property
/// </summary>
/// <param name="dBInstanceClass">The value to set for the DBInstanceClass property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithDBInstanceClass(string dBInstanceClass)
{
this.dBInstanceClass = dBInstanceClass;
return this;
}
// Check to see if DBInstanceClass property is set
internal bool IsSetDBInstanceClass()
{
return this.dBInstanceClass != null;
}
/// <summary>
/// The Amazon EC2 Availability Zone that the Read Replica will be created in. Default: A random, system-chosen Availability Zone in the
/// endpoint's region. Example: <c>us-east-1d</c>
///
/// </summary>
public string AvailabilityZone
{
get { return this.availabilityZone; }
set { this.availabilityZone = value; }
}
/// <summary>
/// Sets the AvailabilityZone property
/// </summary>
/// <param name="availabilityZone">The value to set for the AvailabilityZone property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithAvailabilityZone(string availabilityZone)
{
this.availabilityZone = availabilityZone;
return this;
}
// Check to see if AvailabilityZone property is set
internal bool IsSetAvailabilityZone()
{
return this.availabilityZone != null;
}
/// <summary>
/// The port number that the DB Instance uses for connections. Default: Inherits from the source DB Instance Valid Values: <c>1150-65535</c>
///
/// </summary>
public int Port
{
get { return this.port ?? default(int); }
set { this.port = value; }
}
/// <summary>
/// Sets the Port property
/// </summary>
/// <param name="port">The value to set for the Port property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithPort(int port)
{
this.port = port;
return this;
}
// Check to see if Port property is set
internal bool IsSetPort()
{
return this.port.HasValue;
}
/// <summary>
/// Indicates that minor engine upgrades will be applied automatically to the Read Replica during the maintenance window. Default: Inherits from
/// the source DB Instance
///
/// </summary>
public bool AutoMinorVersionUpgrade
{
get { return this.autoMinorVersionUpgrade ?? default(bool); }
set { this.autoMinorVersionUpgrade = value; }
}
/// <summary>
/// Sets the AutoMinorVersionUpgrade property
/// </summary>
/// <param name="autoMinorVersionUpgrade">The value to set for the AutoMinorVersionUpgrade property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithAutoMinorVersionUpgrade(bool autoMinorVersionUpgrade)
{
this.autoMinorVersionUpgrade = autoMinorVersionUpgrade;
return this;
}
// Check to see if AutoMinorVersionUpgrade property is set
internal bool IsSetAutoMinorVersionUpgrade()
{
return this.autoMinorVersionUpgrade.HasValue;
}
/// <summary>
/// The amount of Provisioned IOPS (input/output operations per second) to be initially allocated for the DB Instance.
///
/// </summary>
public int Iops
{
get { return this.iops ?? default(int); }
set { this.iops = value; }
}
/// <summary>
/// Sets the Iops property
/// </summary>
/// <param name="iops">The value to set for the Iops property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithIops(int iops)
{
this.iops = iops;
return this;
}
// Check to see if Iops property is set
internal bool IsSetIops()
{
return this.iops.HasValue;
}
/// <summary>
/// The option group the DB instance will be associated with. If omitted, the default Option Group for the engine specified will be used.
///
/// </summary>
public string OptionGroupName
{
get { return this.optionGroupName; }
set { this.optionGroupName = value; }
}
/// <summary>
/// Sets the OptionGroupName property
/// </summary>
/// <param name="optionGroupName">The value to set for the OptionGroupName property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithOptionGroupName(string optionGroupName)
{
this.optionGroupName = optionGroupName;
return this;
}
// Check to see if OptionGroupName property is set
internal bool IsSetOptionGroupName()
{
return this.optionGroupName != null;
}
/// <summary>
/// Specifies the accessibility options for the DB Instance. A value of true specifies an Internet-facing instance with a publicly resolvable
/// DNS name, which resolves to a public IP address. A value of false specifies an internal instance with a DNS name that resolves to a private
/// IP address. Default: The default behavior varies depending on whether a VPC has been requested or not. The following list shows the default
/// behavior in each case. <ul> <li><b>Default VPC:</b>true</li> <li><b>VPC:</b>false</li> </ul> If no DB subnet group has been specified as
/// part of the request and the PubliclyAccessible value has not been set, the DB instance will be publicly accessible. If a specific DB subnet
/// group has been specified as part of the request and the PubliclyAccessible value has not been set, the DB instance will be private.
///
/// </summary>
public bool PubliclyAccessible
{
get { return this.publiclyAccessible ?? default(bool); }
set { this.publiclyAccessible = value; }
}
/// <summary>
/// Sets the PubliclyAccessible property
/// </summary>
/// <param name="publiclyAccessible">The value to set for the PubliclyAccessible property </param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public CreateDBInstanceReadReplicaRequest WithPubliclyAccessible(bool publiclyAccessible)
{
this.publiclyAccessible = publiclyAccessible;
return this;
}
// Check to see if PubliclyAccessible property is set
internal bool IsSetPubliclyAccessible()
{
return this.publiclyAccessible.HasValue;
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Dialogs;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Core.Geoprocessing;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using System.Windows.Input;
using System.Collections.ObjectModel;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using System.Windows.Data;
using System.Windows.Threading;
using System.Windows;
namespace SLR_Analyst
{
internal class SLR_DockpaneViewModel : DockPane
{
private const string _dockPaneID = "SLR_Analyst_SLR_Dockpane";
protected SLR_DockpaneViewModel()
{
_btnSelectLayerBySLRCmd = new RelayCommand(() => SelectLayerBySLR(), () => true);
SliderValue = 0;
CkbLandUseChecked = true;
}
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null) return;
pane.Activate();
}
// Parcel layer selection check:
private bool _ckbParcelChecked;
public bool CkbParcelChecked
{
get { return _ckbParcelChecked; }
set
{
SetProperty(ref _ckbParcelChecked, value, () => CkbParcelChecked);
}
}
// LandUse layer selection check:
private bool _ckbLandUseChecked;
public bool CkbLandUseChecked
{
get { return _ckbLandUseChecked; }
set
{
SetProperty(ref _ckbLandUseChecked, value, () => CkbLandUseChecked);
}
}
// Street layer selection check:
private bool _ckbStreetChecked;
public bool CkbStreetChecked
{
get { return _ckbStreetChecked; }
set
{
SetProperty(ref _ckbStreetChecked, value, () => CkbStreetChecked);
}
}
/// <summary>
/// Text shown near the top of the DockPane.
/// </summary>
private string _heading = "Sea Level Rise Viewer";
public string Heading
{
get { return _heading; }
set
{
SetProperty(ref _heading, value, () => Heading);
}
}
public class ChartItem
{
public string Title { get; set; } // coil456
public double Value { get; set; } // 334
public string TooltipLabel
{
get { return string.Format("Code = {0}", this.Value); }
}
}
// Slider layer selection check:
private int _sliderValue;
public int SliderValue
{
get { return _sliderValue; }
set
{
SetProperty(ref _sliderValue, value, () => SliderValue);
}
}
#region Commands
private RelayCommand _btnSelectLayerBySLRCmd;
public ICommand BtnSelectLayerBySLRCmd
{
get
{
return _btnSelectLayerBySLRCmd;
}
}
#endregion
#region SliderUpdate
public void SliderUpdate(double sliderValue)
{
// ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Dude, slider value: " + Convert.ToString(sliderValue));
// Set up the list of SLR layers and turn them on/off depending on what's selected
// IReadOnlyList<Layer> layers = ArcGIS.Desktop.Mapping.MapView.Active.Map.FindLayers("dc_slr/slr_3ft", true);
// TOGGLE THE VISIBILITY
// https://github.com/esri/arcgis-pro-sdk/wiki/ProSnippets-MapAuthoring#find-a-layer
// turn off visibility of any other SLR layer
//var SLRLayer1 = MapView.Active.Map.FindLayers("dc_slr/slr_3ft").FirstOrDefault() as ServiceLayer;
//SLRLayer1.SetVisibility(false);
// turn on visibility of current SLR layer
//var SLRLayer2 = MapView.Active.Map.FindLayers("dc_slr/slr_6ft").FirstOrDefault() as ServiceLayer;
//SLRLayer2.SetVisibility(true);
QueuedTask.Run(() =>
{
var activeMapView = MapView.Active;
if (activeMapView == null) return;
var myLayers = activeMapView.Map.GetLayersAsFlattenedList().OfType<FeatureLayer>(); // OfType<ServiceLayer>();
foreach (var myLayer in myLayers)
{
// ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(myLayer.Name, "ServiceLayers");
//// if(myLayer.Name.StartsWith("dc_slr"))
if (myLayer.Name.StartsWith("FL_SLR_Study"))
myLayer.SetVisibility(false);
}
// if (sliderValue == 0) return;
// var SLRLayer1 = MapView.Active.Map.FindLayers("dc_slr/slr_" + sliderValue + "ft").FirstOrDefault() as ServiceLayer;
// FL_MFL2_slr_6ft
var SLRLayer1 = activeMapView.Map.FindLayers("FL_SLR_Study_" + sliderValue + "ft").FirstOrDefault() as FeatureLayer;
SLRLayer1.SetVisibility(true);
});
}
#endregion
public async void SelectLayerBySLR()
{
// Get checkbox values for selection
// checkBox.IsChecked.Value
// Get the slider value for the current SLR Layer
string strSLRLayerName = "FL_SLR_Study_" + Convert.ToString(_sliderValue) + "ft";
// If SLR layer is set to Zero feet, or no layers are checked for selection, then exit.
if (_sliderValue == 0)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Set slider to an SLR height of 1 - 6 feet", "Set Slider Value");
return;
}
if (_ckbLandUseChecked == false && _ckbParcelChecked == false && _ckbStreetChecked == false)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Select checkbox of study layer(s) to review", "Select Study Layer(s)");
return;
}
// Select Study Area Layers based on what is visible
await QueuedTask.Run(async () =>
{
var activeMapView = MapView.Active;
if (activeMapView == null) return;
// For sub-selection
SpatialQueryFilter spatialFilter = new SpatialQueryFilter
{
FilterGeometry = new PolygonBuilder(MapView.Active.Extent).ToGeometry(),
SpatialRelationship = SpatialRelationship.Intersects
};
string luContentList = "\r\n** LAND USE **\r\n";
string parcelContentList = "\r\n\r\n** PARCELS **\r\n";
string streetContentList = "\r\n\r\n** STREETS **\r\n";
IList<KeyValueWithTooltip> luKv = new List<KeyValueWithTooltip>();
IList<KeyValueWithTooltip> pKv = new List<KeyValueWithTooltip>();
IList<KeyValueWithTooltip> sKv = new List<KeyValueWithTooltip>();
// set titles & report configuration
var paneConfiguration = _ckbLandUseChecked ? "Land Use" : string.Empty;
if (_ckbParcelChecked)
{
paneConfiguration += paneConfiguration.Length > 0 ?
(_ckbStreetChecked ? " , Pacels, and Street" : " and Parcels") :
(_ckbStreetChecked ? "Pacels and Street" : "Parcels");
}
else
{
paneConfiguration += paneConfiguration.Length > 0 ?
(_ckbStreetChecked ? " and Street" : string.Empty) :
(_ckbStreetChecked ? " Street" : string.Empty);
}
paneConfiguration = "This report is showing effects on: " + paneConfiguration;
var paneTitle = $@"Sea Level Rise of {_sliderValue} Feet {Environment.NewLine}";
// ** PARCELS
//if (_ckbParcelChecked == true)
{
var ParcelsLayer = MapView.Active.Map.FindLayers("Parcels_Study").FirstOrDefault() as BasicFeatureLayer;
ParcelsLayer.ClearSelection();
var args = Geoprocessing.MakeValueArray("Parcels_Study", "intersect", strSLRLayerName);
await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);
Selection ParcelsSelection = ParcelsLayer.Select(spatialFilter, SelectionCombinationMethod.And);
int parcelsSelectionCount;
parcelsSelectionCount = ParcelsSelection.GetCount();
// Format parcels report for Textbox output:
string parcelsSelectionCountstring = Convert.ToString(parcelsSelectionCount);
parcelContentList = parcelContentList + "* TOTAL: " + parcelsSelectionCountstring + " Parcels affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";
// LOOP THROUGH THE PARCEL SELECTION AND GET THE UNIQUE LIST OF SUBCODES.
// Create list
List<string> ParcelCodeList = new List<string> { };
// Populate list
using (RowCursor ParcelRowCursor = ParcelsSelection.Search(null, false))
{
while (ParcelRowCursor.MoveNext())
{
using (Row currentRow = ParcelRowCursor.Current)
{
ParcelCodeList.Add(Convert.ToString(currentRow["SUBCODE"]));
}
}
}
ParcelCodeList.Sort();
int count;
// Get unique values and counts in the list
foreach (var item in ParcelCodeList.Distinct())
{
count = ParcelCodeList.Where(x => x.Equals(item)).Count();
parcelContentList = parcelContentList + Convert.ToString(count) + " instances of Code: " + item + "\r\n";
pKv.Add(new KeyValueWithTooltip() { Code = $@"Sub Code: {item}", Key = item.ToString(), Value = count });
}
// Dispose of data classes
ParcelsSelection.Dispose();
}
// ** STREETS
//if (_ckbStreetChecked == true)
{
var StreetsLayer = MapView.Active.Map.FindLayers("Streets_Study").FirstOrDefault() as BasicFeatureLayer;
StreetsLayer.ClearSelection();
var args = Geoprocessing.MakeValueArray("Streets_Study", "intersect", strSLRLayerName);
await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);
Selection StreetsSelection = StreetsLayer.Select(spatialFilter, SelectionCombinationMethod.And);
int streetsSelectionCount;
streetsSelectionCount = StreetsSelection.GetCount();
// Format streets report for Textbox output:
string streetSelectionCountstring = Convert.ToString(streetsSelectionCount);
streetContentList = streetContentList + "* TOTAL: " + streetSelectionCountstring + " Streets affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";
// LOOP THROUGH THE STREET SELECTION AND GET THE UNIQUE LIST OF CODES.
// Create list
List<string> StreetCodeList = new List<string> { };
// Populate list
using (RowCursor StreetRowCursor = StreetsSelection.Search(null, false))
{
while (StreetRowCursor.MoveNext())
{
using (Row currentRow = StreetRowCursor.Current)
{
StreetCodeList.Add(Convert.ToString(currentRow["CLASS"]));
}
}
}
StreetCodeList.Sort();
int count;
// Get unique values and counts in the list
foreach (var item in StreetCodeList.Distinct())
{
count = StreetCodeList.Where(x => x.Equals(item)).Count();
streetContentList = streetContentList + Convert.ToString(count) + " instances of Code: " + item + "\r\n";
sKv.Add(new KeyValueWithTooltip() { Code = $@"Class: {item}", Key = item, Value = count });
}
// Dispose of data classes
StreetsSelection.Dispose();
}
// ** LAND USE
//if (_ckbLandUseChecked == true)
{
// Get selection and make selection on map extent only if needed
var LandUseLayer = MapView.Active.Map.FindLayers("Land_Use_Study").FirstOrDefault() as BasicFeatureLayer;
LandUseLayer.ClearSelection();
var args = Geoprocessing.MakeValueArray("Land_Use_Study", "intersect", strSLRLayerName);
await Geoprocessing.ExecuteToolAsync("SelectLayerByLocation_management", args);
Selection LandUseSelection = LandUseLayer.Select(spatialFilter, SelectionCombinationMethod.And);
int luSelectionCount;
luSelectionCount = LandUseSelection.GetCount();
// Format land use report for Textbox output:
string luSelectionCountstring = Convert.ToString(luSelectionCount);
luContentList = luContentList + "* TOTAL: " + luSelectionCountstring + " Land Use areas affected.\r\n \r\n* Unique Codes in Affected Area: \r\n";
// LOOP THROUGH THE LANDUSE SELECTION AND GET THE UNIQUE LIST OF CODES.
// Create list
List<string> LandUseCodeList = new List<string> { };
// Populate list
using (RowCursor LandUseRowCursor = LandUseSelection.Search(null, false))
{
while (LandUseRowCursor.MoveNext())
{
using (Row currentRow = LandUseRowCursor.Current)
{
LandUseCodeList.Add(Convert.ToString(currentRow["LU"]));
}
}
}
LandUseCodeList.Sort();
int count;
// Get unique values and counts in the list
foreach (var item in LandUseCodeList.Distinct())
{
count = LandUseCodeList.Where(x => x.Equals(item)).Count();
luContentList = luContentList + Convert.ToString(count) + " instances of Code: " + item + "\r\n";
luKv.Add(new KeyValueWithTooltip() { Code = $@"LU Code: {item}", Key = item.ToString(), Value = count });
}
// Dispose of data classes
LandUseSelection.Dispose();
} // End Parcel Routine
string reportText = "SEA LEVEL RISE REPORT: " + SliderValue + "-FEET LEVEL EFFECTS \r\n";
if (_ckbLandUseChecked) reportText += luContentList;
if (_ckbParcelChecked) reportText += parcelContentList;
if (_ckbStreetChecked) reportText += streetContentList;
await System.Windows.Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
Module1.CreateNewSlrPane (paneTitle, paneConfiguration, reportText,
_ckbLandUseChecked, _ckbParcelChecked, _ckbStreetChecked,
luKv, pKv, sKv);
}));
}); // Close QueuedTask
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class SLR_Dockpane_ShowButton : Button
{
protected override void OnClick()
{
SLR_DockpaneViewModel.Show();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.Azure.Management.Network.Fluent
{
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent.PublicIPAddress.Definition;
using Microsoft.Azure.Management.Network.Fluent.PublicIPAddress.Update;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
internal partial class PublicIPAddressImpl
{
/// <summary>
/// Gets the assigned reverse FQDN, if any.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.ReverseFqdn
{
get
{
return this.ReverseFqdn();
}
}
/// <summary>
/// Gets true if this public IP address is assigned to a network interface.
/// </summary>
bool Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.HasAssignedNetworkInterface
{
get
{
return this.HasAssignedNetworkInterface();
}
}
/// <summary>
/// Gets the IP version of the public IP address.
/// </summary>
Models.IPVersion Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.Version
{
get
{
return this.Version();
}
}
/// <summary>
/// Gets the assigned leaf domain label.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.LeafDomainLabel
{
get
{
return this.LeafDomainLabel();
}
}
/// <summary>
/// Gets the assigned FQDN (fully qualified domain name).
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.Fqdn
{
get
{
return this.Fqdn();
}
}
/// <return>The load balancer public frontend that this public IP address is assigned to.</return>
Microsoft.Azure.Management.Network.Fluent.ILoadBalancerPublicFrontend Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.GetAssignedLoadBalancerFrontend()
{
return this.GetAssignedLoadBalancerFrontend();
}
/// <summary>
/// Gets true if this public IP address is assigned to a load balancer.
/// </summary>
bool Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.HasAssignedLoadBalancer
{
get
{
return this.HasAssignedLoadBalancer();
}
}
/// <summary>
/// Gets public IP address sku.
/// </summary>
Microsoft.Azure.Management.Network.Fluent.Models.PublicIPSkuType Microsoft.Azure.Management.Network.Fluent.IPublicIPAddressBeta.Sku
{
get
{
return this.Sku();
}
}
/// <summary>
/// Gets the availability zones assigned to the public IP address.
/// </summary>
System.Collections.Generic.ISet<Microsoft.Azure.Management.ResourceManager.Fluent.Core.AvailabilityZoneId> Microsoft.Azure.Management.Network.Fluent.IPublicIPAddressBeta.AvailabilityZones
{
get
{
return this.AvailabilityZones();
}
}
/// <summary>
/// Gets the idle connection timeout setting (in minutes).
/// </summary>
int Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.IdleTimeoutInMinutes
{
get
{
return this.IdleTimeoutInMinutes();
}
}
/// <return>The network interface IP configuration that this public IP address is assigned to.</return>
Microsoft.Azure.Management.Network.Fluent.INicIPConfiguration Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.GetAssignedNetworkInterfaceIPConfiguration()
{
return this.GetAssignedNetworkInterfaceIPConfiguration();
}
/// <summary>
/// Gets the assigned IP address.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.IPAddress
{
get
{
return this.IPAddress();
}
}
/// <summary>
/// Gets the IP address allocation method (Static/Dynamic).
/// </summary>
Models.IPAllocationMethod Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress.IPAllocationMethod
{
get
{
return this.IPAllocationMethod();
}
}
UpdatableWithTags.UpdatableWithTags.IUpdateWithTags<IPublicIPAddress> IUpdatableWithTags<IPublicIPAddress>.UpdateTags()
{
return UpdateTags();
}
/// <summary>
/// Specifies the timeout (in minutes) for an idle connection.
/// </summary>
/// <param name="minutes">The length of the time out in minutes.</param>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithIdleTimout.WithIdleTimeoutInMinutes(int minutes)
{
return this.WithIdleTimeoutInMinutes(minutes);
}
/// <summary>
/// Specifies the reverse FQDN to assign to this public IP address.
/// </summary>
/// <param name="reverseFQDN">The reverse FQDN to assign.</param>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithReverseFQDN.WithReverseFqdn(string reverseFQDN)
{
return this.WithReverseFqdn(reverseFQDN);
}
/// <summary>
/// Ensures that no reverse FQDN will be used.
/// </summary>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithReverseFQDN.WithoutReverseFqdn()
{
return this.WithoutReverseFqdn();
}
/// <summary>
/// Specifies the reverse FQDN to assign to this public IP address.
/// </summary>
/// <param name="reverseFQDN">The reverse FQDN to assign.</param>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithReverseFQDN.WithReverseFqdn(string reverseFQDN)
{
return this.WithReverseFqdn(reverseFQDN);
}
/// <summary>
/// Ensures that no reverse FQDN will be used.
/// </summary>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithReverseFQDN.WithoutReverseFqdn()
{
return this.WithoutReverseFqdn();
}
/// <summary>
/// Ensures that no leaf domain label will be used.
/// This means that this public IP address will not be associated with a domain name.
/// </summary>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithLeafDomainLabel.WithoutLeafDomainLabel()
{
return this.WithoutLeafDomainLabel();
}
/// <summary>
/// Specifies the leaf domain label to associate with this public IP address.
/// The fully qualified domain name (FQDN)
/// will be constructed automatically by appending the rest of the domain to this label.
/// </summary>
/// <param name="dnsName">The leaf domain label to use. This must follow the required naming convention for leaf domain names.</param>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithLeafDomainLabel.WithLeafDomainLabel(string dnsName)
{
return this.WithLeafDomainLabel(dnsName);
}
/// <summary>
/// Ensures that no leaf domain label will be used.
/// This means that this public IP address will not be associated with a domain name.
/// </summary>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithLeafDomainLabel.WithoutLeafDomainLabel()
{
return this.WithoutLeafDomainLabel();
}
/// <summary>
/// Specifies the leaf domain label to associate with this public IP address.
/// The fully qualified domain name (FQDN)
/// will be constructed automatically by appending the rest of the domain to this label.
/// </summary>
/// <param name="dnsName">The leaf domain label to use. This must follow the required naming convention for leaf domain names.</param>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithLeafDomainLabel.WithLeafDomainLabel(string dnsName)
{
return this.WithLeafDomainLabel(dnsName);
}
/// <summary>
/// Enables static IP address allocation.
/// Use PublicIPAddress.ipAddress() after the public IP address is created to obtain the
/// actual IP address allocated for this resource by Azure.
/// </summary>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithIPAddress.WithStaticIP()
{
return this.WithStaticIP();
}
/// <summary>
/// Enables dynamic IP address allocation.
/// </summary>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithIPAddress.WithDynamicIP()
{
return this.WithDynamicIP();
}
/// <summary>
/// Enables static IP address allocation.
/// Use PublicIPAddress.ipAddress() after the public IP address is updated to
/// obtain the actual IP address allocated for this resource by Azure.
/// </summary>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithIPAddress.WithStaticIP()
{
return this.WithStaticIP();
}
/// <summary>
/// Enables dynamic IP address allocation.
/// </summary>
/// <return>The next stage of the resource update.</return>
PublicIPAddress.Update.IUpdate PublicIPAddress.Update.IWithIPAddress.WithDynamicIP()
{
return this.WithDynamicIP();
}
/// <summary>
/// Specifies the timeout (in minutes) for an idle connection.
/// </summary>
/// <param name="minutes">The length of the time out in minutes.</param>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithIdleTimeout.WithIdleTimeoutInMinutes(int minutes)
{
return this.WithIdleTimeoutInMinutes(minutes);
}
/// <summary>
/// Specifies the availability zone for the IP address.
/// </summary>
/// <param name="zoneId">The zone identifier.</param>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithAvailabilityZone.WithAvailabilityZone(AvailabilityZoneId zoneId)
{
return this.WithAvailabilityZone(zoneId);
}
/// <summary>
/// Specifies the SKU for the IP address.
/// </summary>
/// <param name="skuType">The SKU type.</param>
/// <return>The next stage of the definition.</return>
PublicIPAddress.Definition.IWithCreate PublicIPAddress.Definition.IWithSku.WithSku(PublicIPSkuType skuType)
{
return this.WithSku(skuType);
}
public IAppliableWithTags<IPublicIPAddress> WithoutTag(string key)
{
return base.WithoutTag(key);
}
public IAppliableWithTags<IPublicIPAddress> WithTag(string key, string value)
{
return base.WithTag(key, value);
}
public IAppliableWithTags<IPublicIPAddress> WithTags(IDictionary<string, string> tags)
{
return base.WithTags(tags);
}
}
}
| |
using System;
using System.Collections.Generic;
using Accountant.Web.Controllers;
using Accountant.Web.Models;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace Accountant.Web.Tests
{
public class TransactionsControllerTests
{
[Fact]
public void Get_ReturnsAListWithAllTransactions()
{
// arrange
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.AllItems)
.Returns(GetTestTransactions());
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Get();
// assert
var transactions = Assert.IsType<List<Transaction>>(result);
Assert.Equal(2, transactions.Count);
}
[Fact]
public void Get_ReturnsNotFoundObjectResult_GivenNonexistentTransactionId()
{
// arrange
var mockRepo = new Mock<ITransactionRepository>();
var controller = new TransactionsController(mockRepo.Object);
var nonExistentTransactionId = 999;
// act
var result = controller.Get(nonExistentTransactionId);
// assert
var actionResult = Assert.IsType<ActionResult<Transaction>>(result);
Assert.IsType<NotFoundObjectResult>(actionResult.Result);
}
[Fact]
public void Get_ReturnsTransaction_GivenExistentTransactionId()
{
// arrange
int existentTransactionId = 123;
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.GetById(existentTransactionId))
.Returns(GetTestTransaction());
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Get(existentTransactionId);
// assert
var actionResult = Assert.IsType<ActionResult<Transaction>>(result);
var transaction = Assert.IsType<Transaction>(actionResult.Value);
Assert.Equal(20, transaction.Amount);
}
[Fact]
public void Post_ReturnsBadRequestObjectResult_GivenInvalidModel()
{
// arrange
var mockRepo = new Mock<ITransactionRepository>();
var controller = new TransactionsController(mockRepo.Object);
controller.ModelState.AddModelError("error", "some error");
// act
var result = controller.Post(transaction: null);
// assert
var actionResult = Assert.IsType<ActionResult<Transaction>>(result);
Assert.IsType<BadRequestObjectResult>(actionResult.Result);
}
[Fact]
public void Post_ReturnsNewlyCreatedTransaction()
{
// arrange
var mockRepo = new Mock<ITransactionRepository>();
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Post(new Transaction());
// assert
var actionResult = Assert.IsType<ActionResult<Transaction>>(result);
var createdAtActionResult = Assert.IsType<CreatedAtActionResult>(actionResult.Result);
Assert.IsType<Transaction>(createdAtActionResult.Value);
}
[Fact]
public void Put_ReturnsBadRequestObjectResult_GivenInvalidModel()
{
// arrange
var mockRepo = new Mock<ITransactionRepository>();
var controller = new TransactionsController(mockRepo.Object);
controller.ModelState.AddModelError("error", "some error");
// act
var result = controller.Put(id: 0, updatedTransaction: null);
// assert
Assert.IsType<BadRequestObjectResult>(result);
}
[Fact]
public void Put_ReturnsNotFoundObjectResult_GivenNonexistentTransactionId()
{
// arrange
var nonExistentTransactionId = 999;
var updatedTransaction = new Transaction();
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.TryUpdate(nonExistentTransactionId, updatedTransaction))
.Returns(false);
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Put(nonExistentTransactionId, updatedTransaction);
// assert
Assert.IsType<NotFoundObjectResult>(result);
}
[Fact]
public void Put_ReturnsNoContentResult_WhenUpdateOfTransactionWasSuccessful()
{
// arrange
var existentTransactionId = 42;
var updatedTransaction = new Transaction();
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.TryUpdate(existentTransactionId, updatedTransaction))
.Returns(true);
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Put(existentTransactionId, updatedTransaction);
// assert
Assert.IsType<NoContentResult>(result);
}
[Fact]
public void Delete_ReturnsNotFoundObjectResult_GivenNonexistentTransactionId()
{
// arrange
var nonExistentTransactionId = 999;
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.TryDelete(nonExistentTransactionId))
.Returns(false);
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Delete(nonExistentTransactionId);
// assert
Assert.IsType<NotFoundObjectResult>(result);
}
[Fact]
public void Delete_ReturnsNoContentResult_WhenUpdateOfTransactionWasSuccessful()
{
// arrange
var existentTransactionId = 42;
var mockRepo = new Mock<ITransactionRepository>();
mockRepo.Setup(repo => repo.TryDelete(existentTransactionId))
.Returns(true);
var controller = new TransactionsController(mockRepo.Object);
// act
var result = controller.Delete(existentTransactionId);
// assert
Assert.IsType<NoContentResult>(result);
}
private Transaction GetTestTransaction()
{
return new Transaction { Amount = 20 };
}
private IEnumerable<Transaction> GetTestTransactions()
{
/*var transactions = new List<Transaction>
{
new Transaction()
{
AccountId = 1,
Amount = 5,
Date = new DateTime(2016, 7, 2).ToFileTimeUtc(),
Notes = "a remark",
Tags = { "foo", "bar" },
TypeId = 1
},
new Transaction()
{
AccountId = 1,
Amount = 5,
Date = new DateTime(2016, 7, 2).ToFileTimeUtc(),
Notes = "a remark",
Tags = { "foo", "bar" },
TypeId = 1
}
};*/
return new List<Transaction>
{
new Transaction(),
new Transaction()
};
//return transactions;
}
}
}
| |
// 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.Globalization;
using System.Text;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
internal sealed class UserStringBuilder
{
private bool fHadUndisplayableStringInError;
private bool m_buildingInProgress;
private GlobalSymbolContext m_globalSymbols;
private StringBuilder m_strBuilder;
public UserStringBuilder(
GlobalSymbolContext globalSymbols)
{
Debug.Assert(globalSymbols != null);
fHadUndisplayableStringInError = false;
m_buildingInProgress = false;
m_globalSymbols = globalSymbols;
}
private void BeginString()
{
Debug.Assert(!m_buildingInProgress);
m_buildingInProgress = true;
m_strBuilder = new StringBuilder();
}
private void EndString(out string s)
{
Debug.Assert(m_buildingInProgress);
m_buildingInProgress = false;
s = m_strBuilder.ToString();
m_strBuilder = null;
}
public bool HadUndisplayableString()
{
return fHadUndisplayableStringInError;
}
public void ResetUndisplayableStringFlag()
{
fHadUndisplayableStringInError = false;
}
private void ErrSK(out string psz, SYMKIND sk)
{
MessageID id;
switch (sk)
{
case SYMKIND.SK_MethodSymbol:
id = MessageID.SK_METHOD;
break;
case SYMKIND.SK_AggregateSymbol:
id = MessageID.SK_CLASS;
break;
case SYMKIND.SK_NamespaceSymbol:
id = MessageID.SK_NAMESPACE;
break;
case SYMKIND.SK_FieldSymbol:
id = MessageID.SK_FIELD;
break;
case SYMKIND.SK_LocalVariableSymbol:
id = MessageID.SK_VARIABLE;
break;
case SYMKIND.SK_PropertySymbol:
id = MessageID.SK_PROPERTY;
break;
case SYMKIND.SK_EventSymbol:
id = MessageID.SK_EVENT;
break;
case SYMKIND.SK_TypeParameterSymbol:
id = MessageID.SK_TYVAR;
break;
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
Debug.Assert(false, "Illegal sk");
id = MessageID.SK_ALIAS;
break;
default:
Debug.Assert(false, "impossible sk");
id = MessageID.SK_UNKNOWN;
break;
}
ErrId(out psz, id);
}
/*
* Create a fill-in string describing a parameter list.
* Does NOT include ()
*/
private void ErrAppendParamList(TypeArray @params, bool isVarargs, bool isParamArray)
{
if (null == @params)
return;
for (int i = 0; i < @params.Count; i++)
{
if (i > 0)
{
ErrAppendString(", ");
}
if (isParamArray && i == @params.Count - 1)
{
ErrAppendString("params ");
}
// parameter type name
ErrAppendType(@params[i], null);
}
if (isVarargs)
{
if (@params.Count != 0)
{
ErrAppendString(", ");
}
ErrAppendString("...");
}
}
private void ErrAppendString(string str)
{
m_strBuilder.Append(str);
}
private void ErrAppendChar(char ch)
{
m_strBuilder.Append(ch);
}
private void ErrAppendPrintf(string format, params object[] args)
{
ErrAppendString(string.Format(CultureInfo.InvariantCulture, format, args));
}
private void ErrAppendName(Name name)
{
CheckDisplayableName(name);
if (name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
ErrAppendString("this");
}
else
{
ErrAppendString(name.Text);
}
}
private void ErrAppendMethodParentSym(MethodSymbol sym, SubstContext pcxt, out TypeArray substMethTyParams)
{
substMethTyParams = null;
ErrAppendParentSym(sym, pcxt);
}
private void ErrAppendParentSym(Symbol sym, SubstContext pctx)
{
ErrAppendParentCore(sym.parent, pctx);
}
private void ErrAppendParentType(CType pType, SubstContext pctx)
{
if (pType.IsErrorType())
{
if (pType.AsErrorType().HasTypeParent())
{
ErrAppendType(pType.AsErrorType().GetTypeParent(), null);
ErrAppendChar('.');
}
else
{
ErrAppendParentCore(pType.AsErrorType().GetNSParent(), pctx);
}
}
else if (pType.IsAggregateType())
{
ErrAppendParentCore(pType.AsAggregateType().GetOwningAggregate(), pctx);
}
else if (pType.GetBaseOrParameterOrElementType() != null)
{
ErrAppendType(pType.GetBaseOrParameterOrElementType(), null);
ErrAppendChar('.');
}
}
private void ErrAppendParentCore(Symbol parent, SubstContext pctx)
{
if (null == parent)
return;
if (parent == getBSymmgr().GetRootNS())
return;
if (pctx != null && !pctx.FNop() && parent.IsAggregateSymbol() && 0 != parent.AsAggregateSymbol().GetTypeVarsAll().Count)
{
CType pType = GetTypeManager().SubstType(parent.AsAggregateSymbol().getThisType(), pctx);
ErrAppendType(pType, null);
}
else
{
ErrAppendSym(parent, null);
}
ErrAppendChar('.');
}
private void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx, bool forClass)
{
if (@params != null && @params.Count != 0)
{
ErrAppendChar('<');
ErrAppendType(@params[0], pctx);
for (int i = 1; i < @params.Count; i++)
{
ErrAppendString(",");
ErrAppendType(@params[i], pctx);
}
ErrAppendChar('>');
}
}
private void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs)
{
if (meth.IsExpImpl() && meth.swtSlot)
{
ErrAppendParentSym(meth, pctx);
// Get the type args from the explicit impl type and substitute using pctx (if there is one).
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(meth.swtSlot.GetType(), pctx).AsAggregateType());
ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs);
// args already added
return;
}
if (meth.isPropertyAccessor())
{
PropertySymbol prop = meth.getProperty();
// this includes the parent class
ErrAppendSym(prop, pctx);
// add accessor name
if (prop.methGet == meth)
{
ErrAppendString(".get");
}
else
{
Debug.Assert(meth == prop.methSet);
ErrAppendString(".set");
}
// args already added
return;
}
if (meth.isEventAccessor())
{
EventSymbol @event = meth.getEvent();
// this includes the parent class
ErrAppendSym(@event, pctx);
// add accessor name
if (@event.methAdd == meth)
{
ErrAppendString(".add");
}
else
{
Debug.Assert(meth == @event.methRemove);
ErrAppendString(".remove");
}
// args already added
return;
}
TypeArray replacementTypeArray = null;
ErrAppendMethodParentSym(meth, pctx, out replacementTypeArray);
if (meth.IsConstructor())
{
// Use the name of the parent class instead of the name "<ctor>".
ErrAppendName(meth.getClass().name);
}
else if (meth.IsDestructor())
{
// Use the name of the parent class instead of the name "Finalize".
ErrAppendChar('~');
ErrAppendName(meth.getClass().name);
}
else if (meth.isConversionOperator())
{
// implicit/explicit
ErrAppendString(meth.isImplicit() ? "implicit" : "explicit");
ErrAppendString(" operator ");
// destination type name
ErrAppendType(meth.RetType, pctx);
}
else if (meth.isOperator)
{
// handle user defined operators
// map from CLS predefined names to "operator <X>"
ErrAppendString("operator ");
//
// This is kinda slow, but the alternative is to add bits to methsym.
//
string operatorName;
OperatorKind op = Operators.OperatorOfMethodName(meth.name);
if (Operators.HasDisplayName(op))
{
operatorName = Operators.GetDisplayName(op);
}
else
{
//
// either equals or compare
//
if (meth.name == NameManager.GetPredefinedName(PredefinedName.PN_OPEQUALS))
{
operatorName = "equals";
}
else
{
Debug.Assert(meth.name == NameManager.GetPredefinedName(PredefinedName.PN_OPCOMPARE));
operatorName = "compare";
}
}
ErrAppendString(operatorName);
}
else if (meth.IsExpImpl())
{
if (meth.errExpImpl != null)
ErrAppendType(meth.errExpImpl, pctx, fArgs);
}
else
{
// regular method
ErrAppendName(meth.name);
}
if (null == replacementTypeArray)
{
ErrAppendTypeParameters(meth.typeVars, pctx, false);
}
if (fArgs)
{
// append argument types
ErrAppendChar('(');
if (!meth.computeCurrentBogusState())
{
ErrAppendParamList(GetTypeManager().SubstTypeArray(meth.Params, pctx), meth.isVarargs, meth.isParamArray);
}
ErrAppendChar(')');
}
}
private void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx)
{
ErrAppendString("this[");
ErrAppendParamList(GetTypeManager().SubstTypeArray(indexer.Params, pctx), false, indexer.isParamArray);
ErrAppendChar(']');
}
private void ErrAppendProperty(PropertySymbol prop, SubstContext pctx)
{
ErrAppendParentSym(prop, pctx);
if (prop.IsExpImpl() && prop.swtSlot.Sym != null)
{
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(prop.swtSlot.GetType(), pctx).AsAggregateType());
ErrAppendSym(prop.swtSlot.Sym, ctx);
}
else if (prop.IsExpImpl())
{
if (prop.errExpImpl != null)
ErrAppendType(prop.errExpImpl, pctx, false);
if (prop.isIndexer())
{
ErrAppendChar('.');
ErrAppendIndexer(prop.AsIndexerSymbol(), pctx);
}
}
else if (prop.isIndexer())
{
ErrAppendIndexer(prop.AsIndexerSymbol(), pctx);
}
else
{
ErrAppendName(prop.name);
}
}
private void ErrAppendEvent(EventSymbol @event, SubstContext pctx)
{
}
private void ErrAppendId(MessageID id)
{
string str;
ErrId(out str, id);
ErrAppendString(str);
}
/*
* Create a fill-in string describing a symbol.
*/
private void ErrAppendSym(Symbol sym, SubstContext pctx)
{
ErrAppendSym(sym, pctx, true);
}
private void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs)
{
switch (sym.getKind())
{
case SYMKIND.SK_AggregateDeclaration:
ErrAppendSym(sym.AsAggregateDeclaration().Agg(), pctx);
break;
case SYMKIND.SK_AggregateSymbol:
{
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(sym.AsAggregateSymbol());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else if (sym.AsAggregateSymbol().IsAnonymousType())
{
ErrAppendId(MessageID.AnonymousType);
break;
}
else
{
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
ErrAppendTypeParameters(sym.AsAggregateSymbol().GetTypeVars(), pctx, true);
}
break;
}
case SYMKIND.SK_MethodSymbol:
ErrAppendMethod(sym.AsMethodSymbol(), pctx, fArgs);
break;
case SYMKIND.SK_PropertySymbol:
ErrAppendProperty(sym.AsPropertySymbol(), pctx);
break;
case SYMKIND.SK_EventSymbol:
ErrAppendEvent(sym.AsEventSymbol(), pctx);
break;
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
case SYMKIND.SK_NamespaceSymbol:
if (sym == getBSymmgr().GetRootNS())
{
ErrAppendId(MessageID.GlobalNamespace);
}
else
{
ErrAppendParentSym(sym, null);
ErrAppendName(sym.name);
}
break;
case SYMKIND.SK_FieldSymbol:
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
break;
case SYMKIND.SK_TypeParameterSymbol:
if (null == sym.name)
{
// It's a standard type variable.
if (sym.AsTypeParameterSymbol().IsMethodTypeParameter())
ErrAppendChar('!');
ErrAppendChar('!');
ErrAppendPrintf("{0}", sym.AsTypeParameterSymbol().GetIndexInTotalParameters());
}
else
ErrAppendName(sym.name);
break;
case SYMKIND.SK_LocalVariableSymbol:
// Generate symbol name.
ErrAppendName(sym.name);
break;
case SYMKIND.SK_Scope:
case SYMKIND.SK_LambdaScope:
default:
// Shouldn't happen.
Debug.Assert(false, $"Bad symbol kind: {sym.getKind()}");
break;
}
}
private void ErrAppendType(CType pType, SubstContext pCtx)
{
ErrAppendType(pType, pCtx, true);
}
private void ErrAppendType(CType pType, SubstContext pctx, bool fArgs)
{
if (pctx != null)
{
if (!pctx.FNop())
{
pType = GetTypeManager().SubstType(pType, pctx);
}
// We shouldn't use the SubstContext again so set it to NULL.
pctx = null;
}
switch (pType.GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateType pAggType = pType.AsAggregateType();
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(pAggType.getAggregate());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else if (pAggType.getAggregate().IsAnonymousType())
{
ErrAppendPrintf("AnonymousType#{0}", GetTypeID(pAggType));
break;
}
else
{
if (pAggType.outerType != null)
{
ErrAppendType(pAggType.outerType, pctx);
ErrAppendChar('.');
}
else
{
// In a namespace.
ErrAppendParentSym(pAggType.getAggregate(), pctx);
}
ErrAppendName(pAggType.getAggregate().name);
}
ErrAppendTypeParameters(pAggType.GetTypeArgsThis(), pctx, true);
break;
}
case TypeKind.TK_TypeParameterType:
if (null == pType.GetName())
{
// It's a standard type variable.
if (pType.AsTypeParameterType().IsMethodTypeParameter())
{
ErrAppendChar('!');
}
ErrAppendChar('!');
ErrAppendPrintf("{0}", pType.AsTypeParameterType().GetIndexInTotalParameters());
}
else
{
ErrAppendName(pType.GetName());
}
break;
case TypeKind.TK_ErrorType:
if (pType.AsErrorType().HasParent())
{
Debug.Assert(pType.AsErrorType().nameText != null && pType.AsErrorType().typeArgs != null);
ErrAppendParentType(pType, pctx);
ErrAppendName(pType.AsErrorType().nameText);
ErrAppendTypeParameters(pType.AsErrorType().typeArgs, pctx, true);
}
else
{
// Load the string "<error>".
Debug.Assert(null == pType.AsErrorType().typeArgs);
ErrAppendId(MessageID.ERRORSYM);
}
break;
case TypeKind.TK_NullType:
// Load the string "<null>".
ErrAppendId(MessageID.NULL);
break;
case TypeKind.TK_OpenTypePlaceholderType:
// Leave blank.
break;
case TypeKind.TK_BoundLambdaType:
ErrAppendId(MessageID.AnonMethod);
break;
case TypeKind.TK_UnboundLambdaType:
ErrAppendId(MessageID.Lambda);
break;
case TypeKind.TK_MethodGroupType:
ErrAppendId(MessageID.MethodGroup);
break;
case TypeKind.TK_ArgumentListType:
ErrAppendString(TokenFacts.GetText(TokenKind.ArgList));
break;
case TypeKind.TK_ArrayType:
{
CType elementType = pType.AsArrayType().GetBaseElementType();
if (null == elementType)
{
Debug.Assert(false, "No element type");
break;
}
ErrAppendType(elementType, pctx);
for (elementType = pType;
elementType != null && elementType.IsArrayType();
elementType = elementType.AsArrayType().GetElementType())
{
int rank = elementType.AsArrayType().rank;
// Add [] with (rank-1) commas inside
ErrAppendChar('[');
// known rank.
if (rank == 1)
{
if (!elementType.AsArrayType().IsSZArray)
{
ErrAppendChar('*');
}
}
else
{
for (int i = rank; i > 1; --i)
{
ErrAppendChar(',');
}
}
ErrAppendChar(']');
}
break;
}
case TypeKind.TK_VoidType:
ErrAppendName(GetNameManager().Lookup(TokenFacts.GetText(TokenKind.Void)));
break;
case TypeKind.TK_ParameterModifierType:
// add ref or out
ErrAppendString(pType.AsParameterModifierType().isOut ? "out " : "ref ");
// add base type name
ErrAppendType(pType.AsParameterModifierType().GetParameterType(), pctx);
break;
case TypeKind.TK_PointerType:
// Generate the base type.
ErrAppendType(pType.AsPointerType().GetReferentType(), pctx);
{
// add the trailing *
ErrAppendChar('*');
}
break;
case TypeKind.TK_NullableType:
ErrAppendType(pType.AsNullableType().GetUnderlyingType(), pctx);
ErrAppendChar('?');
break;
case TypeKind.TK_NaturalIntegerType:
default:
// Shouldn't happen.
Debug.Assert(false, "Bad type kind");
break;
}
}
// Returns true if the argument could be converted to a string.
public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings)
{
fUserStrings = false;
psz = null;
bool result = true;
switch (parg.eak)
{
case ErrArgKind.Ids:
ErrId(out psz, parg.ids);
break;
case ErrArgKind.SymKind:
ErrSK(out psz, parg.sk);
break;
case ErrArgKind.Type:
BeginString();
ErrAppendType(parg.pType, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Sym:
BeginString();
ErrAppendSym(parg.sym, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Name:
if (parg.name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
psz = "this";
}
else
{
psz = parg.name.Text;
}
break;
case ErrArgKind.Str:
psz = parg.psz;
break;
case ErrArgKind.SymWithType:
{
SubstContext ctx = new SubstContext(parg.swtMemo.ats, null);
BeginString();
ErrAppendSym(parg.swtMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
case ErrArgKind.MethWithInst:
{
SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs);
BeginString();
ErrAppendSym(parg.mpwiMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
default:
result = false;
break;
}
return result;
}
private bool IsDisplayableName(Name name)
{
return name != NameManager.GetPredefinedName(PredefinedName.PN_MISSING);
}
private void CheckDisplayableName(Name name)
{
if (!IsDisplayableName(name))
{
fHadUndisplayableStringInError = true;
}
}
private NameManager GetNameManager()
{
return m_globalSymbols.GetNameManager();
}
private TypeManager GetTypeManager()
{
return m_globalSymbols.GetTypes();
}
private BSYMMGR getBSymmgr()
{
return m_globalSymbols.GetGlobalSymbols();
}
private int GetTypeID(CType type)
{
return 0;
}
private void ErrId(out string s, MessageID id)
{
s = ErrorFacts.GetMessage(id);
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using System.Collections.Generic;
//using Alica.Reasoner;
//using Al=Alica;
using AutoDiff;
namespace Alica.Reasoner.IntervalPropagation
{
public class ResetIntervals : ITermVisitor<bool>
{
public ResetIntervals() {
}
public bool Visit(Constant constant) {
constant.Parents.Clear();
UpdateInterval(constant,constant.Value,constant.Value);
return true;
}
public bool Visit(Zero zero) {
zero.Parents.Clear();
UpdateInterval(zero,0,0);
return true;
}
public bool Visit(ConstPower intPower) {
intPower.Parents.Clear();
intPower.Base.Accept(this);
if (intPower.Exponent == 0) {
UpdateInterval(intPower,0,0);
return true;
}
double e = Math.Round(intPower.Exponent);
if(intPower.Exponent == e && ((int)e)%2 == 0) {
UpdateInterval(intPower,0,Double.PositiveInfinity);
return true;
}
UpdateInterval(intPower,Double.NegativeInfinity,Double.PositiveInfinity);
return false;
}
public bool Visit(TermPower tp) {
tp.Parents.Clear();
tp.Base.Accept(this);
tp.Exponent.Accept(this);
UpdateInterval(tp,Double.NegativeInfinity,Double.PositiveInfinity);
return false;
}
public bool Visit(Gp gp) {
throw new NotImplementedException();
return false;
}
public bool Visit(Product product) {
product.Parents.Clear();
UpdateInterval(product,Double.NegativeInfinity,Double.PositiveInfinity);
product.Left.Accept(this);
product.Right.Accept(this);
return false;
}
public bool Visit(Sigmoid sigmoid) {
sigmoid.Parents.Clear();
sigmoid.Arg.Accept(this);
sigmoid.Mid.Accept(this);
UpdateInterval(sigmoid,0,1);
return true;
}
public bool Visit(LinSigmoid sigmoid) {
sigmoid.Parents.Clear();
sigmoid.Arg.Accept(this);
UpdateInterval(sigmoid,0,1);
return true;
}
public bool Visit(LTConstraint constraint) {
constraint.Parents.Clear();
constraint.Left.Accept(this);
constraint.Right.Accept(this);
UpdateInterval(constraint,Double.NegativeInfinity,1);
return true;
}
public bool Visit(LTEConstraint constraint) {
constraint.Parents.Clear();
constraint.Left.Accept(this);
constraint.Right.Accept(this);
UpdateInterval(constraint,Double.NegativeInfinity,1);
return true;
}
public bool Visit(Min min) {
min.Parents.Clear();
min.Left.Accept(this);
min.Right.Accept(this);
UpdateInterval(min,Double.NegativeInfinity,Double.PositiveInfinity);
return true;
}
public bool Visit(Reification reif) {
reif.Parents.Clear();
reif.Condition.Accept(this);
UpdateInterval(reif,reif.MinVal,reif.MaxVal);
return true;
}
public bool Visit(Max max) {
max.Parents.Clear();
max.Left.Accept(this);
max.Right.Accept(this);
UpdateInterval(max,Double.NegativeInfinity,Double.PositiveInfinity);
return true;
}
public bool Visit(And and) {
and.Parents.Clear();
and.Left.Accept(this);
and.Right.Accept(this);
UpdateInterval(and,Double.NegativeInfinity,1);
//UpdateInterval(and,1,1); //enforce the purely conjunctive problem
return true;
}
public bool Visit(Or or) {
or.Parents.Clear();
or.Left.Accept(this);
or.Right.Accept(this);
UpdateInterval(or,Double.NegativeInfinity,1);
return true;
}
public bool Visit(ConstraintUtility cu) {
cu.Parents.Clear();
cu.Constraint.Accept(this);
cu.Utility.Accept(this);
UpdateInterval(cu,1,Double.PositiveInfinity);
return true;
}
public bool Visit(Sum sum) {
sum.Parents.Clear();
foreach(Term t in sum.Terms) t.Accept(this);
UpdateInterval(sum,Double.NegativeInfinity,Double.PositiveInfinity);
return true;
}
public bool Visit(AutoDiff.Variable variable) {
variable.Parents.Clear();
UpdateInterval(variable,variable.GlobalMin,variable.GlobalMax);
return true;
}
public bool Visit(Log log) {
log.Parents.Clear();
log.Arg.Accept(this);
UpdateInterval(log,Double.NegativeInfinity,Double.PositiveInfinity);
return true;
}
public bool Visit(Sin sin) {
sin.Parents.Clear();
sin.Arg.Accept(this);
UpdateInterval(sin,-1,1);
return true;
}
public bool Visit(Cos cos) {
cos.Parents.Clear();
cos.Arg.Accept(this);
UpdateInterval(cos,-1,1);
return true;
}
public bool Visit(Abs abs) {
abs.Parents.Clear();
abs.Arg.Accept(this);
UpdateInterval(abs,0,Double.PositiveInfinity);
return true;
}
public bool Visit(Exp exp) {
exp.Parents.Clear();
exp.Arg.Accept(this);
UpdateInterval(exp,0,Double.PositiveInfinity);
return true;
}
public bool Visit(Atan2 atan2) {
atan2.Parents.Clear();
atan2.Left.Accept(this);
atan2.Right.Accept(this);
UpdateInterval(atan2,-Math.PI,Math.PI);
return true;
}
private void UpdateInterval(Term t, double min, double max) {
t.Min = min;
t.Max = max;
return;
}
}
}
| |
#region Using Directives
#endregion
namespace SPALM.SPSF.Library.Actions
{
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
using EnvDTE;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
/// <summary>
/// Exports a given
/// </summary>
[ServiceDependency(typeof(DTE))]
public class WebServiceGenerateWSDL : ConfigurableAction
{
private ProjectItem _WebServiceFile = null;
[Input(Required = true)]
public ProjectItem WebServiceFile
{
get { return _WebServiceFile; }
set { _WebServiceFile = value; }
}
public override void Execute()
{
DTE service = (DTE)this.GetService(typeof(DTE));
Helpers.ShowProgress(service, "Generating WSDL...", 10);
string defaultIISAPP = Helpers.GetDefaultIISWebApp();
string workingDirectory = Path.Combine(Path.GetTempPath(), "SPALMWSDL" + Guid.NewGuid().ToString());
Directory.CreateDirectory(workingDirectory);
ProjectItem asmxfileParentFolder = (ProjectItem)WebServiceFile.ProjectItems.Parent;
//build if necessary
Helpers.WriteToOutputWindow(service, "Compile to get actual version of dll");
Project project = WebServiceFile.ContainingProject;
service.Solution.SolutionBuild.BuildProject(service.Solution.SolutionBuild.ActiveConfiguration.Name, project.UniqueName, true);
//get the asmx file and copy to /_layouts
string projectpath = Helpers.GetFullPathOfProjectItem(project);
string projectfolder = Path.GetDirectoryName(projectpath);
bool ASMXFileExisted = false;
string fullasmxtarget = "";
string asmxfilename = WebServiceFile.Name;
string asmxfilenamewithoutext = asmxfilename.Substring(0, asmxfilename.LastIndexOf("."));
string asmxfullPath = Helpers.GetFullPathOfProjectItem(WebServiceFile);
if (File.Exists(asmxfullPath))
{
string targetfolder = Helpers.GetSharePointHive() + @"\TEMPLATE\LAYOUTS";
Helpers.WriteToOutputWindow(service, "Copying asmx file to _layouts folder");
fullasmxtarget = Path.Combine(targetfolder, asmxfilename);
if (File.Exists(fullasmxtarget))
{
ASMXFileExisted = true;
}
File.Copy(asmxfullPath, fullasmxtarget, true);
}
//add the assembly to the gac
string OutputFileName = project.Properties.Item("OutputFileName").Value.ToString();
string OutputPath = project.ConfigurationManager.ActiveConfiguration.Properties.Item("OutputPath").Value.ToString();
string assemblypath = Path.Combine(Path.Combine(projectfolder, OutputPath), OutputFileName);
if (!File.Exists(assemblypath))
{
//check GAC folder of project
assemblypath = Path.Combine(projectfolder, "GAC");
if (Directory.Exists(assemblypath))
{
assemblypath = Path.Combine(assemblypath, OutputFileName);
}
}
if (!File.Exists(assemblypath))
{
string message = "Warning: No assembly in project found";
Helpers.LogMessage(service, this, message);
MessageBox.Show(message);
}
if (File.Exists(assemblypath))
{
string gacutilpath = Helpers.GetGACUtil(service);
//sear
if (File.Exists(gacutilpath))
{
Helpers.ShowProgress(service, "Generating WSDL...", 30);
Helpers.WriteToOutputWindow(service, "Install dll in GAC", false);
Helpers.RunProcess(service, gacutilpath, "/if " + assemblypath, true, workingDirectory, false);
Helpers.WriteToOutputWindow(service, "IISReset to force reload of dll", false);
Helpers.ShowProgress(service, "Generating WSDL...", 60);
Helpers.LogMessage(service, this, "IISRESET...");
Helpers.RunProcess(service, "iisreset", "", true, workingDirectory, false);
}
else
{
string message =
"GACUTIL.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442";
Helpers.LogMessage(service, this, message);
MessageBox.Show(message);
}
}
//call disco.exe
Helpers.LogMessage(service, this, "Getting path to disco.exe...");
string discopath = Helpers.GetDiscoPath();
if (discopath != "")
{
if (!defaultIISAPP.StartsWith("http:"))
{
defaultIISAPP = "http://" + defaultIISAPP;
}
Helpers.ShowProgress(service, "Generating WSDL...", 80);
string discoargument = " " + defaultIISAPP + "/_layouts" + Helpers.GetVersionedFolder(service) + "/" + asmxfilename;
Helpers.LogMessage(service, this, "Ping server...");
DeploymentHelpers.PingServer(service, discoargument, 20000);
Helpers.LogMessage(service, this, "Running disco.exe...");
Helpers.RunProcess(service, discopath, discoargument, true, workingDirectory, false);
}
else
{
string message = "Disco.exe not found on your system.\nPlease install .net or Windows SDK.\ni.e. Windows SDK 7.1 http://www.microsoft.com/download/en/details.aspx?id=8442";
Helpers.LogMessage(service, this, message);
MessageBox.Show(message);
}
//adding results to the project
//WebService1.disco
string finalwsdlpath = "";
string finaldiscopath = "";
string[] wsdls = Directory.GetFiles(workingDirectory, "*.wsdl");
if (wsdls.Length > 0)
{
finalwsdlpath = wsdls[0];
}
string[] discos = Directory.GetFiles(workingDirectory, "*.disco");
if (discos.Length > 0)
{
finaldiscopath = discos[0];
}
if (File.Exists(finalwsdlpath) && File.Exists(finaldiscopath))
{
string SharePointVersion = Helpers.GetInstalledSharePointVersion();
//replace text in the files
/*To register namespaces of the Windows SharePoint Services object model, open both the .disco and .wsdl files and replace the opening XML processing instruction -- <?xml version="1.0" encoding="utf-8"?> -- with instructions such as the following:
<%@ Page Language="C#" Inherits="System.Web.UI.Page" %>
<%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Import Namespace="Microsoft.SharePoint.Utilities" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<% Response.ContentType = "text/xml"; %>
*/
Helpers.ShowProgress(service, "Generating WSDL...", 90);
StringBuilder wsdlreplaced = new StringBuilder();
TextReader wsdlreader = new StreamReader(finalwsdlpath);
string input = null;
while ((input = wsdlreader.ReadLine()) != null)
{
if (input.TrimStart(null).StartsWith("<?xml version="))
{
wsdlreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>");
wsdlreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>");
wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> ");
wsdlreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>");
wsdlreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>");
}
else if (input.TrimStart(null).StartsWith("<soap:address"))
{
wsdlreplaced.AppendLine("<soap:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />");
}
else if (input.TrimStart(null).StartsWith("<soap12:address"))
{
wsdlreplaced.AppendLine("<soap12:address location=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> />");
}
else
{
wsdlreplaced.AppendLine(input);
}
}
wsdlreader.Close();
TextWriter wsdlwriter = new StreamWriter(finalwsdlpath);
wsdlwriter.Write(wsdlreplaced.ToString());
wsdlwriter.Close();
StringBuilder discoreplaced = new StringBuilder();
TextReader discoreader = new StreamReader(finaldiscopath);
string discoinput = null;
while ((discoinput = discoreader.ReadLine()) != null)
{
if (discoinput.TrimStart(null).StartsWith("<?xml version="))
{
discoreplaced.AppendLine("<%@ Page Language=\"C#\" Inherits=\"System.Web.UI.Page\" %>");
discoreplaced.AppendLine("<%@ Assembly Name=\"Microsoft.SharePoint, Version=" + SharePointVersion + ".0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>");
discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint.Utilities\" %> ");
discoreplaced.AppendLine("<%@ Import Namespace=\"Microsoft.SharePoint\" %>");
discoreplaced.AppendLine("<% Response.ContentType = \"text/xml\"; %>");
}
else if (discoinput.TrimStart(null).StartsWith("<contractRef"))
{
discoreplaced.AppendLine("<contractRef ref=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request) + \"?wsdl\"),Response.Output); %> docRef=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns=\"http://schemas.xmlsoap.org/disco/scl/\" />");
}
else if (discoinput.TrimStart(null).StartsWith("<soap address="))
{
//before
//<soap address="http://tfsrtm08/_layouts/WebService1.asmx" xmlns:q1="http://SMC.Supernet.Web.WebServices/" binding="q1:WebService1Soap" xmlns="http://schemas.xmlsoap.org/disco/soap/" />
//replaced
//<soap address=<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %> xmlns:q1="http://tempuri.org/" binding="q1:HelloWorld" xmlns="http://schemas.xmlsoap.org/disco/soap/" />
//we replace the field adress
string originalstring = discoinput;
string beforeaddress = originalstring.Substring(0, originalstring.IndexOf(" address=") + 9);
string afteraddress = originalstring.Substring(originalstring.IndexOf("\"", originalstring.IndexOf(" address=") + 11));
//skip the quot
afteraddress = afteraddress.Substring(1);
discoreplaced.AppendLine(beforeaddress + "<% SPHttpUtility.AddQuote(SPHttpUtility.HtmlEncode(SPWeb.OriginalBaseUrl(Request)),Response.Output); %>" + afteraddress);
}
else
{
discoreplaced.AppendLine(discoinput);
}
}
discoreader.Close();
TextWriter discowriter = new StreamWriter(finaldiscopath);
discowriter.Write(discoreplaced.ToString());
discowriter.Close();
//files renaming needed
//WebService.wsdl -> WebServiceWSDL.aspx
//WebService.disco -> WebServiceDisco.aspx
string renamedwsdlpath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "WSDL.aspx");
string renameddiscopath = Path.Combine(workingDirectory, asmxfilenamewithoutext + "Disco.aspx");
File.Copy(finalwsdlpath, renamedwsdlpath);
File.Copy(finaldiscopath, renameddiscopath);
//add the files to the project
ProjectItem wsdlItem = Helpers.AddFile(asmxfileParentFolder, renamedwsdlpath);
ProjectItem discoItem = Helpers.AddFile(asmxfileParentFolder, renameddiscopath);
//set the deployment target of the files to the same as the parent
if (Helpers2.IsSharePointVSTemplate(service, project))
{
Helpers2.CopyDeploymentPath(WebServiceFile, wsdlItem);
Helpers2.CopyDeploymentPath(WebServiceFile, discoItem);
}
}
else
{
string message = "Created WSDL and DISCO files not found. Creation failed.";
Helpers.LogMessage(service, this, message);
MessageBox.Show(message);
}
try
{
//delete temp folder
Directory.Delete(workingDirectory, true);
//clean up everything what we have copied to the layouts folder
if (ASMXFileExisted)
{
File.Delete(fullasmxtarget);
}
}
catch (Exception)
{
}
Helpers.HideProgress(service);
}
/// <summary>
/// Removes the previously added reference, if it was created
/// </summary>
public override void Undo()
{
}
}
}
| |
//
// Author:
// Jb Evain ([email protected])
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Zenject.ReflectionBaking.Mono.Collections.Generic;
using SR = System.Reflection;
using Zenject.ReflectionBaking.Mono.Cecil.Metadata;
namespace Zenject.ReflectionBaking.Mono.Cecil {
enum ImportGenericKind {
Definition,
Open,
}
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != candidate.Name)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
}
class MetadataImporter {
readonly ModuleDefinition module;
public MetadataImporter (ModuleDefinition module)
{
this.module = module;
}
#if !CF
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
{ typeof (TypedReference), ElementType.TypedByRef },
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
public TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
public TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type.Assembly),
type.IsValueType);
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType)
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
#if !SILVERLIGHT
return type.IsNested;
#else
return type.DeclaringType != null;
#endif
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType)
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod != null)
return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition);
if (type.DeclaringType != null)
return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition);
throw new InvalidOperationException();
}
private static string NormalizedFullName (Type type)
{
if (IsNestedType (type))
return NormalizedFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType && !type.IsGenericTypeDefinition;
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
AssemblyNameReference ImportScope (SR.Assembly assembly)
{
AssemblyNameReference scope;
#if !SILVERLIGHT
var name = assembly.GetName ();
if (TryGetAssemblyNameReference (name, out scope))
return scope;
scope = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.CultureInfo.Name,
PublicKeyToken = name.GetPublicKeyToken (),
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
};
module.AssemblyReferences.Add (scope);
return scope;
#else
var name = AssemblyNameReference.Parse (assembly.FullName);
if (TryGetAssemblyNameReference (name, out scope))
return scope;
module.AssemblyReferences.Add (name);
return name;
#endif
}
#if !SILVERLIGHT
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
#endif
public FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
#if !SILVERLIGHT
return field.Module.ResolveField (field.MetadataToken);
#else
return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name,
SR.BindingFlags.Public
| SR.BindingFlags.NonPublic
| (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance));
#endif
}
public MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = method.Module.ResolveMethod (method.MetadataToken);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
#endif
public TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type.Scope),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
return reference;
}
IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportAssemblyName ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
{
AssemblyNameReference reference;
if (TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name_reference.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
public FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
public MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var reference_parameters = reference.Parameters;
var parameters = method.Parameters;
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
}
}
| |
namespace Kemel.Tools.Orm
{
partial class FrmProviderSettings
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FrmProviderSettings));
this.kryptonPanel = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryptonHeaderGroup1 = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup();
this.rdbNewQuery = new System.Windows.Forms.RadioButton();
this.rdbOldQuery = new System.Windows.Forms.RadioButton();
this.lblStatus = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.btnSave = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.nudConnectionTimeout = new ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown();
this.btnTest = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.txtOrmNameSpace = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.txtPort = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.txtPassword = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.txtLogin = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.txtDataSource = new ComponentFactory.Krypton.Toolkit.KryptonTextBox();
this.lblConnectionTimeOut = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel1 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryptonLabel2 = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.lblPort = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.lblPassword = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.lblLogin = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.lblDataSource = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.cboLanguage = new ComponentFactory.Krypton.Toolkit.KryptonComboBox();
this.cboDataBase = new ComponentFactory.Krypton.Toolkit.KryptonComboBox();
this.cboProviderType = new ComponentFactory.Krypton.Toolkit.KryptonComboBox();
this.lblDataBase = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.lblProviderType = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel)).BeginInit();
this.kryptonPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).BeginInit();
this.kryptonHeaderGroup1.Panel.SuspendLayout();
this.kryptonHeaderGroup1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.cboLanguage)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cboDataBase)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.cboProviderType)).BeginInit();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// kryptonPanel
//
this.kryptonPanel.Controls.Add(this.kryptonHeaderGroup1);
this.kryptonPanel.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonPanel.Location = new System.Drawing.Point(0, 0);
this.kryptonPanel.Name = "kryptonPanel";
this.kryptonPanel.Size = new System.Drawing.Size(616, 382);
this.kryptonPanel.TabIndex = 0;
//
// kryptonHeaderGroup1
//
this.kryptonHeaderGroup1.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryptonHeaderGroup1.Location = new System.Drawing.Point(0, 0);
this.kryptonHeaderGroup1.Name = "kryptonHeaderGroup1";
//
// kryptonHeaderGroup1.Panel
//
this.kryptonHeaderGroup1.Panel.Controls.Add(this.groupBox1);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblStatus);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.label1);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.btnSave);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.nudConnectionTimeout);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.btnTest);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.txtOrmNameSpace);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.txtPort);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.txtPassword);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.txtLogin);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.txtDataSource);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblConnectionTimeOut);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonLabel1);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonLabel2);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblPort);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblPassword);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblLogin);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblDataSource);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.cboLanguage);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.cboDataBase);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.cboProviderType);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblDataBase);
this.kryptonHeaderGroup1.Panel.Controls.Add(this.lblProviderType);
this.kryptonHeaderGroup1.Size = new System.Drawing.Size(616, 382);
this.kryptonHeaderGroup1.TabIndex = 0;
this.kryptonHeaderGroup1.ValuesPrimary.Heading = "Settings";
this.kryptonHeaderGroup1.ValuesSecondary.Heading = "Provider Settings";
//
// rdbNewQuery
//
this.rdbNewQuery.AutoSize = true;
this.rdbNewQuery.BackColor = System.Drawing.SystemColors.Window;
this.rdbNewQuery.Location = new System.Drawing.Point(61, 19);
this.rdbNewQuery.Name = "rdbNewQuery";
this.rdbNewQuery.Size = new System.Drawing.Size(43, 17);
this.rdbNewQuery.TabIndex = 22;
this.rdbNewQuery.Text = "Yes";
this.rdbNewQuery.UseVisualStyleBackColor = false;
//
// rdbOldQuery
//
this.rdbOldQuery.AutoSize = true;
this.rdbOldQuery.BackColor = System.Drawing.SystemColors.Window;
this.rdbOldQuery.Checked = true;
this.rdbOldQuery.Location = new System.Drawing.Point(6, 19);
this.rdbOldQuery.Name = "rdbOldQuery";
this.rdbOldQuery.Size = new System.Drawing.Size(39, 17);
this.rdbOldQuery.TabIndex = 22;
this.rdbOldQuery.TabStop = true;
this.rdbOldQuery.Text = "No";
this.rdbOldQuery.UseVisualStyleBackColor = false;
//
// lblStatus
//
this.lblStatus.BackColor = System.Drawing.Color.Transparent;
this.lblStatus.Location = new System.Drawing.Point(55, 243);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(77, 13);
this.lblStatus.TabIndex = 10;
this.lblStatus.Text = "-";
this.lblStatus.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Location = new System.Drawing.Point(12, 243);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(40, 13);
this.label1.TabIndex = 9;
this.label1.Text = "Status:";
//
// btnSave
//
this.btnSave.Enabled = false;
this.btnSave.Location = new System.Drawing.Point(463, 270);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(130, 25);
this.btnSave.TabIndex = 21;
this.btnSave.Values.Text = "Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// nudConnectionTimeout
//
this.nudConnectionTimeout.Enabled = false;
this.nudConnectionTimeout.Increment = new decimal(new int[] {
10,
0,
0,
0});
this.nudConnectionTimeout.Location = new System.Drawing.Point(328, 31);
this.nudConnectionTimeout.Maximum = new decimal(new int[] {
10000,
0,
0,
0});
this.nudConnectionTimeout.Minimum = new decimal(new int[] {
10,
0,
0,
0});
this.nudConnectionTimeout.Name = "nudConnectionTimeout";
this.nudConnectionTimeout.Size = new System.Drawing.Size(120, 22);
this.nudConnectionTimeout.TabIndex = 14;
this.nudConnectionTimeout.Value = new decimal(new int[] {
120,
0,
0,
0});
//
// btnTest
//
this.btnTest.Location = new System.Drawing.Point(146, 213);
this.btnTest.Name = "btnTest";
this.btnTest.Size = new System.Drawing.Size(131, 25);
this.btnTest.TabIndex = 8;
this.btnTest.Values.Text = "Test Connection";
this.btnTest.Click += new System.EventHandler(this.btnTest_Click);
//
// txtOrmNameSpace
//
this.txtOrmNameSpace.Location = new System.Drawing.Point(327, 190);
this.txtOrmNameSpace.Name = "txtOrmNameSpace";
this.txtOrmNameSpace.Size = new System.Drawing.Size(266, 20);
this.txtOrmNameSpace.TabIndex = 20;
this.txtOrmNameSpace.Text = "Kemel.Orm";
//
// txtPort
//
this.txtPort.Enabled = false;
this.txtPort.Location = new System.Drawing.Point(327, 82);
this.txtPort.Name = "txtPort";
this.txtPort.Size = new System.Drawing.Size(266, 20);
this.txtPort.TabIndex = 16;
this.txtPort.Text = "1521";
//
// txtPassword
//
this.txtPassword.Location = new System.Drawing.Point(11, 187);
this.txtPassword.Name = "txtPassword";
this.txtPassword.PasswordChar = '*';
this.txtPassword.Size = new System.Drawing.Size(266, 20);
this.txtPassword.TabIndex = 7;
this.txtPassword.Text = "x!rsa5)f";
//
// txtLogin
//
this.txtLogin.Location = new System.Drawing.Point(11, 135);
this.txtLogin.Name = "txtLogin";
this.txtLogin.Size = new System.Drawing.Size(266, 20);
this.txtLogin.TabIndex = 5;
this.txtLogin.Text = "sa";
//
// txtDataSource
//
this.txtDataSource.Location = new System.Drawing.Point(11, 83);
this.txtDataSource.Name = "txtDataSource";
this.txtDataSource.Size = new System.Drawing.Size(266, 20);
this.txtDataSource.TabIndex = 3;
this.txtDataSource.Text = "vmsdigisql01\\dev";
//
// lblConnectionTimeOut
//
this.lblConnectionTimeOut.Location = new System.Drawing.Point(328, 4);
this.lblConnectionTimeOut.Name = "lblConnectionTimeOut";
this.lblConnectionTimeOut.Size = new System.Drawing.Size(127, 20);
this.lblConnectionTimeOut.TabIndex = 13;
this.lblConnectionTimeOut.Values.Text = "Connection Time Out";
//
// kryptonLabel1
//
this.kryptonLabel1.Location = new System.Drawing.Point(328, 111);
this.kryptonLabel1.Name = "kryptonLabel1";
this.kryptonLabel1.Size = new System.Drawing.Size(64, 20);
this.kryptonLabel1.TabIndex = 17;
this.kryptonLabel1.Values.Text = "Language";
//
// kryptonLabel2
//
this.kryptonLabel2.Location = new System.Drawing.Point(328, 164);
this.kryptonLabel2.Name = "kryptonLabel2";
this.kryptonLabel2.Size = new System.Drawing.Size(103, 20);
this.kryptonLabel2.TabIndex = 19;
this.kryptonLabel2.Values.Text = "Orm NameSpace";
//
// lblPort
//
this.lblPort.Location = new System.Drawing.Point(328, 56);
this.lblPort.Name = "lblPort";
this.lblPort.Size = new System.Drawing.Size(33, 20);
this.lblPort.TabIndex = 15;
this.lblPort.Values.Text = "Port";
//
// lblPassword
//
this.lblPassword.Location = new System.Drawing.Point(12, 161);
this.lblPassword.Name = "lblPassword";
this.lblPassword.Size = new System.Drawing.Size(62, 20);
this.lblPassword.TabIndex = 6;
this.lblPassword.Values.Text = "Password";
//
// lblLogin
//
this.lblLogin.Location = new System.Drawing.Point(11, 109);
this.lblLogin.Name = "lblLogin";
this.lblLogin.Size = new System.Drawing.Size(41, 20);
this.lblLogin.TabIndex = 4;
this.lblLogin.Values.Text = "Login";
//
// lblDataSource
//
this.lblDataSource.Location = new System.Drawing.Point(11, 57);
this.lblDataSource.Name = "lblDataSource";
this.lblDataSource.Size = new System.Drawing.Size(73, 20);
this.lblDataSource.TabIndex = 2;
this.lblDataSource.Values.Text = "DataSource";
//
// cboLanguage
//
this.cboLanguage.DropDownWidth = 266;
this.cboLanguage.Items.AddRange(new object[] {
"C#",
"VB.Net"});
this.cboLanguage.Location = new System.Drawing.Point(327, 137);
this.cboLanguage.Name = "cboLanguage";
this.cboLanguage.Size = new System.Drawing.Size(266, 21);
this.cboLanguage.TabIndex = 18;
this.cboLanguage.Text = "Select...";
//
// cboDataBase
//
this.cboDataBase.DropDownWidth = 266;
this.cboDataBase.Enabled = false;
this.cboDataBase.Location = new System.Drawing.Point(11, 296);
this.cboDataBase.Name = "cboDataBase";
this.cboDataBase.Size = new System.Drawing.Size(266, 21);
this.cboDataBase.TabIndex = 12;
this.cboDataBase.Text = "Select...";
//
// cboProviderType
//
this.cboProviderType.DropDownWidth = 266;
this.cboProviderType.Location = new System.Drawing.Point(11, 30);
this.cboProviderType.Name = "cboProviderType";
this.cboProviderType.Size = new System.Drawing.Size(266, 21);
this.cboProviderType.TabIndex = 1;
this.cboProviderType.Text = "Select...";
this.cboProviderType.SelectedIndexChanged += new System.EventHandler(this.cboProviderType_SelectedIndexChanged);
//
// lblDataBase
//
this.lblDataBase.Location = new System.Drawing.Point(11, 270);
this.lblDataBase.Name = "lblDataBase";
this.lblDataBase.Size = new System.Drawing.Size(61, 20);
this.lblDataBase.TabIndex = 11;
this.lblDataBase.Values.Text = "DataBase";
//
// lblProviderType
//
this.lblProviderType.Location = new System.Drawing.Point(11, 4);
this.lblProviderType.Name = "lblProviderType";
this.lblProviderType.Size = new System.Drawing.Size(85, 20);
this.lblProviderType.TabIndex = 0;
this.lblProviderType.Values.Text = "Provider Type";
//
// groupBox1
//
this.groupBox1.BackColor = System.Drawing.SystemColors.Window;
this.groupBox1.Controls.Add(this.rdbOldQuery);
this.groupBox1.Controls.Add(this.rdbNewQuery);
this.groupBox1.Location = new System.Drawing.Point(327, 215);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(266, 49);
this.groupBox1.TabIndex = 23;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "New Query";
//
// FrmProviderSettings
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(616, 382);
this.Controls.Add(this.kryptonPanel);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "FrmProviderSettings";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Provider Settings";
((System.ComponentModel.ISupportInitialize)(this.kryptonPanel)).EndInit();
this.kryptonPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).EndInit();
this.kryptonHeaderGroup1.Panel.ResumeLayout(false);
this.kryptonHeaderGroup1.Panel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).EndInit();
this.kryptonHeaderGroup1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.cboLanguage)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cboDataBase)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.cboProviderType)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryptonPanel;
private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroup1;
private ComponentFactory.Krypton.Toolkit.KryptonComboBox cboProviderType;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblProviderType;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox txtDataSource;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblDataSource;
private ComponentFactory.Krypton.Toolkit.KryptonButton btnTest;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox txtPassword;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox txtLogin;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblPassword;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblLogin;
private ComponentFactory.Krypton.Toolkit.KryptonComboBox cboDataBase;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblDataBase;
private ComponentFactory.Krypton.Toolkit.KryptonNumericUpDown nudConnectionTimeout;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblConnectionTimeOut;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox txtPort;
private ComponentFactory.Krypton.Toolkit.KryptonLabel lblPort;
private ComponentFactory.Krypton.Toolkit.KryptonButton btnSave;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel1;
private ComponentFactory.Krypton.Toolkit.KryptonComboBox cboLanguage;
private System.Windows.Forms.Label lblStatus;
private System.Windows.Forms.Label label1;
private ComponentFactory.Krypton.Toolkit.KryptonTextBox txtOrmNameSpace;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryptonLabel2;
private System.Windows.Forms.RadioButton rdbOldQuery;
private System.Windows.Forms.RadioButton rdbNewQuery;
private System.Windows.Forms.GroupBox groupBox1;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using IKVM.Reflection;
using Type = IKVM.Reflection.Type;
namespace Embeddinator.ObjC {
public static class NameGenerator {
public static Dictionary<string, string> ObjCTypeToArgument = new Dictionary<string, string> {
{ "int", "anInt" },
{ "unsigned int", "aUint" },
{ "double", "aDouble" },
{ "float", "aFloat" },
{ "NSString", "aString" },
{ "NSString *", "aString" },
{ "id", "anObject" },
{ "NSObject", "anObject" },
{ "NSPoint", "aPoint" },
{ "NSRect", "aRect" },
{ "NSFont", "fontObj" },
{ "SEL", "aSelector" },
{ "short", "aShort" },
{ "unsigned short", "aUshort" },
{ "long long", "aLong" },
{ "unsigned long long", "aUlong" },
{ "bool", "aBool" },
{ "char", "aChar" },
{ "unsigned char", "aChar" },
{ "signed char", "aChar" }
};
public static Dictionary<string, string> ObjCTypeToMethodName = new Dictionary<string, string> {
{ "int", "IntValue" },
{ "unsigned int", "UIntValue" },
{ "double", "DoubleValue" },
{ "float", "FloatValue" },
{ "NSString *", "StringValue" },
{ "NSObject", "ObjectValue" },
{ "NSPoint", "PointValue" },
{ "NSRect", "RectValue" },
{ "NSFont", "FontValue" },
{ "SEL", "SelectorValue" },
{ "short", "ShortValue" },
{ "unsigned short", "UShortValue" },
{ "long long", "LongValue" },
{ "unsigned long long", "ULongValue" },
{ "bool", "BoolValue" },
{ "char", "CharValue" },
{ "unsigned char", "UCharValue" },
{ "signed char", "SCharValue" }
};
public static string GetObjCName (Type t)
{
return t.FullName.Replace ('.', '_').Replace ("+", "_");
}
// TODO complete mapping (only with corresponding tests)
// TODO override with attribute ? e.g. [Obj.Name ("XAMType")]
public static string GetTypeName (Type t)
{
if (t.IsByRef) {
var et = t.GetElementType ();
var typecode = Type.GetTypeCode (et);
if (typecode == TypeCode.Decimal || typecode == TypeCode.DateTime) // This is boxed into NSDecimalNumber/NSDate
return GetTypeName (et) + "_Nonnull * _Nullable";
return GetTypeName (et) + " * " + (et.IsValueType ? "_Nullable" : "_Nonnull");
}
if (t.IsEnum)
return GetObjCName (t);
if (t.IsArray)
return GetArrayTypeName (t.GetElementType ());
switch (Type.GetTypeCode (t)) {
case TypeCode.Object:
switch (t.Namespace) {
case "System":
switch (t.Name) {
case "Object":
case "ValueType":
return "NSObject";
case "Void":
return "void";
default:
return GetObjCName (t);
}
default:
return GetObjCName (t);
}
case TypeCode.Boolean:
return "bool";
case TypeCode.Char:
return "unsigned short";
case TypeCode.Double:
return "double";
case TypeCode.Single:
return "float";
case TypeCode.Byte:
return "unsigned char";
case TypeCode.SByte:
return "signed char";
case TypeCode.Int16:
return "short";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long long";
case TypeCode.UInt16:
return "unsigned short";
case TypeCode.UInt32:
return "unsigned int";
case TypeCode.UInt64:
return "unsigned long long";
case TypeCode.String:
return "NSString *";
case TypeCode.Decimal:
return "NSDecimalNumber *";
case TypeCode.DateTime:
return "NSDate *";
default:
throw new NotImplementedException ($"Converting type {t.Name} to a native type name");
}
}
public static string GetMonoName (Type t)
{
if (t.IsByRef)
return GetMonoName (t.GetElementType ()) + "&";
if (t.IsEnum)
return t.FullName;
if (t.IsArray)
return $"{GetMonoName (t.GetElementType ())}[]";
switch (Type.GetTypeCode (t)) {
case TypeCode.Object:
switch (t.Namespace) {
case "System":
switch (t.Name) {
case "Void":
return "void";
default:
return t.IsInterface ? t.FullName : "object";
}
default:
return t.FullName;
}
case TypeCode.Boolean:
return "bool";
case TypeCode.Char:
return "char";
case TypeCode.Double:
return "double";
case TypeCode.Single:
return "single";
case TypeCode.Byte:
return "byte";
case TypeCode.SByte:
return "sbyte";
case TypeCode.Int16:
return "int16";
case TypeCode.Int32:
return "int";
case TypeCode.Int64:
return "long";
case TypeCode.UInt16:
return "uint16";
case TypeCode.UInt32:
return "uint";
case TypeCode.UInt64:
return "ulong";
case TypeCode.String:
return "string";
case TypeCode.Decimal:
return "System.Decimal";
case TypeCode.DateTime:
return "System.DateTime";
default:
throw new NotImplementedException ($"Converting type {t.Name} to a mono type name");
}
}
public static string GetArrayTypeName (Type t)
{
switch (Type.GetTypeCode (t)) {
case TypeCode.Boolean:
case TypeCode.Char:
case TypeCode.Double:
case TypeCode.Single:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.Int32:
case TypeCode.Int64:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return "NSArray <NSNumber *> *";
case TypeCode.Byte:
return "NSData *";
case TypeCode.String:
return "NSArray <NSString *> *";
case TypeCode.Object:
if (t.IsInterface)
return $"NSArray<id<{GetObjCName (t)}>> *";
return $"NSArray<{GetObjCName (t)} *> *";
case TypeCode.Decimal:
return "NSArray <NSDecimalNumber *> *";
case TypeCode.DateTime:
return "NSArray <NSDate *> *";
default:
throw new NotImplementedException ($"Converting type {t.Name} to a native type name");
}
}
public static string GetParameterTypeName (Type t)
{
if (t.IsArray)
return t.GetElementType ().Name + "Array";
if (t.IsByRef)
return t.GetElementType ().Name + "Ref";
if (!ObjCTypeToMethodName.TryGetValue (GetTypeName (t), out string name))
name = t.Name;
return name;
}
public static string GetExtendedParameterName (ParameterInfo p, ParameterInfo [] parameters)
{
string pName = p.Name;
string ptname = GetTypeName (p.ParameterType);
if (RestrictedNames.IsRestrictedName (pName))
pName = "managed" + pName;
if (p.Name.Length < 3) {
if (!ObjCTypeToArgument.TryGetValue (ptname, out pName))
pName = "anObject";
if (parameters.Count (p2 => GetTypeName (p2.ParameterType) == ptname && p2.Name.Length < 3) > 1 ||
pName == "anObject" && parameters.Count (p2 => !ObjCTypeToArgument.ContainsKey (GetTypeName (p2.ParameterType))) > 1)
pName += p.Name.PascalCase ();
}
return pName;
}
public static string GetObjCParamTypeName (ParameterInfo param, List<ProcessedType> allTypes)
{
Type pt = param.ParameterType;
string ptname = GetTypeName (pt);
if (pt.IsInterface)
ptname = $"id<{ptname}>";
if (allTypes.HasClass (pt))
ptname += " *";
return ptname;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Linq.Impl
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Common;
using Remotion.Linq;
/// <summary>
/// Fields query executor.
/// </summary>
internal class CacheFieldsQueryExecutor : IQueryExecutor
{
/** */
private readonly ICacheInternal _cache;
/** */
private static readonly CopyOnWriteConcurrentDictionary<ConstructorInfo, object> CtorCache =
new CopyOnWriteConcurrentDictionary<ConstructorInfo, object>();
/** */
private readonly bool _local;
/** */
private readonly int _pageSize;
/** */
private readonly bool _enableDistributedJoins;
/** */
private readonly bool _enforceJoinOrder;
/// <summary>
/// Initializes a new instance of the <see cref="CacheFieldsQueryExecutor" /> class.
/// </summary>
/// <param name="cache">The executor function.</param>
/// <param name="local">Local flag.</param>
/// <param name="pageSize">Size of the page.</param>
/// <param name="enableDistributedJoins">Distributed joins flag.</param>
/// <param name="enforceJoinOrder">Enforce join order flag.</param>
public CacheFieldsQueryExecutor(ICacheInternal cache, bool local, int pageSize, bool enableDistributedJoins,
bool enforceJoinOrder)
{
Debug.Assert(cache != null);
_cache = cache;
_local = local;
_pageSize = pageSize;
_enableDistributedJoins = enableDistributedJoins;
_enforceJoinOrder = enforceJoinOrder;
}
/** <inheritdoc /> */
public T ExecuteScalar<T>(QueryModel queryModel)
{
return ExecuteSingle<T>(queryModel, false);
}
/** <inheritdoc /> */
public T ExecuteSingle<T>(QueryModel queryModel, bool returnDefaultWhenEmpty)
{
var col = ExecuteCollection<T>(queryModel);
return returnDefaultWhenEmpty ? col.SingleOrDefault() : col.Single();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")]
public IEnumerable<T> ExecuteCollection<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryData = GetQueryData(queryModel);
Debug.WriteLine("\nFields Query: {0} | {1}", qryData.QueryText,
string.Join(", ", qryData.Parameters.Select(x => x == null ? "null" : x.ToString())));
var qry = GetFieldsQuery(qryData.QueryText, qryData.Parameters.ToArray());
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return _cache.QueryFields(qry, selector);
}
/// <summary>
/// Compiles the query (old method, does not support some scenarios).
/// </summary>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel, Delegate queryCaller)
{
Debug.Assert(queryModel != null);
Debug.Assert(queryCaller != null);
var qryData = GetQueryData(queryModel);
var qryText = qryData.QueryText;
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
// Compiled query is a delegate with query parameters
// Delegate parameters order and query parameters order may differ
// These are in order of usage in query
var qryOrderParams = qryData.ParameterExpressions.OfType<MemberExpression>()
.Select(x => x.Member.Name).ToList();
// These are in order they come from user
var userOrderParams = queryCaller.Method.GetParameters().Select(x => x.Name).ToList();
if ((qryOrderParams.Count != qryData.Parameters.Count) ||
(qryOrderParams.Count != userOrderParams.Count))
throw new InvalidOperationException("Error compiling query: all compiled query arguments " +
"should come from enclosing delegate parameters.");
var indices = qryOrderParams.Select(x => userOrderParams.IndexOf(x)).ToArray();
// Check if user param order is already correct
if (indices.SequenceEqual(Enumerable.Range(0, indices.Length)))
return args => _cache.QueryFields(GetFieldsQuery(qryText, args), selector);
// Return delegate with reorder
return args => _cache.QueryFields(GetFieldsQuery(qryText,
args.Select((x, i) => args[indices[i]]).ToArray()), selector);
}
/// <summary>
/// Compiles the query without regard to number or order of arguments.
/// </summary>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
var qryText = GetQueryData(queryModel).QueryText;
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
return args => _cache.QueryFields(GetFieldsQuery(qryText, args), selector);
}
/// <summary>
/// Compiles the query.
/// </summary>
/// <typeparam name="T">Result type.</typeparam>
/// <param name="queryModel">The query model.</param>
/// <param name="queryLambdaModel">The query model generated from lambda body.</param>
/// <param name="queryLambda">The query lambda.</param>
/// <returns>Compiled query func.</returns>
public Func<object[], IQueryCursor<T>> CompileQuery<T>(QueryModel queryModel, QueryModel queryLambdaModel,
LambdaExpression queryLambda)
{
Debug.Assert(queryModel != null);
// Get model from lambda to map arguments properly.
var qryData = GetQueryData(queryLambdaModel);
var qryText = GetQueryData(queryModel).QueryText;
var qryTextLambda = qryData.QueryText;
if (qryText != qryTextLambda)
{
Debug.WriteLine(qryText);
Debug.WriteLine(qryTextLambda);
throw new InvalidOperationException("Error compiling query: entire LINQ expression should be " +
"specified within lambda passed to Compile method. " +
"Part of the query can't be outside the Compile method call.");
}
var selector = GetResultSelector<T>(queryModel.SelectClause.Selector);
var qryParams = qryData.Parameters.ToArray();
// Compiled query is a delegate with query parameters
// Delegate parameters order and query parameters order may differ
// Simple case: lambda with no parameters. Only embedded parameters are used.
if (!queryLambda.Parameters.Any())
{
return argsUnused => _cache.QueryFields(GetFieldsQuery(qryText, qryParams), selector);
}
// These are in order of usage in query
var qryOrderArgs = qryParams.OfType<ParameterExpression>().Select(x => x.Name).ToArray();
// These are in order they come from user
var userOrderArgs = queryLambda.Parameters.Select(x => x.Name).ToList();
// Simple case: all query args directly map to the lambda args in the same order
if (qryOrderArgs.Length == qryParams.Length
&& qryOrderArgs.SequenceEqual(userOrderArgs))
{
return args => _cache.QueryFields(GetFieldsQuery(qryText, args), selector);
}
// General case: embedded args and lambda args are mixed; same args can be used multiple times.
// Produce a mapping that defines where query arguments come from.
var mapping = qryParams.Select(x =>
{
var pe = x as ParameterExpression;
if (pe != null)
return userOrderArgs.IndexOf(pe.Name);
return -1;
}).ToArray();
return args => _cache.QueryFields(
GetFieldsQuery(qryText, MapQueryArgs(args, qryParams, mapping)), selector);
}
/// <summary>
/// Maps the query arguments.
/// </summary>
private static object[] MapQueryArgs(object[] userArgs, object[] embeddedArgs, int[] mapping)
{
var mappedArgs = new object[embeddedArgs.Length];
for (var i = 0; i < mappedArgs.Length; i++)
{
var map = mapping[i];
mappedArgs[i] = map < 0 ? embeddedArgs[i] : userArgs[map];
}
return mappedArgs;
}
/// <summary>
/// Gets the fields query.
/// </summary>
internal SqlFieldsQuery GetFieldsQuery(string text, object[] args)
{
return new SqlFieldsQuery(text, _local, args)
{
EnableDistributedJoins = _enableDistributedJoins,
PageSize = _pageSize,
EnforceJoinOrder = _enforceJoinOrder
};
}
/** <inheritdoc /> */
public static QueryData GetQueryData(QueryModel queryModel)
{
Debug.Assert(queryModel != null);
return new CacheQueryModelVisitor().GenerateQuery(queryModel);
}
/// <summary>
/// Gets the result selector.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetResultSelector<T>(Expression selectorExpression)
{
var newExpr = selectorExpression as NewExpression;
if (newExpr != null)
return GetCompiledCtor<T>(newExpr.Constructor);
var entryCtor = GetCacheEntryCtorInfo(typeof(T));
if (entryCtor != null)
return GetCompiledCtor<T>(entryCtor);
if (typeof(T) == typeof(bool))
return ReadBool<T>;
return (reader, count) => reader.ReadObject<T>();
}
/// <summary>
/// Reads the bool. Actual data may be bool or int/long.
/// </summary>
private static T ReadBool<T>(IBinaryRawReader reader, int count)
{
var obj = reader.ReadObject<object>();
if (obj is bool)
return (T) obj;
if (obj is long)
return TypeCaster<T>.Cast((long) obj != 0);
if (obj is int)
return TypeCaster<T>.Cast((int) obj != 0);
throw new InvalidOperationException("Expected bool, got: " + obj);
}
/// <summary>
/// Gets the cache entry constructor.
/// </summary>
private static ConstructorInfo GetCacheEntryCtorInfo(Type entryType)
{
if (!entryType.IsGenericType || entryType.GetGenericTypeDefinition() != typeof(ICacheEntry<,>))
return null;
var args = entryType.GetGenericArguments();
var targetType = typeof (CacheEntry<,>).MakeGenericType(args);
return targetType.GetConstructors().Single();
}
/// <summary>
/// Gets the compiled constructor.
/// </summary>
private static Func<IBinaryRawReader, int, T> GetCompiledCtor<T>(ConstructorInfo ctorInfo)
{
object result;
if (CtorCache.TryGetValue(ctorInfo, out result))
return (Func<IBinaryRawReader, int, T>) result;
return (Func<IBinaryRawReader, int, T>) CtorCache.GetOrAdd(ctorInfo, x =>
{
var innerCtor1 = DelegateConverter.CompileCtor<T>(x, GetCacheEntryCtorInfo);
return (Func<IBinaryRawReader, int, T>) ((r, c) => innerCtor1(r));
});
}
}
}
| |
//
// Updater.cs
//
// Lunar Unity Mobile Console
// https://github.com/SpaceMadness/lunar-unity-console
//
// Copyright 2015-2021 Alex Lementuev, SpaceMadness.
//
// 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 UnityEditor;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using LunarConsolePluginInternal;
namespace LunarConsoleEditorInternal
{
static class Updater
{
private static readonly string kMessageBoxTitle = "Lunar Mobile Console";
struct UpdateInfo
{
public readonly string version;
public readonly string url;
public readonly string message;
public UpdateInfo(string version, string url, string message)
{
this.version = version;
this.url = url;
this.message = message;
}
public override string ToString()
{
return string.Format("UpdateInfo:\n\tversion={0}\n\turl={1}\n\tmessage={2}", version, url, message);
}
}
struct VersionInfo
{
public readonly int major;
public readonly int minor;
public readonly int maintenance;
public VersionInfo(int major, int minor, int maintenace)
{
this.major = major;
this.minor = minor;
this.maintenance = maintenace;
}
public static bool TryParse(string value, out VersionInfo info)
{
if (value.Length > 1 && value.EndsWith("b"))
{
value = value.Substring(0, value.Length - 1);
}
if (string.IsNullOrEmpty(value))
{
info = default(VersionInfo);
return false;
}
string[] tokens = value.Split('.');
if (tokens.Length != 3)
{
info = default(VersionInfo);
return false;
}
int major;
if (!int.TryParse(tokens[0], out major))
{
info = default(VersionInfo);
return false;
}
int minor;
if (!int.TryParse(tokens[1], out minor))
{
info = default(VersionInfo);
return false;
}
int maintenance;
if (!int.TryParse(tokens[2], out maintenance))
{
info = default(VersionInfo);
return false;
}
info = new VersionInfo(major, minor, maintenance);
return true;
}
public int CompareTo(ref VersionInfo other)
{
int majorCmp = this.major.CompareTo(other.major);
if (majorCmp != 0) return majorCmp;
int minorCmd = this.minor.CompareTo(other.minor);
if (minorCmd != 0) return minorCmd;
return this.maintenance.CompareTo(other.maintenance);
}
}
#pragma warning disable 0649
private static LastCheckDate s_lastInstallCheckDate;
#pragma warning restore 0649
public static void TryCheckForUpdates()
{
#if !LUNAR_CONSOLE_UPDATER_DISABLED
s_lastInstallCheckDate = new LastCheckDate(kPrefsKeyLastUpdateCheckDate);
if (s_lastInstallCheckDate.CanCheckNow())
{
s_lastInstallCheckDate.SetToday();
CheckForUpdates();
}
else
{
Log.d("Skipping update check. Next check: {0}", s_lastInstallCheckDate);
}
#endif
}
public static void CheckForUpdates(bool silent = true)
{
LunarConsoleHttpClient downloader = new LunarConsoleHttpClient(LunarConsoleConfig.fullVersion ? Constants.UpdateJsonURLFull : Constants.UpdateJsonURLFree);
downloader.DownloadString(delegate (string response, Exception error)
{
if (error != null)
{
Log.e(error, "Can't get updater info");
if (!silent)
{
Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
}
return;
}
UpdateInfo info;
if (response != null && TryParseUpdateInfo(response, out info))
{
if (IsShouldSkipVersion(info.version))
{
Log.d("User decided to skip version {0}", info.version);
return;
}
if (PluginVersionChecker.IsNewerVersion(info.version))
{
StringBuilder message = new StringBuilder();
message.AppendFormat("A new version {0} is available!\n\n", info.version);
if (info.message != null && info.message.Length > 0)
{
message.Append(info.message);
message.AppendLine();
}
Utils.ShowDialog(kMessageBoxTitle, message.ToString(),
new DialogButton("Details...", delegate (string obj)
{
Application.OpenURL(info.url);
LunarConsoleEditorAnalytics.TrackEvent("Version", "updater_details");
}),
new DialogButton("Remind me later", delegate (string obj)
{
LunarConsoleEditorAnalytics.TrackEvent("Version", "updater_later");
}),
new DialogButton("Skip this version", delegate (string obj)
{
SetShouldSkipVersion(info.version);
LunarConsoleEditorAnalytics.TrackEvent("Version", "updater_skip");
})
);
}
else
{
if (!silent)
{
Utils.ShowMessageDialog(kMessageBoxTitle, "Everything is up to date");
}
Debug.Log("Everything is up to date");
}
}
else
{
Log.e("Unable to parse response: '{0}'", response);
if (!silent)
{
Utils.ShowDialog(kMessageBoxTitle, "Update info is not available.\n\nTry again later.", "OK");
}
}
});
}
public static void Reset()
{
s_lastInstallCheckDate.Reset();
}
private static bool TryParseUpdateInfo(string response, out UpdateInfo updateInfo)
{
try
{
JSONNode node = JSON.Parse(response);
JSONClass root = node.AsObject;
if (root != null)
{
return TryParseUpdateInfo(root, out updateInfo);
}
}
catch (Exception e)
{
Log.e(e, "Unable to parse plugin update info");
}
updateInfo = default(UpdateInfo);
return false;
}
private static bool TryParseUpdateInfo(JSONClass response, out UpdateInfo updateInfo)
{
string status = response["status"];
if (status != "OK")
{
Log.e("Unexpected response 'status': {0}", status);
updateInfo = default(UpdateInfo);
return false;
}
string version = response["version"];
if (version == null)
{
Log.e("Missing response 'version' string");
updateInfo = default(UpdateInfo);
return false;
}
string url = response["url"];
if (url == null)
{
Log.e("Missing response 'url' string");
updateInfo = default(UpdateInfo);
return false;
}
string message = response["message"];
if (message == null)
{
Log.e("Missing response 'message'");
updateInfo = default(UpdateInfo);
return false;
}
updateInfo = new UpdateInfo(version, url, message);
return true;
}
static class PluginVersionChecker
{
public static bool IsNewerVersion(string version)
{
VersionInfo newVersion;
if (!VersionInfo.TryParse(version, out newVersion))
{
throw new ArgumentException("Bad version number: " + version);
}
string oldVersionStr = ResolvePluginVersion();
VersionInfo oldVersion;
if (oldVersionStr != null && VersionInfo.TryParse(oldVersionStr, out oldVersion))
{
return oldVersion.CompareTo(ref newVersion) < 0;
}
return true;
}
private static string ResolvePluginVersion()
{
return Constants.Version;
}
}
#region Preferences
private static readonly string kPrefsKeySkipVersion = Constants.EditorPrefsKeyBase + ".SkipVersion";
private static readonly string kPrefsKeyLastUpdateCheckDate = Constants.EditorPrefsKeyBase + ".LastUpdateCheckDate";
private static bool IsShouldSkipVersion(string version)
{
string skipVersion = EditorPrefs.GetString(kPrefsKeySkipVersion);
return skipVersion == version;
}
private static void SetShouldSkipVersion(string version)
{
EditorPrefs.SetString(kPrefsKeySkipVersion, version);
}
private static bool GetPrefsFlag(string key)
{
return EditorPrefs.GetInt(key, 0) != 0;
}
private static void SetPrefsFlag(string key, bool flag)
{
EditorPrefs.SetInt(key, flag ? 1 : 0);
}
#endregion
#region Last date checker
class LastCheckDate
{
private string m_key;
public LastCheckDate(string key)
{
if (key == null)
{
throw new ArgumentNullException("key");
}
m_key = key;
}
public bool CanCheckNow()
{
DateTime lastCheckDate = GetDate();
int totalDays = (int)(DateTime.Now - lastCheckDate).TotalDays;
return totalDays > 0;
}
public void SetToday()
{
SetDate(DateTime.Now);
}
public void SetNever()
{
SetDate(DateTime.MaxValue);
}
public void Reset()
{
EditorPrefs.DeleteKey(m_key);
}
private void SetDate(DateTime date)
{
EditorPrefs.SetString(m_key, date.ToShortDateString());
}
private DateTime GetDate()
{
string value = EditorPrefs.GetString(m_key);
DateTime date;
if (value != null && DateTime.TryParse(value, out date))
{
return date;
}
return DateTime.MinValue;
}
public override string ToString()
{
return GetDate().ToString();
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Text;
using System.Runtime;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using Internal.Reflection.Augments;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
namespace System
{
// WARNING: Bartok hard-codes offsets to the delegate fields, so it's notion of where fields are may
// differ from the runtime's notion. Bartok honors sequential and explicit layout directives, so I've
// ordered the fields in such a way as to match the runtime's layout and then just tacked on this
// sequential layout directive so that Bartok matches it.
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")]
public abstract partial class Delegate : ICloneable, ISerializable
{
// This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a
// "protected-and-internal" rather than "internal" but C# has no keyword for the former.
internal Delegate()
{
// ! Do NOT put any code here. Delegate constructers are not guaranteed to be executed.
}
// V1 API: Create closed instance delegates. Method name matching is case sensitive.
protected Delegate(object target, string method)
{
// This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an
// overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal
// implementation of CreateDelegate below, and does not invoke this constructor.
// The constructor is just for API compatibility with the public contract of the Delegate class.
throw new PlatformNotSupportedException();
}
// V1 API: Create open static delegates. Method name matching is case insensitive.
protected Delegate(Type target, string method)
{
// This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an
// overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal
// implementation of CreateDelegate below, and does not invoke this constructor.
// The constructor is just for API compatibility with the public contract of the Delegate class.
throw new PlatformNotSupportedException();
}
// New Delegate Implementation
protected internal object m_firstParameter;
protected internal object m_helperObject;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
protected internal IntPtr m_extraFunctionPointerOrData;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")]
protected internal IntPtr m_functionPointer;
[ThreadStatic]
protected static string s_DefaultValueString;
// WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs
// Do not change their values without updating the values in the calling convention converter component
protected const int MulticastThunk = 0;
protected const int ClosedStaticThunk = 1;
protected const int OpenStaticThunk = 2;
protected const int ClosedInstanceThunkOverGenericMethod = 3; // This may not exist
protected const int DelegateInvokeThunk = 4;
protected const int OpenInstanceThunk = 5; // This may not exist
protected const int ReversePinvokeThunk = 6; // This may not exist
protected const int ObjectArrayThunk = 7; // This may not exist
//
// If the thunk does not exist, the function will return IntPtr.Zero.
protected virtual IntPtr GetThunk(int whichThunk)
{
#if DEBUG
// The GetThunk function should be overriden on all delegate types, except for universal
// canonical delegates which use calling convention converter thunks to marshal arguments
// for the delegate call. If we execute this version of GetThunk, we can at least assert
// that the current delegate type is a generic type.
Debug.Assert(this.EETypePtr.IsGeneric);
#endif
return TypeLoaderExports.GetDelegateThunk(this, whichThunk);
}
//
// If there is a default value string, the overridden function should set the
// s_DefaultValueString field and return true.
protected virtual bool LoadDefaultValueString() { return false; }
/// <summary>
/// Used by various parts of the runtime as a replacement for Delegate.Method
///
/// The Interop layer uses this to distinguish between different methods on a
/// single type, and to get the function pointer for delegates to static functions
///
/// The reflection apis use this api to figure out what MethodInfo is related
/// to a delegate.
///
/// </summary>
/// <param name="typeOfFirstParameterIfInstanceDelegate">
/// This value indicates which type an delegate's function pointer is associated with
/// This value is ONLY set for delegates where the function pointer points at an instance method
/// </param>
/// <param name="isOpenResolver">
/// This value indicates if the returned pointer is an open resolver structure.
/// </param>
/// <param name="isInterpreterEntrypoint">
/// Delegate points to an object array thunk (the delegate wraps a Func<object[], object> delegate). This
/// is typically a delegate pointing to the LINQ expression interpreter.
/// </param>
/// <returns></returns>
unsafe internal IntPtr GetFunctionPointer(out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver, out bool isInterpreterEntrypoint)
{
typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle);
isOpenResolver = false;
isInterpreterEntrypoint = false;
if (GetThunk(MulticastThunk) == m_functionPointer)
{
return IntPtr.Zero;
}
else if (GetThunk(ObjectArrayThunk) == m_functionPointer)
{
isInterpreterEntrypoint = true;
return IntPtr.Zero;
}
else if (m_extraFunctionPointerOrData != IntPtr.Zero)
{
if (GetThunk(OpenInstanceThunk) == m_functionPointer)
{
typeOfFirstParameterIfInstanceDelegate = ((OpenMethodResolver*)m_extraFunctionPointerOrData)->DeclaringType;
isOpenResolver = true;
}
return m_extraFunctionPointerOrData;
}
else
{
if (m_firstParameter != null)
typeOfFirstParameterIfInstanceDelegate = new RuntimeTypeHandle(m_firstParameter.EETypePtr);
// TODO! Implementation issue for generic invokes here ... we need another IntPtr for uniqueness.
return m_functionPointer;
}
}
// @todo: Not an api but some NativeThreadPool code still depends on it.
internal IntPtr GetNativeFunctionPointer()
{
if (GetThunk(ReversePinvokeThunk) != m_functionPointer)
{
throw new InvalidOperationException("GetNativeFunctionPointer may only be used on a reverse pinvoke delegate");
}
return m_extraFunctionPointerOrData;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstance(object firstParameter, IntPtr functionPointer)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
// This function is known to the IL Transformer.
protected void InitializeClosedInstanceSlow(object firstParameter, IntPtr functionPointer)
{
// This method is like InitializeClosedInstance, but it handles ALL cases. In particular, it handles generic method with fun function pointers.
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the compiler.
protected void InitializeClosedInstanceWithGVMResolution(object firstParameter, RuntimeMethodHandle tokenOfGenericVirtualMethod)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
IntPtr functionResolution = TypeLoaderExports.GVMLookupForSlot(firstParameter, tokenOfGenericVirtualMethod);
if (functionResolution == IntPtr.Zero)
{
// TODO! What to do when GVM resolution fails. Should never happen
throw new InvalidOperationException();
}
if (!FunctionPointerOps.IsGenericMethodPointer(functionResolution))
{
m_functionPointer = functionResolution;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionResolution;
m_helperObject = firstParameter;
}
return;
}
private void InitializeClosedInstanceToInterface(object firstParameter, IntPtr dispatchCell)
{
if (firstParameter == null)
throw new ArgumentException(SR.Arg_DlgtNullInst);
m_functionPointer = RuntimeImports.RhpResolveInterfaceMethod(firstParameter, dispatchCell);
m_firstParameter = firstParameter;
}
// This is used to implement MethodInfo.CreateDelegate() in a desktop-compatible way. Yes, the desktop really
// let you use that api to invoke an instance method with a null 'this'.
private void InitializeClosedInstanceWithoutNullCheck(object firstParameter, IntPtr functionPointer)
{
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
m_functionPointer = functionPointer;
m_firstParameter = firstParameter;
}
else
{
m_firstParameter = this;
m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod);
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
}
}
// This function is known to the compiler backend.
protected void InitializeClosedStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
m_functionPointer = functionPointerThunk;
m_firstParameter = this;
}
// This function is known to the compiler backend.
protected void InitializeClosedStaticWithoutThunk(object firstParameter, IntPtr functionPointer)
{
m_extraFunctionPointerOrData = functionPointer;
m_helperObject = firstParameter;
m_functionPointer = GetThunk(ClosedStaticThunk);
m_firstParameter = this;
}
// This function is known to the compiler backend.
protected void InitializeOpenStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeOpenStaticWithoutThunk(object firstParameter, IntPtr functionPointer)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(OpenStaticThunk);
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeReversePInvokeThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeReversePInvokeWithoutThunk(object firstParameter, IntPtr functionPointer)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(ReversePinvokeThunk);
m_extraFunctionPointerOrData = functionPointer;
}
// This function is known to the compiler backend.
protected void InitializeOpenInstanceThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0);
m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr();
}
// This function is known to the compiler backend.
protected void InitializeOpenInstanceWithoutThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = GetThunk(OpenInstanceThunk);
OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0);
m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr();
}
protected void InitializeOpenInstanceThunkDynamic(IntPtr functionPointer, IntPtr functionPointerThunk)
{
// This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself.
m_firstParameter = this;
m_functionPointer = functionPointerThunk;
m_extraFunctionPointerOrData = functionPointer;
}
internal void SetClosedStaticFirstParameter(object firstParameter)
{
// Closed static delegates place a value in m_helperObject that they pass to the target method.
Debug.Assert(m_functionPointer == GetThunk(ClosedStaticThunk));
m_helperObject = firstParameter;
}
// This function is only ever called by the open instance method thunk, and in that case,
// m_extraFunctionPointerOrData always points to an OpenMethodResolver
[MethodImpl(MethodImplOptions.NoInlining)]
protected IntPtr GetActualTargetFunctionPointer(object thisObject)
{
return OpenMethodResolver.ResolveMethod(m_extraFunctionPointerOrData, thisObject);
}
public override int GetHashCode()
{
return GetType().GetHashCode();
}
private bool IsDynamicDelegate()
{
if (this.GetThunk(MulticastThunk) == IntPtr.Zero)
{
return true;
}
return false;
}
[DebuggerGuidedStepThroughAttribute]
protected virtual object DynamicInvokeImpl(object[] args)
{
if (IsDynamicDelegate())
{
// DynamicDelegate case
object result = ((Func<object[], object>)m_helperObject)(args);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
else
{
IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk);
#if PROJECTN
object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null, wrapInTargetInvocationException: true);
#else
IntPtr genericDictionary = IntPtr.Zero;
if (FunctionPointerOps.IsGenericMethodPointer(invokeThunk))
{
unsafe
{
GenericMethodDescriptor* descriptor = FunctionPointerOps.ConvertToGenericDescriptor(invokeThunk);
genericDictionary = descriptor->InstantiationArgument;
invokeThunk = descriptor->MethodFunctionPointer;
}
}
object result = InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, null, invokeThunk, genericDictionary, this, args, binderBundle: null, wrapInTargetInvocationException: true, invokeMethodHelperIsThisCall: false);
#endif
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
}
[DebuggerGuidedStepThroughAttribute]
public object DynamicInvoke(params object[] args)
{
object result = DynamicInvokeImpl(args);
DebugAnnotations.PreviousCallContainsDebuggerStepInCode();
return result;
}
public static unsafe Delegate Combine(Delegate a, Delegate b)
{
if (a == null)
return b;
if (b == null)
return a;
return a.CombineImpl(b);
}
public static Delegate Remove(Delegate source, Delegate value)
{
if (source == null)
return null;
if (value == null)
return source;
if (!InternalEqualTypes(source, value))
throw new ArgumentException(SR.Arg_DlgtTypeMis);
return source.RemoveImpl(value);
}
public static Delegate RemoveAll(Delegate source, Delegate value)
{
Delegate newDelegate = null;
do
{
newDelegate = source;
source = Remove(source, value);
}
while (newDelegate != source);
return newDelegate;
}
// Used to support the C# compiler in implementing the "+" operator for delegates
public static Delegate Combine(params Delegate[] delegates)
{
if ((delegates == null) || (delegates.Length == 0))
return null;
Delegate d = delegates[0];
for (int i = 1; i < delegates.Length; i++)
{
d = Combine(d, delegates[i]);
}
return d;
}
private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount, bool thisIsMultiCastAlready)
{
// First, allocate a new multicast delegate just like this one, i.e. same type as the this object
MulticastDelegate result = (MulticastDelegate)RuntimeImports.RhNewObject(this.EETypePtr);
// Performance optimization - if this already points to a true multicast delegate,
// copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them
if (thisIsMultiCastAlready)
{
result.m_functionPointer = this.m_functionPointer;
}
else
{
result.m_functionPointer = GetThunk(MulticastThunk);
}
result.m_firstParameter = result;
result.m_helperObject = invocationList;
result.m_extraFunctionPointerOrData = (IntPtr)invocationCount;
return result;
}
internal MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount)
{
return NewMulticastDelegate(invocationList, invocationCount, false);
}
private bool TrySetSlot(Delegate[] a, int index, Delegate o)
{
if (a[index] == null && System.Threading.Interlocked.CompareExchange<Delegate>(ref a[index], o, null) == null)
return true;
// The slot may be already set because we have added and removed the same method before.
// Optimize this case, because it's cheaper than copying the array.
if (a[index] != null)
{
MulticastDelegate d = (MulticastDelegate)o;
MulticastDelegate dd = (MulticastDelegate)a[index];
if (object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) &&
object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) &&
dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData &&
dd.m_functionPointer == d.m_functionPointer)
{
return true;
}
}
return false;
}
// This method will combine this delegate with the passed delegate
// to form a new delegate.
protected virtual Delegate CombineImpl(Delegate d)
{
if ((object)d == null) // cast to object for a more efficient test
return this;
// Verify that the types are the same...
if (!InternalEqualTypes(this, d))
throw new ArgumentException();
if (IsDynamicDelegate() && d.IsDynamicDelegate())
{
throw new InvalidOperationException();
}
MulticastDelegate dFollow = (MulticastDelegate)d;
Delegate[] resultList;
int followCount = 1;
Delegate[] followList = dFollow.m_helperObject as Delegate[];
if (followList != null)
followCount = (int)dFollow.m_extraFunctionPointerOrData;
int resultCount;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
resultCount = 1 + followCount;
resultList = new Delegate[resultCount];
resultList[0] = this;
if (followList == null)
{
resultList[1] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[1 + i] = followList[i];
}
return NewMulticastDelegate(resultList, resultCount);
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
resultCount = invocationCount + followCount;
resultList = null;
if (resultCount <= invocationList.Length)
{
resultList = invocationList;
if (followList == null)
{
if (!TrySetSlot(resultList, invocationCount, dFollow))
resultList = null;
}
else
{
for (int i = 0; i < followCount; i++)
{
if (!TrySetSlot(resultList, invocationCount + i, followList[i]))
{
resultList = null;
break;
}
}
}
}
if (resultList == null)
{
int allocCount = invocationList.Length;
while (allocCount < resultCount)
allocCount *= 2;
resultList = new Delegate[allocCount];
for (int i = 0; i < invocationCount; i++)
resultList[i] = invocationList[i];
if (followList == null)
{
resultList[invocationCount] = dFollow;
}
else
{
for (int i = 0; i < followCount; i++)
resultList[invocationCount + i] = followList[i];
}
}
return NewMulticastDelegate(resultList, resultCount, true);
}
}
private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount)
{
Delegate[] thisInvocationList = m_helperObject as Delegate[];
int allocCount = thisInvocationList.Length;
while (allocCount / 2 >= invocationCount - deleteCount)
allocCount /= 2;
Delegate[] newInvocationList = new Delegate[allocCount];
for (int i = 0; i < deleteIndex; i++)
newInvocationList[i] = invocationList[i];
for (int i = deleteIndex + deleteCount; i < invocationCount; i++)
newInvocationList[i - deleteCount] = invocationList[i];
return newInvocationList;
}
private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count)
{
for (int i = 0; i < count; i++)
{
if (!(a[start + i].Equals(b[i])))
return false;
}
return true;
}
// This method currently looks backward on the invocation list
// for an element that has Delegate based equality with value. (Doesn't
// look at the invocation list.) If this is found we remove it from
// this list and return a new delegate. If its not found a copy of the
// current list is returned.
protected virtual Delegate RemoveImpl(Delegate d)
{
// There is a special case were we are removing using a delegate as
// the value we need to check for this case
//
MulticastDelegate v = d as MulticastDelegate;
if (v == null)
return this;
if (v.m_helperObject as Delegate[] == null)
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
// they are both not real Multicast
if (this.Equals(d))
return null;
}
else
{
int invocationCount = (int)m_extraFunctionPointerOrData;
for (int i = invocationCount; --i >= 0;)
{
if (d.Equals(invocationList[i]))
{
if (invocationCount == 2)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[1 - i];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1);
return NewMulticastDelegate(list, invocationCount - 1, true);
}
}
}
}
}
else
{
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList != null)
{
int invocationCount = (int)m_extraFunctionPointerOrData;
int vInvocationCount = (int)v.m_extraFunctionPointerOrData;
for (int i = invocationCount - vInvocationCount; i >= 0; i--)
{
if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount))
{
if (invocationCount - vInvocationCount == 0)
{
// Special case - no values left
return null;
}
else if (invocationCount - vInvocationCount == 1)
{
// Special case - only one value left, either at the beginning or the end
return invocationList[i != 0 ? 0 : invocationCount - 1];
}
else
{
Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount);
return NewMulticastDelegate(list, invocationCount - vInvocationCount, true);
}
}
}
}
}
return this;
}
public virtual Delegate[] GetInvocationList()
{
Delegate[] del;
Delegate[] invocationList = m_helperObject as Delegate[];
if (invocationList == null)
{
del = new Delegate[1];
del[0] = this;
}
else
{
// Create an array of delegate copies and each
// element into the array
int invocationCount = (int)m_extraFunctionPointerOrData;
del = new Delegate[invocationCount];
for (int i = 0; i < del.Length; i++)
del[i] = invocationList[i];
}
return del;
}
public MethodInfo Method
{
get
{
return GetMethodImpl();
}
}
protected virtual MethodInfo GetMethodImpl()
{
return RuntimeAugments.Callbacks.GetDelegateMethod(this);
}
public override bool Equals(object obj)
{
// It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this
// therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave
// correctly, we'll just throw here.
throw new PlatformNotSupportedException();
}
// Force inline as the true/false ternary takes it above ALWAYS_INLINE size even though the asm ends up smaller
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(Delegate d1, Delegate d2)
{
// Test d2 first to allow branch elimination when inlined for null checks (== null)
// so it can become a simple test
if (d2 is null)
{
// return true/false not the test result https://github.com/dotnet/coreclr/issues/914
return (d1 is null) ? true : false;
}
return ReferenceEquals(d2, d1) ? true : d2.Equals((object)d1);
}
public static bool operator !=(Delegate d1, Delegate d2)
{
// Test d2 first to allow branch elimination when inlined for not null checks (!= null)
// so it can become a simple test
if (d2 is null)
{
// return true/false not the test result https://github.com/dotnet/coreclr/issues/914
return (d1 is null) ? false : true;
}
return ReferenceEquals(d2, d1) ? false : !d2.Equals(d1);
}
public object Target
{
get
{
// Multi-cast delegates return the Target of the last delegate in the list
if (m_functionPointer == GetThunk(MulticastThunk))
{
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
return invocationList[invocationCount - 1].Target;
}
// Closed static delegates place a value in m_helperObject that they pass to the target method.
if (m_functionPointer == GetThunk(ClosedStaticThunk) ||
m_functionPointer == GetThunk(ClosedInstanceThunkOverGenericMethod) ||
m_functionPointer == GetThunk(ObjectArrayThunk))
return m_helperObject;
// Other non-closed thunks can be identified as the m_firstParameter field points at this.
if (object.ReferenceEquals(m_firstParameter, this))
{
return null;
}
// Closed instance delegates place a value in m_firstParameter, and we've ruled out all other types of delegates
return m_firstParameter;
}
}
// V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed.
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) => CreateDelegate(type, firstArgument, method, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, firstArgument, method, throwOnBindFailure);
// V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed.
public static Delegate CreateDelegate(Type type, MethodInfo method) => CreateDelegate(type, method, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, method, throwOnBindFailure);
// V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed.
public static Delegate CreateDelegate(Type type, object target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure);
// V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed.
public static Delegate CreateDelegate(Type type, Type target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true);
public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure);
public virtual object Clone()
{
return MemberwiseClone();
}
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new PlatformNotSupportedException(SR.Serialization_DelegatesNotSupported);
}
internal bool IsOpenStatic
{
get
{
return GetThunk(OpenStaticThunk) == m_functionPointer;
}
}
internal static bool InternalEqualTypes(object a, object b)
{
return a.EETypePtr == b.EETypePtr;
}
// Returns a new delegate of the specified type whose implementation is provied by the
// provided delegate.
internal static Delegate CreateObjectArrayDelegate(Type t, Func<object[], object> handler)
{
EETypePtr delegateEEType;
if (!t.TryGetEEType(out delegateEEType))
{
throw new InvalidOperationException();
}
if (!delegateEEType.IsDefType || delegateEEType.IsGenericTypeDefinition)
{
throw new InvalidOperationException();
}
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
IntPtr objArrayThunk = del.GetThunk(Delegate.ObjectArrayThunk);
if (objArrayThunk == IntPtr.Zero)
{
throw new InvalidOperationException();
}
del.m_helperObject = handler;
del.m_functionPointer = objArrayThunk;
del.m_firstParameter = del;
return del;
}
//
// Internal (and quite unsafe) helper to create delegates of an arbitrary type. This is used to support Reflection invoke.
//
// Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of
// this code customized for each delegate type.
//
internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, object thisObject, bool isStatic, bool isOpen)
{
Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType));
// What? No constructor call? That's right, and it's not an oversight. All "construction" work happens in
// the Initialize() methods. This helper has a hard dependency on this invariant.
if (isStatic)
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenStaticThunk);
del.InitializeOpenStaticThunk(null, ldftnResult, thunk);
}
else
{
IntPtr thunk = del.GetThunk(Delegate.ClosedStaticThunk);
del.InitializeClosedStaticThunk(thisObject, ldftnResult, thunk);
}
}
else
{
if (isOpen)
{
IntPtr thunk = del.GetThunk(Delegate.OpenInstanceThunk);
del.InitializeOpenInstanceThunkDynamic(ldftnResult, thunk);
}
else
{
del.InitializeClosedInstanceWithoutNullCheck(thisObject, ldftnResult);
}
}
return del;
}
private string GetTargetMethodsDescriptionForDebugger()
{
if (m_functionPointer == GetThunk(MulticastThunk))
{
// Multi-cast delegates return the Target of the last delegate in the list
Delegate[] invocationList = (Delegate[])m_helperObject;
int invocationCount = (int)m_extraFunctionPointerOrData;
StringBuilder builder = new StringBuilder();
for (int c = 0; c < invocationCount; c++)
{
if (c != 0)
builder.Append(", ");
builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger());
}
return builder.ToString();
}
else
{
RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate;
IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _);
if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer))
{
return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate);
}
else
{
unsafe
{
GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer);
return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate);
}
}
}
}
private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate)
{
// This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer
throw new NotSupportedException();
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Diagnostics;
namespace Trinity.Core.Lib
{
#pragma warning disable 0420
/// <summary>
/// RWULock: Tri-state lock
/// Mutual table:
///
/// +---------+--------+--------+--------+
/// |Enter/St.|Read |Upgrade |Write |
/// +---------+--------+--------+--------+
/// |Reader |Enter |Enter |Block |
/// +---------+--------+--------+--------+
/// |Upgrader |Enter |Block |N/A |
/// +---------+--------+--------+--------+
/// |Writer |Block |N/A |N/A |
/// +---------+--------+--------+--------+
///
/// Write state can only be entered from Upgrade state. So Writer cannot meet Write status.
///
/// ReaderWriterUpgrader lock features similar interfaces to ReaderWriterLockSlim
/// </summary>
class ReadWriteLock
{
private volatile int updateLock = 0;
private volatile int rwLock = 0;
internal const int COUNTER_THRESHOLD_1 = 20000;
internal const int COUNTER_THRESHOLD_2 = COUNTER_THRESHOLD_1 + 20;
internal const int TIMEOUT_THRESHOLD = COUNTER_THRESHOLD_2 + 2000;
public void EnterReadLock()
{
RdLock_Start:
if ((Interlocked.Add(ref rwLock, 2) & 1) != 0)
{
Interlocked.Add(ref rwLock, -2);
int counter = 0;
while (true)
{
if ((rwLock & 1) == 0)
goto RdLock_Start;
++counter;
if (counter < COUNTER_THRESHOLD_1)
continue;
if (counter < COUNTER_THRESHOLD_2)
Thread.Sleep(0);
else
{
if (TrinityConfig.RWTimeout && counter > TIMEOUT_THRESHOLD)
{
#pragma warning disable 618
int thread_id = AppDomain.GetCurrentThreadId();
#pragma warning restore 618
int managed_thread_id = Thread.CurrentThread.ManagedThreadId;
Trace.TraceWarning("Thread id: {0}, managed thread id: {1}, it takes too long to enter the read lock.", thread_id, managed_thread_id);
throw new InvalidOperationException("EnterReadLock timeout, thread id: " + thread_id + ", managed thread id: " + managed_thread_id + ".");
}
Thread.Sleep(1);
}
}
}
}
public void EnterReadLockAggressively()
{
if ((Interlocked.Add(ref rwLock, 2) & 1) != 0)
{
int counter = 0;
while (true)
{
if ((rwLock & 1) == 0)
break;
++counter;
if (counter < COUNTER_THRESHOLD_1)
continue;
if (counter < COUNTER_THRESHOLD_2)
Thread.Sleep(0);
else
Thread.Sleep(1);
}
}
}
public bool TryEnterReadLock()
{
if ((Interlocked.Add(ref rwLock, 2) & 1) != 0)
{
Interlocked.Add(ref rwLock, -2);
return false;
}
return true;
}
public bool TryEnterReadLock(int retry)
{
int counter = retry;
RdLock_Start:
if ((Interlocked.Add(ref rwLock, 2) & 1) != 0)
{
Interlocked.Add(ref rwLock, -2);
while (true)
{
if (--counter < 0)
return false;
if ((rwLock & 1) == 0)
goto RdLock_Start;
Thread.Sleep(1);
}
}
return true;
}
public void ExitReadLock()
{
Interlocked.Add(ref rwLock, -2);
}
public void EnterWriteLock()
{
EnterUpgradeState();
EnterWriteState();
}
public void ExitWriteLock()
{
Interlocked.Decrement(ref rwLock);
updateLock = 0;
}
private void EnterWriteState()
{
WriteLock_Start:
if (1 == Interlocked.Increment(ref rwLock))//Clean entrance, no readers
{
return;
}
int counter = 0;
while (true)
{
if (rwLock == 1)
break;
++counter;
if (counter < COUNTER_THRESHOLD_1)
{
Thread.Sleep(0);
continue;
}
Interlocked.Decrement(ref rwLock);
Thread.Sleep(1);
goto WriteLock_Start;
}
}
private void ExitWriteState()
{
Interlocked.Decrement(ref rwLock);
}
private void EnterUpgradeState()
{
if (Interlocked.CompareExchange(ref updateLock, 1, 0) != 0)
{
int counter = 0;
while (true)
{
if (updateLock == 0 && Interlocked.CompareExchange(ref updateLock, 1, 0) == 0)
break;
++counter;
if (counter < COUNTER_THRESHOLD_1)
continue;
if (counter < COUNTER_THRESHOLD_2)
Thread.Sleep(0);
else
{
if (TrinityConfig.RWTimeout && counter > TIMEOUT_THRESHOLD)
{
#pragma warning disable 618
int thread_id = AppDomain.GetCurrentThreadId();
#pragma warning restore 618
int managed_thread_id = Thread.CurrentThread.ManagedThreadId;
Trace.TraceWarning("Thread id: {0}, managed thread id: {1}, it takes too long to enter the read lock.", thread_id, managed_thread_id);
throw new InvalidOperationException("EnterUpgradeState timeout, thread id: " + thread_id + ", managed thread id: " + managed_thread_id + ".");
}
Thread.Sleep(1);
}
}
}
}
private void ExitUpgradeState()
{
Thread.MemoryBarrier();
updateLock = 0;
}
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System;
using System.Text;
namespace Contoso.Text.Html
{
/// <summary>
/// HtmlStringReader
/// </summary>
public class HtmlStringReader : IDisposable
{
private string _text;
private int _textLength;
private StringBuilder _b;
private int _startIndex = 0;
private int _valueStartIndex;
private int _valueEndIndex;
private int _openIndex = -1;
private int _closeIndex;
private string _lastParseElementName;
/// <summary>
/// Initializes a new instance of the <see cref="HtmlAdvancingTextProcess"/> class.
/// </summary>
/// <param name="text">The text.</param>
public HtmlStringReader(string text)
: this(text, new StringBuilder()) { }
/// <summary>
/// Initializes a new instance of the <see cref="HtmlAdvancingTextProcess"/> class.
/// </summary>
/// <param name="text">The text.</param>
/// <param name="textBuilder">The text builder.</param>
public HtmlStringReader(string text, StringBuilder b)
{
_text = text;
_textLength = text.Length;
_b = b;
}
/// <summary>
/// Appends the specified value.
/// </summary>
/// <param name="value">The value.</param>
public void Append(string value)
{
_b.Append(value);
}
/// <summary>
/// Gets the found element.
/// </summary>
/// <returns></returns>
public string GetFoundElement()
{
if (_openIndex == -1)
throw new InvalidOperationException();
// find matching > to the open anchor tag
int openCloseBraceIndex = _text.IndexOf(">", _openIndex);
if (openCloseBraceIndex == -1)
openCloseBraceIndex = _textLength;
// extract tag
return _text.Substring(_openIndex, openCloseBraceIndex - _openIndex) + ">";
}
/// <summary>
/// Determines whether [is attribute in element] [the specified element].
/// </summary>
/// <param name="element">The element.</param>
/// <param name="attribute">The attribute.</param>
/// <returns>
/// <c>true</c> if [is attribute in element] [the specified element]; otherwise, <c>false</c>.
/// </returns>
public bool IsAttributeInElement(string element, string attribute)
{
int attributeLength = attribute.Length;
int targetStartKey = 0;
// if the tag contains the text "attribute"
int targetAttribIndex;
while ((targetAttribIndex = element.IndexOf(attribute, targetStartKey, StringComparison.OrdinalIgnoreCase)) > -1)
// determine whether "attribute" is inside of a string
if (((element.Substring(0, targetAttribIndex).Length - element.Substring(0, targetAttribIndex).Replace("\"", string.Empty).Length) % 2) == 0)
// "attribute" is not inside of a string -- attribute exists
return true;
else
// skip "attribute" text and look for next match
targetStartKey = targetAttribIndex + attributeLength;
return false;
}
/// <summary>
/// Indexes the of.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public int IndexOf(string value)
{
return _text.IndexOf(value, _startIndex, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Sets the search value.
/// </summary>
/// <param name="valueStartIndex">Start index of the value.</param>
/// <param name="valueEndIndex">End index of the value.</param>
public void SetSearchValue(int valueStartIndex, int valueEndIndex)
{
_valueStartIndex = valueStartIndex;
_valueEndIndex = valueEndIndex;
}
/// <summary>
/// Searches for any element.
/// </summary>
/// <returns></returns>
public bool SearchIfInElement()
{
_lastParseElementName = null;
// look for the closest open tag (<) to the left of the url
_openIndex = _text.LastIndexOf("<", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase);
// open tag found
if (_openIndex > -1)
{
// find the corresponding close tag ([</][/>]) to the left of the url
_closeIndex = _text.LastIndexOf("</", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
int close2Index = _text.LastIndexOf("/>", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
if ((close2Index > -1) && (close2Index < _closeIndex))
_closeIndex = close2Index;
// false:close tag found -- url is not enclosed in an anchor tag
// true:close tag not found -- url is already linked (enclosed in an anchor tag)
return (_closeIndex == -1);
}
// open tag not found
else
return false;
}
/// <summary>
/// Searches for element.
/// </summary>
/// <param name="elementName">Name of the element.</param>
/// <returns></returns>
public bool SearchIfInElement(string elementName)
{
_lastParseElementName = elementName.ToLowerInvariant();
// look for the closest open element tag (<a>) to the left of the url
_openIndex = _text.LastIndexOf("<" + elementName + " ", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase);
// open tag found
if (_openIndex > -1)
{
// find the corresponding close tag (</a>) to the left of the url
_closeIndex = _text.LastIndexOf("</" + elementName + ">", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase);
// false:close tag found -- value is not enclosed in an element tag
// true:close tag not found -- value is already elemented (enclosed in an anchor tag)
return (_closeIndex == -1);
}
// open tag not found
else
return false;
}
#region Stream
/// <summary>
/// Streams to end of first element.
/// </summary>
public void StreamToEndOfFirstElement()
{
// find the close tag (>) to the left of the url
int closeIndex = _text.IndexOf(">", _valueEndIndex, StringComparison.OrdinalIgnoreCase);
if (closeIndex > -1)
{
_b.Append(_text.Substring(_startIndex, closeIndex - _startIndex + 1));
Advance(closeIndex + 1);
}
else
{
_b.Append(_text.Substring(_startIndex));
Advance(_textLength);
}
}
/// <summary>
/// Streams the found element fragment.
/// </summary>
/// <param name="elementBuilder">The element builder.</param>
public void StreamFoundElementFragment(Func<string, string> elementBuilder)
{
if (_openIndex == -1)
throw new InvalidOperationException();
int elementOffset = _lastParseElementName.Length + 2;
// look for closing anchor tag
int closeIndex = _text.IndexOf("</" + _lastParseElementName + ">", _valueEndIndex, StringComparison.OrdinalIgnoreCase);
// close anchor tag found
if (closeIndex > -1)
{
closeIndex += elementOffset;
_b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, closeIndex - _openIndex - elementOffset - 1)));
Advance(closeIndex + 1);
}
// close anchor tag not found
else
{
Advance(_textLength);
_b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, _startIndex - _openIndex - elementOffset)));
}
}
/// <summary>
/// Streams to end of value.
/// </summary>
public void StreamToEndOfValue()
{
_b.Append(_text.Substring(_startIndex, _valueStartIndex - _startIndex));
Advance(_valueEndIndex + 1);
}
/// <summary>
/// Advances the specified index.
/// </summary>
/// <param name="index">The index.</param>
protected void Advance(int index)
{
_startIndex = index;
_openIndex = -1;
}
/// <summary>
/// Streams to begin element.
/// </summary>
public void StreamToBeginElement()
{
if (_openIndex == -1)
throw new InvalidOperationException();
// stream text to left of url
_b.Append(_text.Substring(_startIndex, _openIndex - _startIndex));
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override string ToString()
{
// append trailing text, if any
if (_startIndex < _textLength)
{
_b.Append(_text.Substring(_startIndex));
Advance(_textLength);
}
return _b.ToString();
}
#endregion
public void Dispose()
{
}
}
}
| |
using System.Diagnostics;
namespace Lucene.Net.Util.Automaton
{
/*
* 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.
*/
// The following code was generated with the moman/finenight pkg
// this package is available under the MIT License, see NOTICE.txt
// for more details.
using ParametricDescription = Lucene.Net.Util.Automaton.LevenshteinAutomata.ParametricDescription;
/// <summary>
/// Parametric description for generating a Levenshtein automaton of degree 2 </summary>
internal class Lev2ParametricDescription : ParametricDescription
{
internal override int Transition(int absState, int position, int vector)
{
// null absState should never be passed in
Debug.Assert(absState != -1);
// decode absState -> state, offset
int state = absState / (m_w + 1);
int offset = absState % (m_w + 1);
Debug.Assert(offset >= 0);
if (position == m_w)
{
if (state < 3)
{
int loc = vector * 3 + state;
offset += Unpack(offsetIncrs0, loc, 1);
state = Unpack(toStates0, loc, 2) - 1;
}
}
else if (position == m_w - 1)
{
if (state < 5)
{
int loc = vector * 5 + state;
offset += Unpack(offsetIncrs1, loc, 1);
state = Unpack(toStates1, loc, 3) - 1;
}
}
else if (position == m_w - 2)
{
if (state < 11)
{
int loc = vector * 11 + state;
offset += Unpack(offsetIncrs2, loc, 2);
state = Unpack(toStates2, loc, 4) - 1;
}
}
else if (position == m_w - 3)
{
if (state < 21)
{
int loc = vector * 21 + state;
offset += Unpack(offsetIncrs3, loc, 2);
state = Unpack(toStates3, loc, 5) - 1;
}
}
else if (position == m_w - 4)
{
if (state < 30)
{
int loc = vector * 30 + state;
offset += Unpack(offsetIncrs4, loc, 3);
state = Unpack(toStates4, loc, 5) - 1;
}
}
else
{
if (state < 30)
{
int loc = vector * 30 + state;
offset += Unpack(offsetIncrs5, loc, 3);
state = Unpack(toStates5, loc, 5) - 1;
}
}
if (state == -1)
{
// null state
return -1;
}
else
{
// translate back to abs
return state * (m_w + 1) + offset;
}
}
// 1 vectors; 3 states per vector; array length = 3
private static readonly long[] toStates0 = new long[] { 0x23L }; //2 bits per value
private static readonly long[] offsetIncrs0 = new long[] { 0x0L }; //1 bits per value
// 2 vectors; 5 states per vector; array length = 10
private static readonly long[] toStates1 = new long[] { 0x13688b44L }; //3 bits per value
private static readonly long[] offsetIncrs1 = new long[] { 0x3e0L }; //1 bits per value
// 4 vectors; 11 states per vector; array length = 44
private static readonly long[] toStates2 = new long[] {
0x26a09a0a0520a504L, 0x2323523321a260a2L, 0x354235543213L
}; //4 bits per value
private static readonly long[] offsetIncrs2 = new long[] {
0x5555520280000800L, 0x555555L
}; //2 bits per value
// 8 vectors; 21 states per vector; array length = 168
private static readonly long[] toStates3 = new long[] {
0x380e014a051404L, 0xe28245009451140L, unchecked((long)0x8a26880098a6268cL), 0x180a288ca0246213L,
0x494053284a1080e1L, 0x510265a89c311940L, 0x4218c41188a6509cL, 0x6340c4211c4710dL,
unchecked((long)0xa168398471882a12L), 0x104c841c683a0425L, 0x3294472904351483L, unchecked((long)0xe6290620a84a20d0L),
0x1441a0ea2896a4a0L, 0x32L
}; //5 bits per value
private static readonly long[] offsetIncrs3 = new long[] {
0x33300230c0000800L, 0x220ca080a00fc330L, 0x555555f832823380L, 0x5555555555555555L,
0x5555555555555555L, 0x5555L
}; //2 bits per value
// 16 vectors; 30 states per vector; array length = 480
private static readonly long[] toStates4 = new long[] {
0x380e014a051404L, 0xaa015452940L, 0x55014501000000L, 0x1843ddc771085c07L,
0x7141200040108405L, 0x52b44004c5313460L, 0x401080200063115cL, unchecked((long)0x85314c4d181c5048L),
0x1440190a3e5c7828L, 0x28a232809100a21L, unchecked((long)0xa028ca2a84203846L), unchecked((long)0xca0240010800108aL),
unchecked((long)0xc7b4205c1580a508L), 0x1021090251846b6L, 0x4cb513862328090L, 0x210863128ca2b8a2L,
0x4e188ca024402940L, 0xa6b6c7c520532d4L, unchecked((long)0x8c41101451150219L), unchecked((long)0xa0c4211c4710d421L),
0x2108421094e15063L, unchecked((long)0x8f13c43708631044L), 0x18274d908c611631L, 0x1cc238c411098263L,
0x450e3a1d0212d0b4L, 0x31050242048108c6L, 0xfa318b42d07308eL, unchecked((long)0xa8865182356907c6L),
0x1ca410d4520c4140L, 0x2954e13883a0ca51L, 0x3714831044229442L, unchecked((long)0x93946116b58f2c84L),
unchecked((long)0xc41109a5631a574dL), 0x1d4512d4941cc520L, 0x52848294c643883aL, unchecked((long)0xb525073148310502L),
unchecked((long)0xa5356939460f7358L), 0x409ca651L
}; //5 bits per value
private static readonly long[] offsetIncrs4 = new long[] {
0x20c0600000010000L, 0x2000040000000001L, 0x209204a40209L, 0x301b6c0618018618L,
0x207206186000186cL, 0x1200061b8e06dc0L, 0x480492080612010L, unchecked((long)0xa20204a040048000L),
0x1061a0000129124L, 0x1848349b680612L, unchecked((long)0xd26da0204a041868L), 0x2492492492496128L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x24924924L
}; //3 bits per value
// 32 vectors; 30 states per vector; array length = 960
private static readonly long[] toStates5 = new long[] {
0x380e014a051404L, 0xaa015452940L, unchecked((long)0x8052814501000000L), unchecked((long)0xb80a515450000e03L),
0x5140410842108426L, 0x71dc421701c01540L, 0x100421014610f7L, unchecked((long)0x85c0700550145010L),
unchecked((long)0x94a271843ddc7710L), 0x1346071412108a22L, 0x3115c52b44004c53L, unchecked((long)0xc504840108020006L),
0x54d1001314c4d181L, 0x9081204239c4a71L, 0x14c5313460714124L, 0x51006428f971e0a2L,
0x4d181c5048402884L, 0xa3e5c782885314cL, 0x2809409482a8a239L, 0x2a84203846028a23L,
0x10800108aa028caL, 0xe1180a288ca0240L, unchecked((long)0x98c6b80e3294a108L), 0x2942328091098c10L,
0x11adb1ed08170560L, unchecked((long)0xa024004084240946L), 0x7b4205c1580a508cL, unchecked((long)0xa8c2968c71846b6cL),
0x4cb5138623280910L, 0x10863128ca2b8a20L, unchecked((long)0xe188ca0244029402L), 0x4e3294e288132d44L,
unchecked((long)0x809409ad1218c39cL), unchecked((long)0xf14814cb51386232L), 0x514454086429adb1L, 0x32d44e188ca02440L,
unchecked((long)0x8c390a6b6c7c5205L), unchecked((long)0xd4218c41409cd2aaL), 0x5063a0c4211c4710L, 0x10442108421094e1L,
0x31084711c4350863L, unchecked((long)0xbdef7bddf05918f2L), unchecked((long)0xc4f10dc218c41ef7L), 0x9d3642318458c63L,
0x70863104426098c6L, 0x8c6116318f13c43L, 0x41ef75dd6b5de4d9L, unchecked((long)0xd0212d0b41cc238cL),
0x2048108c6450e3a1L, 0x42d07308e3105024L, unchecked((long)0xdb591938f274084bL), unchecked((long)0xc238c41f77deefbbL),
0x1f183e8c62d0b41cL, 0x502a2194608d5a4L, unchecked((long)0xa318b42d07308e31L), unchecked((long)0xed675db56907c60fL),
unchecked((long)0xa410d4520c41f773L), 0x54e13883a0ca511cL, 0x1483104422944229L, 0x20f2329447290435L,
0x1ef6f7ef6f7df05cL, unchecked((long)0xad63cb210dc520c4L), 0x58c695d364e51845L, unchecked((long)0xc843714831044269L),
unchecked((long)0xe4d93946116b58f2L), 0x520c41ef717d6b17L, unchecked((long)0x83a1d4512d4941ccL), 0x50252848294c6438L,
0x144b525073148310L, unchecked((long)0xefaf7b591c20f275L), unchecked((long)0x941cc520c41f777bL), unchecked((long)0xd5a4e5183dcd62d4L),
0x4831050272994694L, 0x460f7358b5250731L, unchecked((long)0xf779bd6717b56939L)
}; //5 bits per value
private static readonly long[] offsetIncrs5 = new long[] {
0x20c0600000010000L, 0x40000000001L, 0xb6db6d4830180L, 0x4812900824800010L,
0x2092000040000082L, 0x618000b659254a40L, unchecked((long)0x86c301b6c0618018L), unchecked((long)0xdb01860061860001L),
unchecked((long)0x81861800075baed6L), 0x186e381b70081cL, unchecked((long)0xe56dc02072061860L), 0x61201001200075b8L,
0x480000480492080L, 0x52b5248201848040L, unchecked((long)0x880812810012000bL), 0x4004800004a4492L,
0xb529124a20204aL, 0x49b68061201061a0L, unchecked((long)0x8480418680018483L), 0x1a000752ad26da01L,
0x4a349b6808128106L, unchecked((long)0xa0204a0418680018L), 0x492492497528d26dL, 0x2492492492492492L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L
}; //3 bits per value
// state map
// 0 -> [(0, 0)]
// 1 -> [(0, 2)]
// 2 -> [(0, 1)]
// 3 -> [(0, 1), (1, 1)]
// 4 -> [(0, 2), (1, 2)]
// 5 -> [(0, 2), (2, 1)]
// 6 -> [(0, 1), (2, 2)]
// 7 -> [(0, 2), (2, 2)]
// 8 -> [(0, 1), (1, 1), (2, 1)]
// 9 -> [(0, 2), (1, 2), (2, 2)]
// 10 -> [(0, 1), (2, 1)]
// 11 -> [(0, 2), (3, 2)]
// 12 -> [(0, 2), (1, 2), (3, 2)]
// 13 -> [(0, 2), (1, 2), (2, 2), (3, 2)]
// 14 -> [(0, 1), (2, 2), (3, 2)]
// 15 -> [(0, 2), (3, 1)]
// 16 -> [(0, 1), (3, 2)]
// 17 -> [(0, 1), (1, 1), (3, 2)]
// 18 -> [(0, 2), (1, 2), (3, 1)]
// 19 -> [(0, 2), (2, 2), (3, 2)]
// 20 -> [(0, 2), (2, 1), (3, 1)]
// 21 -> [(0, 2), (2, 1), (4, 2)]
// 22 -> [(0, 2), (1, 2), (4, 2)]
// 23 -> [(0, 2), (1, 2), (3, 2), (4, 2)]
// 24 -> [(0, 2), (2, 2), (3, 2), (4, 2)]
// 25 -> [(0, 2), (3, 2), (4, 2)]
// 26 -> [(0, 2), (1, 2), (2, 2), (4, 2)]
// 27 -> [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2)]
// 28 -> [(0, 2), (4, 2)]
// 29 -> [(0, 2), (2, 2), (4, 2)]
public Lev2ParametricDescription(int w)
: base(w, 2, new int[] { 0, 2, 1, 0, 1, -1, 0, 0, -1, 0, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })
{
}
}
}
| |
using System;
using System.Collections.Generic;
using ALinq.Mapping;
namespace ALinq.SqlClient
{
internal class SqlReorderer
{
// Fields
private SqlFactory sql;
private ITypeSystemProvider typeProvider;
// Methods
internal SqlReorderer(ITypeSystemProvider typeProvider, SqlFactory sqlFactory)
{
this.typeProvider = typeProvider;
this.sql = sqlFactory;
}
internal SqlNode Reorder(SqlNode node)
{
return new Visitor(this.typeProvider, this.sql).Visit(node);
}
// Nested Types
internal class SqlGatherColumnsProduced
{
// Methods
internal static List<SqlColumn> GatherColumns(SqlSource source)
{
List<SqlColumn> columns = new List<SqlColumn>();
new Visitor(columns).Visit(source);
return columns;
}
// Nested Types
private class Visitor : SqlVisitor
{
// Fields
private List<SqlColumn> columns;
// Methods
internal Visitor(List<SqlColumn> columns)
{
this.columns = columns;
}
internal override SqlSelect VisitSelect(SqlSelect select)
{
foreach (SqlColumn column in select.Row.Columns)
{
this.columns.Add(column);
}
return select;
}
internal override SqlNode VisitUnion(SqlUnion su)
{
return su;
}
}
}
private class Visitor : SqlVisitor
{
// Fields
private bool addPrimaryKeys;
private SqlAggregateChecker aggregateChecker;
private SqlSelect currentSelect;
private List<SqlOrderExpression> orders = new List<SqlOrderExpression>();
private List<SqlOrderExpression> rowNumberOrders;
private SqlFactory sql;
private bool topSelect = true;
private ITypeSystemProvider typeProvider;
// Methods
internal Visitor(ITypeSystemProvider typeProvider, SqlFactory sqlFactory)
{
this.typeProvider = typeProvider;
this.sql = sqlFactory;
this.aggregateChecker = new SqlAggregateChecker();
}
private static bool IsTableAlias(SqlSource src)
{
SqlAlias alias = src as SqlAlias;
return ((alias != null) && (alias.Node is SqlTable));
}
private void PrependOrderExpressions(IEnumerable<SqlOrderExpression> exprs)
{
if (exprs != null)
{
this.Orders.InsertRange(0, exprs);
}
}
private void PushDown(SqlColumn column)
{
SqlSelect node = new SqlSelect(new SqlNop(column.ClrType, column.SqlType, column.SourceExpression),
this.currentSelect.From, this.currentSelect.SourceExpression);
this.currentSelect.From = new SqlAlias(node);
node.Row.Columns.Add(column);
}
internal override SqlAlias VisitAlias(SqlAlias a)
{
if (!IsTableAlias(a) || !this.addPrimaryKeys)
{
return base.VisitAlias(a);
}
SqlTable node = (SqlTable) a.Node;
List<SqlOrderExpression> exprs = new List<SqlOrderExpression>();
foreach (MetaDataMember member in node.RowType.IdentityMembers)
{
string mappedName = member.MappedName;
SqlColumn item = node.Find(mappedName);
if (item == null)
{
item = new SqlColumn(member.MemberAccessor.Type,
this.typeProvider.From(member.MemberAccessor.Type), mappedName, member,
null, node.SourceExpression);
item.Alias = a;
node.Columns.Add(item);
}
exprs.Add(new SqlOrderExpression(SqlOrderType.Ascending, new SqlColumnRef(item)));
}
this.PrependOrderExpressions(exprs);
return a;
}
internal override SqlSource VisitJoin(SqlJoin join)
{
this.Visit(join.Left);
List<SqlOrderExpression> orders = this.orders;
this.orders = null;
this.Visit(join.Right);
this.PrependOrderExpressions(orders);
return join;
}
internal override SqlRowNumber VisitRowNumber(SqlRowNumber rowNumber)
{
if (rowNumber.OrderBy.Count <= 0)
{
SqlDuplicator duplicator = new SqlDuplicator(true);
List<SqlOrderExpression> list = new List<SqlOrderExpression>();
List<SqlOrderExpression> list2 = new List<SqlOrderExpression>();
if ((this.rowNumberOrders != null) && (this.rowNumberOrders.Count != 0))
{
list2 = new List<SqlOrderExpression>(this.rowNumberOrders);
}
else if (this.orders != null)
{
list2 = new List<SqlOrderExpression>(this.orders);
}
foreach (SqlOrderExpression expression in list2)
{
if (!expression.Expression.IsConstantColumn)
{
list.Add(expression);
if (this.rowNumberOrders != null)
{
this.rowNumberOrders.Remove(expression);
}
if (this.orders != null)
{
this.orders.Remove(expression);
}
}
}
rowNumber.OrderBy.Clear();
if (list.Count == 0)
{
foreach (
SqlColumn column in
SqlReorderer.SqlGatherColumnsProduced.GatherColumns(this.currentSelect.From))
{
if (column.Expression.SqlType.IsOrderable)
{
list.Add(new SqlOrderExpression(SqlOrderType.Ascending, new SqlColumnRef(column)));
}
}
if (list.Count == 0)
{
var column2 = new SqlColumn("rowNumberOrder",
sql.Value(typeof (int),
typeProvider.From(typeof (int)), 1,
false, rowNumber.SourceExpression));
this.PushDown(column2);
list.Add(new SqlOrderExpression(SqlOrderType.Ascending, new SqlColumnRef(column2)));
}
}
foreach (SqlOrderExpression expression2 in list)
{
rowNumber.OrderBy.Add(new SqlOrderExpression(expression2.OrderType,
(SqlExpression)
duplicator.Duplicate(expression2.Expression)));
}
}
return rowNumber;
}
internal override SqlSelect VisitSelect(SqlSelect select)
{
bool topSelect = this.topSelect;
bool addPrimaryKeys = this.addPrimaryKeys;
SqlSelect currentSelect = this.currentSelect;
this.currentSelect = select;
if (select.OrderingType == SqlOrderingType.Always)
{
this.addPrimaryKeys = true;
}
this.topSelect = false;
if (select.GroupBy.Count > 0)
{
this.Visit(select.From);
this.orders = null;
}
else
{
this.Visit(select.From);
}
if (select.OrderBy.Count > 0)
{
this.PrependOrderExpressions(select.OrderBy);
}
List<SqlOrderExpression> orders = this.orders;
this.orders = null;
this.rowNumberOrders = orders;
select.Where = this.VisitExpression(select.Where);
int num = 0;
int count = select.GroupBy.Count;
while (num < count)
{
select.GroupBy[num] = this.VisitExpression(select.GroupBy[num]);
num++;
}
select.Having = this.VisitExpression(select.Having);
int num3 = 0;
int num4 = select.OrderBy.Count;
while (num3 < num4)
{
select.OrderBy[num3].Expression = this.VisitExpression(select.OrderBy[num3].Expression);
num3++;
}
select.Top = this.VisitExpression(select.Top);
select.Selection = this.VisitExpression(select.Selection);
select.Row = (SqlRow) this.Visit(select.Row);
this.topSelect = topSelect;
this.addPrimaryKeys = addPrimaryKeys;
this.orders = orders;
if (select.OrderingType == SqlOrderingType.Blocked)
{
this.orders = null;
}
select.OrderBy.Clear();
SqlRowNumberChecker checker = new SqlRowNumberChecker();
if (checker.HasRowNumber(select) && (checker.RowNumberColumn != null))
{
select.Row.Columns.Remove(checker.RowNumberColumn);
this.PushDown(checker.RowNumberColumn);
this.Orders.Add(new SqlOrderExpression(SqlOrderType.Ascending,
new SqlColumnRef(checker.RowNumberColumn)));
}
if ((this.topSelect || (select.Top != null)) &&
((select.OrderingType != SqlOrderingType.Never) && (this.orders != null)))
{
SqlDuplicator duplicator = new SqlDuplicator(true);
foreach (SqlOrderExpression expression in this.orders)
{
select.OrderBy.Add(new SqlOrderExpression(expression.OrderType,
(SqlExpression)
duplicator.Duplicate(expression.Expression)));
}
}
this.currentSelect = currentSelect;
return select;
}
internal override SqlExpression VisitSubSelect(SqlSubSelect ss)
{
List<SqlOrderExpression> orders = this.orders;
this.orders = new List<SqlOrderExpression>();
base.VisitSubSelect(ss);
this.orders = orders;
return ss;
}
internal override SqlNode VisitUnion(SqlUnion su)
{
this.orders = null;
su.Left = this.Visit(su.Left);
this.orders = null;
su.Right = this.Visit(su.Right);
this.orders = null;
return su;
}
// Properties
private List<SqlOrderExpression> Orders
{
get
{
if (this.orders == null)
{
this.orders = new List<SqlOrderExpression>();
}
return this.orders;
}
}
}
}
}
| |
/*
Based on ObjExporter.cs, this "wrapper" lets you export to .OBJ directly from the editor menu.
This should be put in your "Editor"-folder. Use by selecting the objects you want to export, and select
the appropriate menu item from "Custom->Export". Exported models are put in a folder called
"ExportedObj" in the root of your Unity-project. Textures should also be copied and placed in the
same folder. */
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
struct ObjMaterial
{
public string name;
public string textureName;
}
public class EditorObjExporter : ScriptableObject
{
private static int vertexOffset = 0;
private static int normalOffset = 0;
private static int uvOffset = 0;
//User should probably be able to change this. It is currently left as an excercise for
//the reader.
private static string targetFolder = "ExportedObj";
private static string MeshToString(MeshFilter mf, Dictionary<string, ObjMaterial> materialList)
{
Mesh m = mf.sharedMesh;
Material[] mats = mf.renderer.sharedMaterials;
StringBuilder sb = new StringBuilder();
sb.Append("g ").Append(mf.name).Append("\n");
foreach(Vector3 lv in m.vertices)
{
Vector3 wv = mf.transform.TransformPoint(lv);
//This is sort of ugly - inverting x-component since we're in
//a different coordinate system than "everyone" is "used to".
sb.Append(string.Format("v {0} {1} {2}\n",-wv.x,wv.y,wv.z));
}
sb.Append("\n");
foreach(Vector3 lv in m.normals)
{
Vector3 wv = mf.transform.TransformDirection(lv);
sb.Append(string.Format("vn {0} {1} {2}\n",-wv.x,wv.y,wv.z));
}
sb.Append("\n");
foreach(Vector3 v in m.uv)
{
sb.Append(string.Format("vt {0} {1}\n",v.x,v.y));
}
for (int material=0; material < m.subMeshCount; material ++) {
sb.Append("\n");
sb.Append("usemtl ").Append(mats[material].name).Append("\n");
sb.Append("usemap ").Append(mats[material].name).Append("\n");
//See if this material is already in the materiallist.
try
{
ObjMaterial objMaterial = new ObjMaterial();
objMaterial.name = mats[material].name;
if (mats[material].mainTexture)
objMaterial.textureName = AssetDatabase.GetAssetPath(mats[material].mainTexture);
else
objMaterial.textureName = null;
materialList.Add(objMaterial.name, objMaterial);
}
catch (ArgumentException)
{
//Already in the dictionary
}
int[] triangles = m.GetTriangles(material);
for (int i=0;i<triangles.Length;i+=3)
{
//Because we inverted the x-component, we also needed to alter the triangle winding.
sb.Append(string.Format("f {1}/{1}/{1} {0}/{0}/{0} {2}/{2}/{2}\n",
triangles[i]+1 + vertexOffset, triangles[i+1]+1 + normalOffset, triangles[i+2]+1 + uvOffset));
}
}
vertexOffset += m.vertices.Length;
normalOffset += m.normals.Length;
uvOffset += m.uv.Length;
return sb.ToString();
}
private static void Clear()
{
vertexOffset = 0;
normalOffset = 0;
uvOffset = 0;
}
private static Dictionary<string, ObjMaterial> PrepareFileWrite()
{
Clear();
return new Dictionary<string, ObjMaterial>();
}
private static void MaterialsToFile(Dictionary<string, ObjMaterial> materialList, string folder, string filename)
{
using (StreamWriter sw = new StreamWriter(folder + "/" + filename + ".mtl"))
{
foreach( KeyValuePair<string, ObjMaterial> kvp in materialList )
{
sw.Write("\n");
sw.Write("newmtl {0}\n", kvp.Key);
sw.Write("Ka 0.6 0.6 0.6\n");
sw.Write("Kd 0.6 0.6 0.6\n");
sw.Write("Ks 0.9 0.9 0.9\n");
sw.Write("d 1.0\n");
sw.Write("Ns 0.0\n");
sw.Write("illum 2\n");
if (kvp.Value.textureName != null)
{
string destinationFile = kvp.Value.textureName;
int stripIndex = destinationFile.LastIndexOf('/');//FIXME: Should be Path.PathSeparator;
if (stripIndex >= 0)
destinationFile = destinationFile.Substring(stripIndex + 1).Trim();
string relativeFile = destinationFile;
destinationFile = folder + "/" + destinationFile;
Debug.Log("Copying texture from " + kvp.Value.textureName + " to " + destinationFile);
try
{
//Copy the source file
File.Copy(kvp.Value.textureName, destinationFile);
}
catch
{
}
sw.Write("map_Kd {0}", relativeFile);
}
sw.Write("\n\n\n");
}
}
}
private static void MeshToFile(MeshFilter mf, string folder, string filename)
{
Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
sw.Write(MeshToString(mf, materialList));
}
MaterialsToFile(materialList, folder, filename);
}
private static void MeshesToFile(MeshFilter[] mf, string folder, string filename)
{
Dictionary<string, ObjMaterial> materialList = PrepareFileWrite();
using (StreamWriter sw = new StreamWriter(folder +"/" + filename + ".obj"))
{
sw.Write("mtllib ./" + filename + ".mtl\n");
for (int i = 0; i < mf.Length; i++)
{
sw.Write(MeshToString(mf[i], materialList));
}
}
MaterialsToFile(materialList, folder, filename);
}
private static bool CreateTargetFolder()
{
try
{
System.IO.Directory.CreateDirectory(targetFolder);
}
catch
{
EditorUtility.DisplayDialog("Error!", "Failed to create target folder!", "");
return false;
}
return true;
}
[MenuItem ("Custom/Export/Export all MeshFilters in selection to separate OBJs")]
static void ExportSelectionToSeparate()
{
if (!CreateTargetFolder())
return;
Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
if (selection.Length == 0)
{
EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
return;
}
int exportedObjects = 0;
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
for (int m = 0; m < meshfilter.Length; m++)
{
exportedObjects++;
MeshToFile((MeshFilter)meshfilter[m], targetFolder, selection[i].name + "_" + i + "_" + m);
}
}
if (exportedObjects > 0)
EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects", "");
else
EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
}
[MenuItem ("Custom/Export/Export whole selection to single OBJ")]
static void ExportWholeSelectionToSingle()
{
if (!CreateTargetFolder())
return;
Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
if (selection.Length == 0)
{
EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
return;
}
int exportedObjects = 0;
ArrayList mfList = new ArrayList();
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
for (int m = 0; m < meshfilter.Length; m++)
{
exportedObjects++;
mfList.Add(meshfilter[m]);
}
}
if (exportedObjects > 0)
{
MeshFilter[] mf = new MeshFilter[mfList.Count];
for (int i = 0; i < mfList.Count; i++)
{
mf[i] = (MeshFilter)mfList[i];
}
string filename = EditorApplication.currentScene + "_" + exportedObjects;
int stripIndex = filename.LastIndexOf('/');//FIXME: Should be Path.PathSeparator
if (stripIndex >= 0)
filename = filename.Substring(stripIndex + 1).Trim();
MeshesToFile(mf, targetFolder, filename);
EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects to " + filename, "");
}
else
EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
}
[MenuItem ("Custom/Export/Export each selected to single OBJ")]
static void ExportEachSelectionToSingle()
{
if (!CreateTargetFolder())
return;
Transform[] selection = Selection.GetTransforms(SelectionMode.Editable | SelectionMode.ExcludePrefab);
if (selection.Length == 0)
{
EditorUtility.DisplayDialog("No source object selected!", "Please select one or more target objects", "");
return;
}
int exportedObjects = 0;
for (int i = 0; i < selection.Length; i++)
{
Component[] meshfilter = selection[i].GetComponentsInChildren(typeof(MeshFilter));
MeshFilter[] mf = new MeshFilter[meshfilter.Length];
for (int m = 0; m < meshfilter.Length; m++)
{
exportedObjects++;
mf[m] = (MeshFilter)meshfilter[m];
}
MeshesToFile(mf, targetFolder, selection[i].name + "_" + i);
}
if (exportedObjects > 0)
{
EditorUtility.DisplayDialog("Objects exported", "Exported " + exportedObjects + " objects", "");
}
else
EditorUtility.DisplayDialog("Objects not exported", "Make sure at least some of your selected objects have mesh filters!", "");
}
}
| |
using System;
using System.Collections;
using System.Text;
using UnityEngine;
//using Microsoft.Xna.Framework;
//using Microsoft.Xna.Framework.Audio;
//using Microsoft.Xna.Framework.Content;
//using Microsoft.Xna.Framework.GamerServices;
//using Microsoft.Xna.Framework.Graphics;
//using Microsoft.Xna.Framework.Input;
//using Microsoft.Xna.Framework.Net;
//using Microsoft.Xna.Framework.Storage;
/// <summary>
/// GameState A preciser
/// </summary>
public class GameState : MonoBehaviour
{
#region Member Variables
private System.IO.TextWriter stateStream;
//Player orientation
private Quaternion orientation = Quaternion.identity;
//world rotation so that we can transform between the two
private Matrix4x4 worldRotation;
//grab the player's transform so that we can use it
public Transform playerTransform;
//If we've paused the game
private bool movementFrozen = false;
//Player's velocity in vector format
//private Vector3 playerVelocityVector;
//player Velocity as a scalar magnitude
//public double playerVelocity;
//time passed since last frame in the world frame
private double deltaTimeWorld;
//time passed since last frame in the player frame
private double deltaTimePlayer;
//total time passed in the player frame
private double totalTimePlayer;
//total time passed in the world frame
private double totalTimeWorld;
//speed of light
private double c = 6;
//Speed of light that is affected by the Unity editor
public double totalC = 6;
//max speed the player can achieve (starting value accessible from Unity Editor)
public double maxPlayerSpeed;
//max speed, for game use, not accessible from Unity Editor
private double maxSpeed;
//speed of light squared, kept for easy access in many calculations
private double cSqrd;
public VelocityFPC rigid = null;
//Use this to determine the state of the color shader. If it's True, all you'll see is the lorenz transform.
private bool shaderOff = false;
//Did we hit the menu key?
public bool menuKeyDown = false;
//Did we hit the shader key?
public bool shaderKeyDown = false;
//This is a value that gets used in many calculations, so we calculate it each frame
private double sqrtOneMinusVSquaredCWDividedByCSquared;
//Player rotation and change in rotation since last frame
public Vector3 playerRotation = new Vector3(0, 0, 0);
public Vector3 deltaRotation = new Vector3(0, 0, 0);
public double pctOfSpdUsing = 0; // Percent of velocity you are using
#endregion
#region Properties
public float finalMaxSpeed = .99f;
public bool MovementFrozen { get { return movementFrozen; } set { movementFrozen = value; } }
public Matrix4x4 WorldRotation { get { return worldRotation; } }
public Quaternion Orientation { get { return orientation; } }
public double PctOfSpdUsing { get { return pctOfSpdUsing; } set { pctOfSpdUsing = value; } }
//public Vector3 PlayerVelocityVector { get { return playerVelocityVector; } set { playerVelocityVector = value; } }
//public double PlayerVelocity { get { return playerVelocity; } }
public double SqrtOneMinusVSquaredCWDividedByCSquared { get { return sqrtOneMinusVSquaredCWDividedByCSquared; } }
public double DeltaTimeWorld { get { return deltaTimeWorld; } }
public double DeltaTimePlayer { get { return deltaTimePlayer; } }
public double TotalTimePlayer { get { return totalTimePlayer; } }
public double TotalTimeWorld { get { return totalTimeWorld; } }
public double SpeedOfLight { get { return c; } set { c = value; cSqrd = value * value; } }
public double SpeedOfLightSqrd { get { return cSqrd; } }
public bool keyHit = false;
public double MaxSpeed { get { return maxSpeed; } set { maxSpeed = value; } }
#endregion
#region consts
private const float ORB_SPEED_INC = 0.05f;
private const float ORB_DECEL_RATE = 0.6f;
private const float ORB_SPEED_DUR = 2f;
private const float MAX_SPEED = 6.00f;
public const float NORM_PERCENT_SPEED = .99f;
public const int splitDistance = 21000;
#endregion
private WiiMote wii = null;
public void Awake()
{
//Initialize the player's speed to zero
//playerVelocityVector = Vector3.zero;
//playerVelocity = 0;
//Set our constants
MaxSpeed = MAX_SPEED;
pctOfSpdUsing = NORM_PERCENT_SPEED;
c = totalC;
cSqrd = c*c;
//And ensure that the game starts/
movementFrozen = false;
}
public void reset()
{
//Reset everything not level-based
playerRotation.x = 0;
playerRotation.y = 0;
playerRotation.z = 0;
pctOfSpdUsing = 0;
}
//Call this function to pause and unpause the game
public void ChangeState()
{
}
//We set this in late update because of timing issues with collisions
public void LateUpdate()
{
Shader.SetGlobalFloat("xyr", (float)Camera.main.pixelWidth / Camera.main.pixelHeight);
Shader.SetGlobalFloat("xs", (float)Mathf.Tan(Mathf.Deg2Rad * Camera.main.fieldOfView / 2f));
Shader.SetGlobalFloat("_spdOfLight", (float)TRR.SPEEDOFLIGHT);
/* //Set the pause code in here so that our other objects can access it.
if (Input.GetAxis("Menu Key") > 0 && !menuKeyDown)
{
menuKeyDown = true;
ChangeState();
}
//set up our buttonUp function
else if (!(Input.GetAxis("Menu Key") > 0))
{
menuKeyDown = false;
}
*/
if (wii == null)
wii = GameObject.Find ("First Person Controller").GetComponent<WiiMote> ();
//Set our button code for the shader on/off button
if ((Input.GetKeyDown(KeyCode.B)|| wii.b_Z ) && !shaderKeyDown)
{
if(shaderOff)
shaderOff = false;
else
shaderOff = true;
shaderKeyDown = true;
}
//set up our buttonUp function
else if (!Input.GetKeyDown(KeyCode.B) || !wii.b_Z)
{
shaderKeyDown = false;
}
//If we're not paused, update everything
if (!movementFrozen)
{
if(rigid == null)
rigid = GameObject.FindGameObjectWithTag("Player").GetComponent<VelocityFPC>();
//Put our player position into the shader so that it can read it.
Shader.SetGlobalVector("_playerOffset", new Vector4(rigid.transform.position.x, rigid.transform.position.y, rigid.transform.position.z, 0));
/*
//if we reached max speed, forward or backwards, keep at max speed
if (playerVelocityVector.magnitude >= (float)MaxSpeed-.01f)
{
playerVelocityVector = playerVelocityVector.normalized * ((float)MaxSpeed-.01f);
}
//update our player velocity
playerVelocity = playerVelocityVector.magnitude;
*/
//During colorshift on/off, during the last level we don't want to have the funky
//colors changing so they can apperciate the other effects
if (shaderOff)
{
Shader.SetGlobalFloat("_colorShift", (float)0.0);
}
else
{
Shader.SetGlobalFloat("_colorShift", (float)1);
}
//Debug.Log (rigid.velocity);
//Send v/c to shader
Shader.SetGlobalVector("_vpc", new Vector4(rigid.vitesse.x, rigid.vitesse.y, rigid.vitesse.z, 0) / (float)TRR.SPEEDOFLIGHT);
//Shader.SetGlobalVector("_vpc", new Vector4(5.95f, 0f, 0f, 0) / (float)TRR.SPEEDOFLIGHT);
//Send world time to shader
Shader.SetGlobalFloat("_wrldTime", (float)TotalTimeWorld);
/******************************
* PART TWO OF ALGORITHM
* THE NEXT 4 LINES OF CODE FIND
* THE TIME PASSED IN WORLD FRAME
* ****************************/
//find this constant
sqrtOneMinusVSquaredCWDividedByCSquared = (double)Math.Sqrt(1 - Math.Pow(rigid.vitesse.magnitude, 2) / cSqrd);
//Set by Unity, time since last update
deltaTimePlayer = (double)Time.deltaTime;
//Get the total time passed of the player and world for display purposes
if (keyHit)
{
totalTimePlayer += deltaTimePlayer;
if (!double.IsNaN(sqrtOneMinusVSquaredCWDividedByCSquared))
{
//Get the delta time passed for the world, changed by relativistic effects
deltaTimeWorld = deltaTimePlayer / sqrtOneMinusVSquaredCWDividedByCSquared;
//and get the total time passed in the world
totalTimeWorld += deltaTimeWorld;
}
}
/*
//Set our rigidbody's velocity
if (!double.IsNaN(deltaTimePlayer) && !double.IsNaN(sqrtOneMinusVSquaredCWDividedByCSquared))
{
GameObject.FindGameObjectWithTag("Playermesh").GetComponent<Rigidbody>().velocity = -1*(rigid.velocity / (float)sqrtOneMinusVSquaredCWDividedByCSquared);
}
//But if either of those two constants is null due to a zero error, that means our velocity is zero anyways.
else
{
GameObject.FindGameObjectWithTag("Playermesh").GetComponent<Rigidbody>().velocity = Vector3.zero;
}
*/
/*****************************
* PART 3 OF ALGORITHM
* FIND THE ROTATION MATRIX
* AND CHANGE THE PLAYERS VELOCITY
* BY THIS ROTATION MATRIX
* ***************************/
//Find the turn angle
//Steering constant angular velocity in the player frame
//Rotate around the y-axis
orientation = Quaternion.AngleAxis(playerRotation.y, Vector3.up) * Quaternion.AngleAxis(playerRotation.x, Vector3.right);
Quaternion WorldOrientation = Quaternion.Inverse(orientation);
Normalize(orientation);
worldRotation = CreateFromQuaternion(WorldOrientation);
//Add up our rotation so that we know where the character (NOT CAMERA) should be facing
playerRotation += deltaRotation;
}
}
#region Matrix/Quat math
//They are functions that XNA had but Unity doesn't, so I had to make them myself
//This function takes in a quaternion and creates a rotation matrix from it
public Matrix4x4 CreateFromQuaternion(Quaternion q)
{
double w = q.w;
double x = q.x;
double y = q.y;
double z = q.z;
Matrix4x4 matrix;
matrix.m00 = (float)(Math.Pow((double)w, 2) + Math.Pow((double)x, 2.0) - Math.Pow((double)y, 2) - Math.Pow((double)z, 2));
matrix.m01 = (float)(2 * x * y - 2 * w * z);
matrix.m02 = (float)(2 * x * z + 2 * w * y);
matrix.m03 = (float)0;
matrix.m10 = (float)(2 * x * y + 2 * w * z);
matrix.m11 = (float)(Math.Pow((double)w, 2) - Math.Pow((double)x, 2.0) + Math.Pow((double)y, 2) - Math.Pow((double)z, 2));
matrix.m12 = (float)(2 * y * z + 2 * w * x);
matrix.m13 = (float)0;
matrix.m20 = (float)(2 * x * z - 2 * w * y);
matrix.m21 = (float)(2 * y * z - 2 * w * x);
matrix.m22 = (float)(Math.Pow((double)w, 2) - Math.Pow((double)x, 2.0) - Math.Pow((double)y, 2) + Math.Pow((double)z, 2));
matrix.m23 = 0;
matrix.m30 = 0;
matrix.m31 = 0;
matrix.m32 = 0;
matrix.m33 = 1;
return matrix;
}
//Normalize the given quaternion so that its magnitude is one.
public Quaternion Normalize(Quaternion quat)
{
Quaternion q = quat;
if (Math.Pow(q.w, 2) + Math.Pow(q.x, 2) + Math.Pow(q.y, 2) + Math.Pow(q.z, 2) != 1)
{
double magnitude = (double)Math.Sqrt(Math.Pow(q.w, 2) + Math.Pow(q.x, 2) + Math.Pow(q.y, 2) + Math.Pow(q.z, 2));
q.w = (float)((double)q.w / magnitude);
q.x = (float)((double)q.x / magnitude);
q.y = (float)((double)q.y / magnitude);
q.z = (float)((double)q.z / magnitude);
}
return q;
}
//Transform the matrix by a vector3
public Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix)
{
Vector3 final;
final.x = matrix.m00 * normal.x + matrix.m10 * normal.y + matrix.m20 * normal.z;
final.y = matrix.m02 * normal.x + matrix.m11 * normal.y + matrix.m21 * normal.z;
final.z = matrix.m03 * normal.x + matrix.m12 * normal.y + matrix.m22 * normal.z;
return final;
}
#endregion
}
| |
using System;
using System.Xml;
using System.Collections;
using System.IO;
using System.Text;
using System.Net;
using System.Diagnostics;
namespace Sgml
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class TestSuite
{
int tests = 0;
int passed = 0;
int ignored = 0;
bool domain = false;
bool crawl = false;
bool debug = false;
bool basify = false;
bool testdoc = false;
string proxy = null;
Encoding encoding = null;
string output = null;
bool formatted = false;
bool noxmldecl = false;
bool verbose = false;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args) {
TestSuite suite = new TestSuite();
suite.ParseCommandLine(args);
suite.Run();
}
void ParseCommandLine(string[] args) {
for (int i = 0; i < args.Length; i++){
string arg = args[i];
if (arg[0] == '-'){
switch (arg.Substring(1)){
case "debug":
debug = true;
break;
case "base":
basify = true;
break;
case "crawl":
crawl = true;
if (args[++i] == "domain")
domain = true;
break;
case "testdoc":
testdoc = true;
break;
case "verbose":
verbose = true;
break;
}
}
}
}
void Run(){
Uri baseUri;
try {
baseUri = new Uri(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
} catch {
baseUri = new Uri("file://" + Path.Combine(Directory.GetCurrentDirectory(), System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName.Replace('\\', '/')));
}
Console.WriteLine("baseUri = " + baseUri);
if(File.Exists("html.suite")) {
RunTest(baseUri, "html.suite");
} else {
RunTest(baseUri, Path.Combine("..", Path.Combine("..", "html.suite")));
}
if(File.Exists("ofx.suite")) {
RunTest(baseUri, "ofx.suite");
} else {
RunTest(baseUri, Path.Combine("..", Path.Combine("..", "ofx.suite")));
}
RegressionTest1();
RegressionTest2();
return;
}
void RunTest(Uri baseUri, string inputUri) {
Uri resolved = new Uri(baseUri, inputUri);
string path = resolved.LocalPath;
this.passed = 0;
this.tests = 0;
this.ignored = 0;
SgmlReader reader = new SgmlReader();
if(verbose) {
reader.ErrorLog = Console.Error;
}
RunTest(reader, path);
Console.WriteLine("{0} Tests passed", this.passed);
if ((this.passed + this.ignored) != this.tests) {
Console.WriteLine("{0} Tests failed", this.tests-(this.passed + this.ignored));
}
if(this.ignored != 0) {
Console.WriteLine("{0} Tests ignored", this.ignored);
}
Console.WriteLine();
return;
}
/**************************************************************************
* Run a test suite. Tests suites are organized into expected input/output
* blocks separated by back quotes (`). It runs the input and compares it
* with the expected output and reports any failures.
**************************************************************************/
void RunTest(SgmlReader reader, string file) {
Console.WriteLine(file);
StreamReader sr = new StreamReader(file);
StringBuilder input = new StringBuilder();
StringBuilder expectedOutput = new StringBuilder();
StringBuilder current = null;
StringBuilder args = new StringBuilder();
Uri baseUri = new Uri(new Uri(Directory.GetCurrentDirectory()+"\\"), file);
reader.SetBaseUri(baseUri.AbsoluteUri);
int start = 1;
int line = 1;
int pos = 1;
bool skipToEOL = false;
bool readArgs = false;
int i;
do {
i = sr.Read();
char ch = (char)i;
if (pos == 1 && ch == '`') {
++pos;
if (current == null) {
current = input;
current.Length = 0;
readArgs = true;
} else if (current == input) {
current = expectedOutput;
}
else {
RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
start = line;
input.Length = 0;
args.Length = 0;
expectedOutput.Length = 0;
current = input;
readArgs = true;
}
skipToEOL = true;
} else {
++pos;
if(current != null) {
if (readArgs){
args.Append(ch);
} else if (!skipToEOL){
current.Append(ch);
}
}
if (ch == '\r') {
line++; pos = 1;
if (sr.Peek() == '\n') {
i = sr.Read();
if (!skipToEOL) current.Append((char)i);
if (readArgs) args.Append(ch);
}
skipToEOL = false;
readArgs = false;
} else if (ch == '\n'){
skipToEOL = false;
readArgs = false;
line++; pos = 1;
}
}
} while (i != -1);
if (current.Length>0 && expectedOutput.Length>0) {
RunTest(reader, start, args.ToString(), input.ToString(), expectedOutput.ToString());
}
}
void RunTest(SgmlReader reader, int line, string args, string input, string expectedOutput){
try {
bool testdoc = false;
bool testclone = false;
bool format = true;
bool ignore = false;
foreach(string arg in args.Split(' ')) {
string sarg = arg.Trim();
if(sarg.Length == 0)
continue;
if(sarg[0] == '-') {
switch(sarg.Substring(1)) {
case "html":
reader.DocType = "html";
break;
case "lower":
reader.CaseFolding = CaseFolding.ToLower;
break;
case "upper":
reader.CaseFolding = CaseFolding.ToUpper;
break;
case "testdoc":
testdoc = true;
break;
case "testclone":
testclone = true;
break;
case "noformat":
format = false;
break;
case "ignore":
ignore = true;
break;
}
}
}
this.tests++;
if(ignore) {
this.ignored++;
return;
}
reader.InputStream = new StringReader(input);
if(format) {
reader.WhitespaceHandling = WhitespaceHandling.None;
} else {
reader.WhitespaceHandling = WhitespaceHandling.All;
}
StringWriter output = new StringWriter();
XmlTextWriter w = new XmlTextWriter(output);
if(format) {
w.Formatting = Formatting.Indented;
}
if(testdoc) {
XmlDocument doc = new XmlDocument();
doc.Load(reader);
doc.WriteTo(w);
} else if(testclone) {
XmlDocument doc = new XmlDocument();
doc.Load(reader);
XmlNode clone = doc.Clone();
clone.WriteTo(w);
} else {
reader.Read();
while(!reader.EOF) {
w.WriteNode(reader, true);
}
}
w.Close();
string actualOutput = output.ToString();
// validate output
using(StringReader source = new StringReader(actualOutput)) {
XmlDocument doc = new XmlDocument();
doc.Load(source);
}
// compare output
if(actualOutput.Trim().Replace("\r", "") != expectedOutput.Trim().Replace("\r", "")) {
Console.WriteLine();
Console.WriteLine("ERROR: Test failed on line {0}", line);
Console.WriteLine("---- Expected output");
Console.Write(expectedOutput);
Console.WriteLine("---- Actual output");
Console.WriteLine(actualOutput);
} else {
this.passed++;
}
} catch(Exception e) {
Console.WriteLine("FATAL ERROR: Test threw an exception on line {0}", line);
Console.WriteLine(e.Message);
Console.WriteLine(e.ToString());
Console.WriteLine("---- Input");
Console.Write(input);
}
}
void Process(SgmlReader reader, string uri, bool loadAsStream) {
if (uri == null) {
reader.InputStream = Console.In;
}
else if (loadAsStream) {
Uri location = new Uri(uri);
if (location.IsFile) {
reader.InputStream = new StreamReader(uri);
} else {
WebRequest wr = WebRequest.Create(location);
reader.InputStream = new StreamReader(wr.GetResponse().GetResponseStream());
}
} else {
reader.Href = uri;
}
if (debug) {
Debug(reader);
reader.Close();
return;
}
if (crawl) {
StartCrawl(reader, uri, basify);
return;
}
if (this.encoding == null) {
this.encoding = reader.GetEncoding();
}
XmlTextWriter w = null;
if (output != null) {
w = new XmlTextWriter(output, this.encoding);
}
else {
w = new XmlTextWriter(Console.Out);
}
if (formatted) w.Formatting = Formatting.Indented;
if (!noxmldecl) {
w.WriteStartDocument();
}
if (testdoc) {
XmlDocument doc = new XmlDocument();
try {
doc.Load(reader);
doc.WriteTo(w);
} catch (XmlException e) {
Console.WriteLine("Error:" + e.Message);
Console.WriteLine("at line " + e.LineNumber + " column " + e.LinePosition);
}
} else {
reader.Read();
while (!reader.EOF) {
w.WriteNode(reader, true);
}
}
w.Flush();
w.Close();
}
/***************************************************************************
* Useful debugging code...
* **************************************************************************/
void StartCrawl(SgmlReader reader, string uri, bool basify) {
Console.WriteLine("Loading '"+reader.BaseURI+"'");
XmlDocument doc = new XmlDocument();
try {
doc.XmlResolver = null; // don't do any downloads!
doc.Load(reader);
}
catch (Exception e) {
Console.WriteLine("Error loading document\n"+e.Message);
}
reader.Close();
if (basify) {
// html and head are option, if they are there use them otherwise not.
XmlElement be = (XmlElement)doc.SelectSingleNode("//base");
if (be == null) {
be = doc.CreateElement("base");
be.SetAttribute("href", doc.BaseURI);
XmlElement head = (XmlElement)doc.SelectSingleNode("//head");
if (head != null) {
head.InsertBefore(be, head.FirstChild);
}
else {
XmlElement html = (XmlElement)doc.SelectSingleNode("//html");
if (html != null) html.InsertBefore(be, html.FirstChild);
else doc.DocumentElement.InsertBefore(be, doc.DocumentElement.FirstChild);
}
}
}
try {
Crawl(reader.Dtd, doc, reader.ErrorLog);
}
catch (Exception e) {
Console.WriteLine("Uncaught exception: " + e.Message);
}
}
enum NodeTypeFlags {
None = 0,
Element = 0x1,
Attribute = 0x2,
Text = 0x4,
CDATA = 0x8,
EntityReference = 0x10,
Entity = 0x20,
ProcessingInstruction = 0x40,
Comment = 0x80,
Document = 0x100,
DocumentType = 0x200,
DocumentFragment = 0x400,
Notation = 0x800,
Whitespace = 0x1000,
SignificantWhitespace = 0x2000,
EndElement = 0x4000,
EndEntity = 0x8000,
filler = 0x10000,
XmlDeclaration = 0x20000,
}
NodeTypeFlags[] NodeTypeMap = new NodeTypeFlags[19] {
NodeTypeFlags.None,
NodeTypeFlags.Element,
NodeTypeFlags.Attribute,
NodeTypeFlags.Text,
NodeTypeFlags.CDATA,
NodeTypeFlags.EntityReference,
NodeTypeFlags.Entity,
NodeTypeFlags.ProcessingInstruction,
NodeTypeFlags.Comment,
NodeTypeFlags.Document,
NodeTypeFlags.DocumentType,
NodeTypeFlags.DocumentFragment,
NodeTypeFlags.Notation,
NodeTypeFlags.Whitespace,
NodeTypeFlags.SignificantWhitespace,
NodeTypeFlags.EndElement,
NodeTypeFlags.EndEntity,
NodeTypeFlags.filler,
NodeTypeFlags.XmlDeclaration,
};
void Debug(SgmlReader sr) {
NodeTypeFlags[] AllowedContentMap = new NodeTypeFlags[19] {
NodeTypeFlags.None, // none
NodeTypeFlags.Element | NodeTypeFlags.Attribute | NodeTypeFlags.Text | NodeTypeFlags.CDATA | NodeTypeFlags.EntityReference | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Comment | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.EndElement, // element
NodeTypeFlags.Text | NodeTypeFlags.EntityReference, // attribute
NodeTypeFlags.None, // text
NodeTypeFlags.None, // cdata
NodeTypeFlags.None, // entity reference
NodeTypeFlags.None, // entity
NodeTypeFlags.None, // processing instruction
NodeTypeFlags.None, // comment
NodeTypeFlags.Comment | NodeTypeFlags.DocumentType | NodeTypeFlags.Element | NodeTypeFlags.EndElement | NodeTypeFlags.ProcessingInstruction | NodeTypeFlags.Whitespace | NodeTypeFlags.SignificantWhitespace | NodeTypeFlags.XmlDeclaration, // document
NodeTypeFlags.None, // document type
NodeTypeFlags.None, // document fragment (not expecting these)
NodeTypeFlags.None, // notation
NodeTypeFlags.None, // whitespace
NodeTypeFlags.None, // signification whitespace
NodeTypeFlags.None, // end element
NodeTypeFlags.None, // end entity
NodeTypeFlags.None, // filler
NodeTypeFlags.None, // xml declaration.
};
Stack s = new Stack();
while (sr.Read()) {
if (sr.NodeType == XmlNodeType.EndElement) {
s.Pop();
}
if (s.Count > 0) {
XmlNodeType pt = (XmlNodeType)s.Peek();
NodeTypeFlags p = NodeTypeMap[(int)pt];
NodeTypeFlags f = NodeTypeMap[(int)sr.NodeType];
if ((AllowedContentMap[(int)pt]& f) != f) {
Console.WriteLine("Invalid content!!");
}
}
if (s.Count != sr.Depth-1) {
Console.WriteLine("Depth is wrong!");
}
if ( (sr.NodeType == XmlNodeType.Element && !sr.IsEmptyElement) ||
sr.NodeType == XmlNodeType.Document) {
s.Push(sr.NodeType);
}
for (int i = 1; i < sr.Depth; i++)
Console.Write(" ");
Console.Write(sr.NodeType.ToString() + " " + sr.Name);
if (sr.NodeType == XmlNodeType.Element && sr.AttributeCount > 0) {
sr.MoveToAttribute(0);
Console.Write(" (" + sr.Name+"="+sr.Value + ")");
sr.MoveToElement();
}
if (sr.Value != null) {
Console.Write(" " + sr.Value.Replace("\n"," ").Replace("\r",""));
}
Console.WriteLine();
}
}
int depth = 0;
int count = 0;
Hashtable visited = new Hashtable();
bool Crawl(SgmlDtd dtd, XmlDocument doc, TextWriter log) {
depth++;
StringBuilder indent = new StringBuilder();
for (int i = 0; i < depth; i++)
indent.Append(" ");
count++;
Uri baseUri = new Uri(doc.BaseURI);
XmlElement baseElmt = (XmlElement)doc.SelectSingleNode("/html/head/base");
if (baseElmt != null) {
string href = baseElmt.GetAttribute("href");
if (href != "") {
try {
baseUri = new Uri(href);
}
catch (Exception ) {
Console.WriteLine("### Error parsing BASE href '"+href+"'");
}
}
}
foreach (XmlElement a in doc.SelectNodes("//a")) {
string href = a.GetAttribute("href");
if (href != "" && href != null && depth<5) {
Uri local = new Uri(baseUri, href);
if (domain && baseUri.Host != local.Host)
continue;
string ext = Path.GetExtension(local.AbsolutePath).ToLower();
if (ext == ".jpg" || ext == ".gif" || ext==".mpg")
continue;
string url = local.AbsoluteUri;
if (!visited.ContainsKey(url)) {
visited.Add(url, url);
log.WriteLine(indent+"Loading '"+url+"'");
log.Flush();
StreamReader stm = null;
try {
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.Timeout = 10000;
if (proxy != null) wr.Proxy = new WebProxy(proxy);
wr.PreAuthenticate = false;
// Pass the credentials of the process.
wr.Credentials = CredentialCache.DefaultCredentials;
WebResponse resp = wr.GetResponse();
Uri actual = resp.ResponseUri;
if (actual.AbsoluteUri != url) {
local = new Uri(actual.AbsoluteUri);
log.WriteLine(indent+"Redirected to '"+actual.AbsoluteUri+"'");
log.Flush();
}
if (resp.ContentType != "text/html") {
log.WriteLine(indent+"Skipping ContentType="+resp.ContentType);
log.Flush();
resp.Close();
}
else {
stm = new StreamReader(resp.GetResponseStream());
}
}
catch (Exception e) {
log.WriteLine(indent+"### Error opening URL: " + e.Message);
log.Flush();
}
if (stm != null) {
SgmlReader reader = new SgmlReader();
reader.Dtd = dtd;
reader.SetBaseUri(local.AbsoluteUri);
reader.InputStream = stm;
reader.WebProxy = proxy;
XmlDocument d2 = new XmlDocument();
d2.XmlResolver = null; // don't do any downloads!
try {
d2.Load(reader);
reader.Close();
stm.Close();
if (!Crawl(dtd, d2, log))
return false;
}
catch (Exception e) {
log.WriteLine(indent+"### Error parsing document '"+local.AbsoluteUri+"', "+e.Message);
log.Flush();
reader.Close();
}
}
}
}
}
depth--;
return true;
}
void RegressionTest1() {
// Make sure we can do MoveToElement after reading multiple attributes.
SgmlReader r = new SgmlReader();
r.InputStream = new StringReader("<test id='10' x='20'><a/><!--comment-->test</test>");
if (r.Read()) {
while (r.MoveToNextAttribute()) {
Trace.WriteLine(r.Name);
}
if (r.MoveToElement()) {
Trace.WriteLine(r.ReadInnerXml());
}
}
}
void RegressionTest2() {
// test setup
var source = "&test";
var reader = new SgmlReader();
reader.DocType = "HTML";
reader.WhitespaceHandling = WhitespaceHandling.All;
reader.StripDocType = true;
reader.InputStream = new StringReader(source);
reader.CaseFolding = CaseFolding.ToLower;
// test
var element = System.Xml.Linq.XElement.Load(reader);
string value = element.Value;
if(!string.IsNullOrEmpty(value) && value[value.Length - 1] == (char)65535) {
Console.Error.WriteLine("ERROR: sgml reader added 65535 to input end");
}
}
}
}
| |
/* ====================================================================
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 NPOI.XSSF.UserModel;
using NUnit.Framework;
using NPOI.XSSF.UserModel.Helpers;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.Model;
using System.Collections.Generic;
using System;
using NPOI.XSSF;
using NPOI.Util;
using NPOI.HSSF.Record;
using TestCases.SS.UserModel;
using TestCases.HSSF;
namespace NPOI.XSSF.UserModel
{
[TestFixture]
public class TestXSSFSheet : BaseTestSheet
{
public TestXSSFSheet()
: base(XSSFITestDataProvider.instance)
{
}
//[Test]
//TODO column styles are not yet supported by XSSF
public override void TestDefaultColumnStyle()
{
base.TestDefaultColumnStyle();
}
[Test]
public void TestTestGetSetMargin()
{
BaseTestGetSetMargin(new double[] { 0.7, 0.7, 0.75, 0.75, 0.3, 0.3 });
}
[Test]
public void TestExistingHeaderFooter()
{
XSSFWorkbook workbook = XSSFTestDataSamples.OpenSampleWorkbook("45540_classic_Header.xlsx");
XSSFOddHeader hdr;
XSSFOddFooter ftr;
// Sheet 1 has a header with center and right text
XSSFSheet s1 = (XSSFSheet)workbook.GetSheetAt(0);
Assert.IsNotNull(s1.Header);
Assert.IsNotNull(s1.Footer);
hdr = (XSSFOddHeader)s1.Header;
ftr = (XSSFOddFooter)s1.Footer;
Assert.AreEqual("&Ctestdoc&Rtest phrase", hdr.Text);
Assert.AreEqual(null, ftr.Text);
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("testdoc", hdr.Center);
Assert.AreEqual("test phrase", hdr.Right);
Assert.AreEqual("", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
// Sheet 2 has a footer, but it's empty
XSSFSheet s2 = (XSSFSheet)workbook.GetSheetAt(1);
Assert.IsNotNull(s2.Header);
Assert.IsNotNull(s2.Footer);
hdr = (XSSFOddHeader)s2.Header;
ftr = (XSSFOddFooter)s2.Footer;
Assert.AreEqual(null, hdr.Text);
Assert.AreEqual("&L&F", ftr.Text);
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("", hdr.Center);
Assert.AreEqual("", hdr.Right);
Assert.AreEqual("&F", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
// Save and reload
IWorkbook wb = XSSFTestDataSamples.WriteOutAndReadBack(workbook);
hdr = (XSSFOddHeader)wb.GetSheetAt(0).Header;
ftr = (XSSFOddFooter)wb.GetSheetAt(0).Footer;
Assert.AreEqual("", hdr.Left);
Assert.AreEqual("testdoc", hdr.Center);
Assert.AreEqual("test phrase", hdr.Right);
Assert.AreEqual("", ftr.Left);
Assert.AreEqual("", ftr.Center);
Assert.AreEqual("", ftr.Right);
}
[Test]
public void TestGetAllHeadersFooters()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
Assert.IsNotNull(sheet.OddFooter);
Assert.IsNotNull(sheet.EvenFooter);
Assert.IsNotNull(sheet.FirstFooter);
Assert.IsNotNull(sheet.OddHeader);
Assert.IsNotNull(sheet.EvenHeader);
Assert.IsNotNull(sheet.FirstHeader);
Assert.AreEqual("", sheet.OddFooter.Left);
sheet.OddFooter.Left = ("odd footer left");
Assert.AreEqual("odd footer left", sheet.OddFooter.Left);
Assert.AreEqual("", sheet.EvenFooter.Left);
sheet.EvenFooter.Left = ("even footer left");
Assert.AreEqual("even footer left", sheet.EvenFooter.Left);
Assert.AreEqual("", sheet.FirstFooter.Left);
sheet.FirstFooter.Left = ("first footer left");
Assert.AreEqual("first footer left", sheet.FirstFooter.Left);
Assert.AreEqual("", sheet.OddHeader.Left);
sheet.OddHeader.Left = ("odd header left");
Assert.AreEqual("odd header left", sheet.OddHeader.Left);
Assert.AreEqual("", sheet.OddHeader.Right);
sheet.OddHeader.Right = ("odd header right");
Assert.AreEqual("odd header right", sheet.OddHeader.Right);
Assert.AreEqual("", sheet.OddHeader.Center);
sheet.OddHeader.Center = ("odd header center");
Assert.AreEqual("odd header center", sheet.OddHeader.Center);
// Defaults are odd
Assert.AreEqual("odd footer left", sheet.Footer.Left);
Assert.AreEqual("odd header center", sheet.Header.Center);
}
[Test]
public void TestAutoSizeColumn()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
sheet.CreateRow(0).CreateCell(13).SetCellValue("test");
sheet.AutoSizeColumn(13);
ColumnHelper columnHelper = sheet.GetColumnHelper();
CT_Col col = columnHelper.GetColumn(13, false);
Assert.IsTrue(col.bestFit);
}
[Test]
public void TestSetCellComment()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
IDrawing dg = sheet.CreateDrawingPatriarch();
IComment comment = dg.CreateCellComment(new XSSFClientAnchor());
ICell cell = sheet.CreateRow(0).CreateCell(0);
CommentsTable comments = sheet.GetCommentsTable(false);
CT_Comments ctComments = comments.GetCTComments();
cell.CellComment = (comment);
Assert.AreEqual("A1", ctComments.commentList.GetCommentArray(0).@ref);
comment.Author = ("test A1 author");
Assert.AreEqual("test A1 author", comments.GetAuthor((int)ctComments.commentList.GetCommentArray(0).authorId));
}
[Test]
public void TestGetActiveCell()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
sheet.SetActiveCell("R5");
Assert.AreEqual("R5", sheet.ActiveCell);
}
[Test]
public void TestCreateFreezePane_XSSF()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
sheet.CreateFreezePane(2, 4);
Assert.AreEqual(2.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.xSplit);
Assert.AreEqual(ST_Pane.bottomRight, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.activePane);
sheet.CreateFreezePane(3, 6, 10, 10);
Assert.AreEqual(3.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.xSplit);
//Assert.AreEqual(10, sheet.TopRow);
//Assert.AreEqual(10, sheet.LeftCol);
sheet.CreateSplitPane(4, 8, 12, 12, PanePosition.LowerRight);
Assert.AreEqual(8.0, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.ySplit);
Assert.AreEqual(ST_Pane.bottomRight, ctWorksheet.sheetViews.GetSheetViewArray(0).pane.activePane);
}
[Test]
public void TestRemoveMergedRegion_lowlevel()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
CellRangeAddress region_1 = CellRangeAddress.ValueOf("A1:B2");
CellRangeAddress region_2 = CellRangeAddress.ValueOf("C3:D4");
CellRangeAddress region_3 = CellRangeAddress.ValueOf("E5:F6");
sheet.AddMergedRegion(region_1);
sheet.AddMergedRegion(region_2);
sheet.AddMergedRegion(region_3);
Assert.AreEqual("C3:D4", ctWorksheet.mergeCells.GetMergeCellArray(1).@ref);
Assert.AreEqual(3, sheet.NumMergedRegions);
sheet.RemoveMergedRegion(1);
Assert.AreEqual("E5:F6", ctWorksheet.mergeCells.GetMergeCellArray(1).@ref);
Assert.AreEqual(2, sheet.NumMergedRegions);
sheet.RemoveMergedRegion(1);
sheet.RemoveMergedRegion(0);
Assert.AreEqual(0, sheet.NumMergedRegions);
Assert.IsNull(sheet.GetCTWorksheet().mergeCells, " CTMergeCells should be deleted After removing the last merged " +
"region on the sheet.");
}
[Test]
public void TestSetDefaultColumnStyle()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet ctWorksheet = sheet.GetCTWorksheet();
StylesTable stylesTable = workbook.GetStylesSource();
XSSFFont font = new XSSFFont();
font.FontName = ("Cambria");
stylesTable.PutFont(font);
CT_Xf cellStyleXf = new CT_Xf();
cellStyleXf.fontId = (1);
cellStyleXf.fillId = 0;
cellStyleXf.borderId = 0;
cellStyleXf.numFmtId = 0;
stylesTable.PutCellStyleXf(cellStyleXf);
CT_Xf cellXf = new CT_Xf();
cellXf.xfId = (1);
stylesTable.PutCellXf(cellXf);
XSSFCellStyle cellStyle = new XSSFCellStyle(1, 1, stylesTable, null);
Assert.AreEqual(1, cellStyle.FontIndex);
sheet.SetDefaultColumnStyle(3, cellStyle);
Assert.AreEqual(1u, ctWorksheet.GetColsArray(0).GetColArray(0).style);
}
[Test]
public void TestGroupUngroupColumn()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
//one level
sheet.GroupColumn(2, 7);
sheet.GroupColumn(10, 11);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(2, cols.sizeOfColArray());
List<CT_Col> colArray = cols.GetColList();
Assert.IsNotNull(colArray);
Assert.AreEqual((uint)(2 + 1), colArray[0].min); // 1 based
Assert.AreEqual((uint)(7 + 1), colArray[0].max); // 1 based
Assert.AreEqual(1, colArray[0].outlineLevel);
Assert.AreEqual(0, sheet.GetColumnOutlineLevel(0));
//two level
sheet.GroupColumn(1, 2);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(4, cols.sizeOfColArray());
colArray = cols.GetColList();
Assert.AreEqual(2, colArray[1].outlineLevel);
//three level
sheet.GroupColumn(6, 8);
sheet.GroupColumn(2, 3);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(7, cols.sizeOfColArray());
colArray = cols.GetColList();
Assert.AreEqual(3, colArray[1].outlineLevel);
Assert.AreEqual(3, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelCol);
sheet.UngroupColumn(8, 10);
colArray = cols.GetColList();
//Assert.AreEqual(3, colArray[1].outlineLevel);
sheet.UngroupColumn(4, 6);
sheet.UngroupColumn(2, 2);
colArray = cols.GetColList();
Assert.AreEqual(4, colArray.Count);
Assert.AreEqual(2, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelCol);
}
[Test]
public void TestGroupUngroupRow()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
//one level
sheet.GroupRow(9, 10);
Assert.AreEqual(2, sheet.PhysicalNumberOfRows);
CT_Row ctrow = ((XSSFRow)sheet.GetRow(9)).GetCTRow();
Assert.IsNotNull(ctrow);
Assert.AreEqual(10u, ctrow.r);
Assert.AreEqual(1, ctrow.outlineLevel);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
//two level
sheet.GroupRow(10, 13);
Assert.AreEqual(5, sheet.PhysicalNumberOfRows);
ctrow = ((XSSFRow)sheet.GetRow(10)).GetCTRow();
Assert.IsNotNull(ctrow);
Assert.AreEqual(11u, ctrow.r);
Assert.AreEqual(2, ctrow.outlineLevel);
Assert.AreEqual(2, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
sheet.UngroupRow(8, 10);
Assert.AreEqual(4, sheet.PhysicalNumberOfRows);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
sheet.UngroupRow(10, 10);
Assert.AreEqual(3, sheet.PhysicalNumberOfRows);
Assert.AreEqual(1, sheet.GetCTWorksheet().sheetFormatPr.outlineLevelRow);
}
[Test]
public void TestSetZoom()
{
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)workBook.CreateSheet("new sheet");
sheet1.SetZoom(3, 4); // 75 percent magnification
long zoom = sheet1.GetCTWorksheet().sheetViews.GetSheetViewArray(0).zoomScale;
Assert.AreEqual(zoom, 75);
sheet1.SetZoom(200);
zoom = sheet1.GetCTWorksheet().sheetViews.GetSheetViewArray(0).zoomScale;
Assert.AreEqual(zoom, 200);
try
{
sheet1.SetZoom(500);
Assert.Fail("Expecting exception");
}
catch (ArgumentException e)
{
Assert.AreEqual("Valid scale values range from 10 to 400", e.Message);
}
}
/**
* TODO - while this is internally consistent, I'm not
* completely clear in all cases what it's supposed to
* be doing... Someone who understands the goals a little
* better should really review this!
*/
[Test]
public void TestSetColumnGroupCollapsed()
{
IWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)wb.CreateSheet();
CT_Cols cols = sheet1.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(0, cols.sizeOfColArray());
sheet1.GroupColumn((short)4, (short)7);
sheet1.GroupColumn((short)9, (short)12);
Assert.AreEqual(2, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(1).max); // 1 based
sheet1.GroupColumn((short)10, (short)11);
Assert.AreEqual(4, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(3).max); // 1 based
// collapse columns - 1
sheet1.SetColumnGroupCollapsed((short)5, true);
Assert.AreEqual(5, cols.sizeOfColArray());
Assert.AreEqual(true, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
// expand columns - 1
sheet1.SetColumnGroupCollapsed((short)5, false);
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
//collapse - 2
sheet1.SetColumnGroupCollapsed((short)9, true);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//expand - 2
sheet1.SetColumnGroupCollapsed((short)9, false);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(14, cols.GetColArray(5).min);
//outline level 2: the line under ==> collapsed==True
Assert.AreEqual(2, cols.GetColArray(3).outlineLevel);
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//DOCUMENTARE MEGLIO IL DISCORSO DEL LIVELLO
//collapse - 3
sheet1.SetColumnGroupCollapsed((short)10, true);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(true, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
//expand - 3
sheet1.SetColumnGroupCollapsed((short)10, false);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).hidden);
Assert.AreEqual(false, cols.GetColArray(5).hidden);
Assert.AreEqual(false, cols.GetColArray(4).IsSetCollapsed());
// write out and give back
// Save and re-load
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual(6, cols.sizeOfColArray());
Assert.AreEqual(false, cols.GetColArray(0).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(0).IsSetCollapsed());
Assert.AreEqual(5, cols.GetColArray(0).min); // 1 based
Assert.AreEqual(8, cols.GetColArray(0).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(1).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(1).IsSetCollapsed());
Assert.AreEqual(9, cols.GetColArray(1).min); // 1 based
Assert.AreEqual(9, cols.GetColArray(1).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(2).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(2).IsSetCollapsed());
Assert.AreEqual(10, cols.GetColArray(2).min); // 1 based
Assert.AreEqual(10, cols.GetColArray(2).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(3).IsSetHidden());
Assert.AreEqual(true, cols.GetColArray(3).IsSetCollapsed());
Assert.AreEqual(11, cols.GetColArray(3).min); // 1 based
Assert.AreEqual(12, cols.GetColArray(3).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(4).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(4).IsSetCollapsed());
Assert.AreEqual(13, cols.GetColArray(4).min); // 1 based
Assert.AreEqual(13, cols.GetColArray(4).max); // 1 based
Assert.AreEqual(false, cols.GetColArray(5).IsSetHidden());
Assert.AreEqual(false, cols.GetColArray(5).IsSetCollapsed());
Assert.AreEqual(14, cols.GetColArray(5).min); // 1 based
Assert.AreEqual(14, cols.GetColArray(5).max); // 1 based
}
/**
* TODO - while this is internally consistent, I'm not
* completely clear in all cases what it's supposed to
* be doing... Someone who understands the goals a little
* better should really review this!
*/
[Test]
public void TestSetRowGroupCollapsed()
{
IWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)wb.CreateSheet();
sheet1.GroupRow(5, 14);
sheet1.GroupRow(7, 14);
sheet1.GroupRow(16, 19);
Assert.AreEqual(14, sheet1.PhysicalNumberOfRows);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
//collapsed
sheet1.SetRowGroupCollapsed(7, true);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
//expanded
sheet1.SetRowGroupCollapsed(7, false);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
// Save and re-load
wb = XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(6)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(7)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(9)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(true, ((XSSFRow)sheet1.GetRow(14)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(16)).GetCTRow().IsSetHidden());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetCollapsed());
Assert.AreEqual(false, ((XSSFRow)sheet1.GetRow(18)).GetCTRow().IsSetHidden());
}
/**
* Get / Set column width and check the actual values of the underlying XML beans
*/
[Test]
public void TestColumnWidth_lowlevel()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
sheet.SetColumnWidth(1, 22 * 256);
Assert.AreEqual(22 * 256, sheet.GetColumnWidth(1));
// Now check the low level stuff, and check that's all
// been Set correctly
XSSFSheet xs = sheet;
CT_Worksheet cts = xs.GetCTWorksheet();
List<CT_Cols> cols_s = cts.GetColsList();
Assert.AreEqual(1, cols_s.Count);
CT_Cols cols = cols_s[0];
Assert.AreEqual(1, cols.sizeOfColArray());
CT_Col col = cols.GetColArray(0);
// XML is 1 based, POI is 0 based
Assert.AreEqual(2u, col.min);
Assert.AreEqual(2u, col.max);
Assert.AreEqual(22.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
// Now Set another
sheet.SetColumnWidth(3, 33 * 256);
cols_s = cts.GetColsList();
Assert.AreEqual(1, cols_s.Count);
cols = cols_s[0];
Assert.AreEqual(2, cols.sizeOfColArray());
col = cols.GetColArray(0);
Assert.AreEqual(2u, col.min); // POI 1
Assert.AreEqual(2u, col.max);
Assert.AreEqual(22.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
col = cols.GetColArray(1);
Assert.AreEqual(4u, col.min); // POI 3
Assert.AreEqual(4u, col.max);
Assert.AreEqual(33.0, col.width, 0.0);
Assert.IsTrue(col.customWidth);
}
/**
* Setting width of a column included in a column span
*/
[Test]
public void Test47862()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("47862.xlsx");
XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
//<cols>
// <col min="1" max="5" width="15.77734375" customWidth="1"/>
//</cols>
//a span of columns [1,5]
Assert.AreEqual(1, cols.sizeOfColArray());
CT_Col col = cols.GetColArray(0);
Assert.AreEqual((uint)1, col.min);
Assert.AreEqual((uint)5, col.max);
double swidth = 15.77734375; //width of columns in the span
Assert.AreEqual(swidth, col.width, 0.0);
for (int i = 0; i < 5; i++)
{
Assert.AreEqual((int)(swidth * 256), sheet.GetColumnWidth(i));
}
int[] cw = new int[] { 10, 15, 20, 25, 30 };
for (int i = 0; i < 5; i++)
{
sheet.SetColumnWidth(i, cw[i] * 256);
}
//the check below failed prior to fix of Bug #47862
ColumnHelper.SortColumns(cols);
//<cols>
// <col min="1" max="1" customWidth="true" width="10.0" />
// <col min="2" max="2" customWidth="true" width="15.0" />
// <col min="3" max="3" customWidth="true" width="20.0" />
// <col min="4" max="4" customWidth="true" width="25.0" />
// <col min="5" max="5" customWidth="true" width="30.0" />
//</cols>
//now the span is splitted into 5 individual columns
Assert.AreEqual(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(cw[i] * 256, sheet.GetColumnWidth(i));
Assert.AreEqual(cw[i], cols.GetColArray(i).width, 0.0);
}
//serialize and check again
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = (XSSFSheet)wb.GetSheetAt(0);
cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(5, cols.sizeOfColArray());
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(cw[i] * 256, sheet.GetColumnWidth(i));
Assert.AreEqual(cw[i], cols.GetColArray(i).width, 0.0);
}
}
/**
* Hiding a column included in a column span
*/
[Test]
public void Test47804()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("47804.xlsx");
XSSFSheet sheet = (XSSFSheet)wb.GetSheetAt(0);
CT_Cols cols = sheet.GetCTWorksheet().GetColsArray(0);
Assert.AreEqual(2, cols.sizeOfColArray());
CT_Col col;
//<cols>
// <col min="2" max="4" width="12" customWidth="1"/>
// <col min="7" max="7" width="10.85546875" customWidth="1"/>
//</cols>
//a span of columns [2,4]
col = cols.GetColArray(0);
Assert.AreEqual((uint)2, col.min);
Assert.AreEqual((uint)4, col.max);
//individual column
col = cols.GetColArray(1);
Assert.AreEqual((uint)7, col.min);
Assert.AreEqual((uint)7, col.max);
sheet.SetColumnHidden(2, true); // Column C
sheet.SetColumnHidden(6, true); // Column G
Assert.IsTrue(sheet.IsColumnHidden(2));
Assert.IsTrue(sheet.IsColumnHidden(6));
//other columns but C and G are not hidden
Assert.IsFalse(sheet.IsColumnHidden(1));
Assert.IsFalse(sheet.IsColumnHidden(3));
Assert.IsFalse(sheet.IsColumnHidden(4));
Assert.IsFalse(sheet.IsColumnHidden(5));
//the check below failed prior to fix of Bug #47804
ColumnHelper.SortColumns(cols);
//the span is now splitted into three parts
//<cols>
// <col min="2" max="2" customWidth="true" width="12.0" />
// <col min="3" max="3" customWidth="true" width="12.0" hidden="true"/>
// <col min="4" max="4" customWidth="true" width="12.0"/>
// <col min="7" max="7" customWidth="true" width="10.85546875" hidden="true"/>
//</cols>
Assert.AreEqual(4, cols.sizeOfColArray());
col = cols.GetColArray(0);
Assert.AreEqual((uint)2, col.min);
Assert.AreEqual((uint)2, col.max);
col = cols.GetColArray(1);
Assert.AreEqual((uint)3, col.min);
Assert.AreEqual((uint)3, col.max);
col = cols.GetColArray(2);
Assert.AreEqual((uint)4, col.min);
Assert.AreEqual((uint)4, col.max);
col = cols.GetColArray(3);
Assert.AreEqual((uint)7, col.min);
Assert.AreEqual((uint)7, col.max);
//serialize and check again
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
sheet = (XSSFSheet)wb.GetSheetAt(0);
Assert.IsTrue(sheet.IsColumnHidden(2));
Assert.IsTrue(sheet.IsColumnHidden(6));
Assert.IsFalse(sheet.IsColumnHidden(1));
Assert.IsFalse(sheet.IsColumnHidden(3));
Assert.IsFalse(sheet.IsColumnHidden(4));
Assert.IsFalse(sheet.IsColumnHidden(5));
}
[Test]
public void TestCommentsTable()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet1 = (XSSFSheet)workbook.CreateSheet();
CommentsTable comment1 = sheet1.GetCommentsTable(false);
Assert.IsNull(comment1);
comment1 = sheet1.GetCommentsTable(true);
Assert.IsNotNull(comment1);
Assert.AreEqual("/xl/comments1.xml", comment1.GetPackageRelationship().TargetUri.ToString());
Assert.AreSame(comment1, sheet1.GetCommentsTable(true));
//second sheet
XSSFSheet sheet2 = (XSSFSheet)workbook.CreateSheet();
CommentsTable comment2 = sheet2.GetCommentsTable(false);
Assert.IsNull(comment2);
comment2 = sheet2.GetCommentsTable(true);
Assert.IsNotNull(comment2);
Assert.AreSame(comment2, sheet2.GetCommentsTable(true));
Assert.AreEqual("/xl/comments2.xml", comment2.GetPackageRelationship().TargetUri.ToString());
//comment1 and comment2 are different objects
Assert.AreNotSame(comment1, comment2);
//now Test against a workbook Containing cell comments
workbook = XSSFTestDataSamples.OpenSampleWorkbook("WithMoreVariousData.xlsx");
sheet1 = (XSSFSheet)workbook.GetSheetAt(0);
comment1 = sheet1.GetCommentsTable(true);
Assert.IsNotNull(comment1);
Assert.AreEqual("/xl/comments1.xml", comment1.GetPackageRelationship().TargetUri.ToString());
Assert.AreSame(comment1, sheet1.GetCommentsTable(true));
}
/**
* Rows and cells can be Created in random order,
* but CTRows are kept in ascending order
*/
[Test]
public new void TestCreateRow()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet();
CT_Worksheet wsh = sheet.GetCTWorksheet();
CT_SheetData sheetData = wsh.sheetData;
Assert.AreEqual(0, sheetData.SizeOfRowArray());
XSSFRow row1 = (XSSFRow)sheet.CreateRow(2);
row1.CreateCell(2);
row1.CreateCell(1);
XSSFRow row2 = (XSSFRow)sheet.CreateRow(1);
row2.CreateCell(2);
row2.CreateCell(1);
row2.CreateCell(0);
XSSFRow row3 = (XSSFRow)sheet.CreateRow(0);
row3.CreateCell(3);
row3.CreateCell(0);
row3.CreateCell(2);
row3.CreateCell(5);
List<CT_Row> xrow = sheetData.row;
Assert.AreEqual(3, xrow.Count);
//rows are sorted: {0, 1, 2}
Assert.AreEqual(4, xrow[0].SizeOfCArray());
Assert.AreEqual(1u, xrow[0].r);
Assert.IsTrue(xrow[0].Equals(row3.GetCTRow()));
Assert.AreEqual(3, xrow[1].SizeOfCArray());
Assert.AreEqual(2u, xrow[1].r);
Assert.IsTrue(xrow[1].Equals(row2.GetCTRow()));
Assert.AreEqual(2, xrow[2].SizeOfCArray());
Assert.AreEqual(3u, xrow[2].r);
Assert.IsTrue(xrow[2].Equals(row1.GetCTRow()));
List<CT_Cell> xcell = xrow[0].c;
Assert.AreEqual("D1", xcell[0].r);
Assert.AreEqual("A1", xcell[1].r);
Assert.AreEqual("C1", xcell[2].r);
Assert.AreEqual("F1", xcell[3].r);
//re-creating a row does NOT add extra data to the parent
row2 = (XSSFRow)sheet.CreateRow(1);
Assert.AreEqual(3, sheetData.SizeOfRowArray());
//existing cells are invalidated
Assert.AreEqual(0, sheetData.GetRowArray(1).SizeOfCArray());
Assert.AreEqual(0, row2.PhysicalNumberOfCells);
workbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
sheet = (XSSFSheet)workbook.GetSheetAt(0);
wsh = sheet.GetCTWorksheet();
xrow = sheetData.row;
Assert.AreEqual(3, xrow.Count);
//rows are sorted: {0, 1, 2}
Assert.AreEqual(4, xrow[0].SizeOfCArray());
Assert.AreEqual(1u, xrow[0].r);
//cells are now sorted
xcell = xrow[0].c;
Assert.AreEqual("A1", xcell[0].r);
Assert.AreEqual("C1", xcell[1].r);
Assert.AreEqual("D1", xcell[2].r);
Assert.AreEqual("F1", xcell[3].r);
Assert.AreEqual(0, xrow[1].SizeOfCArray());
Assert.AreEqual(2u, xrow[1].r);
Assert.AreEqual(2, xrow[2].SizeOfCArray());
Assert.AreEqual(3u, xrow[2].r);
}
[Test]
public void TestSetAutoFilter()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)wb.CreateSheet("new sheet");
sheet.SetAutoFilter(CellRangeAddress.ValueOf("A1:D100"));
Assert.AreEqual("A1:D100", sheet.GetCTWorksheet().autoFilter.@ref);
// auto-filter must be registered in workboook.xml, see Bugzilla 50315
XSSFName nm = wb.GetBuiltInName(XSSFName.BUILTIN_FILTER_DB, 0);
Assert.IsNotNull(nm);
Assert.AreEqual(0u, nm.GetCTName().localSheetId);
Assert.AreEqual(true, nm.GetCTName().hidden);
Assert.AreEqual("_xlnm._FilterDatabase", nm.GetCTName().name);
Assert.AreEqual("'new sheet'!$A$1:$D$100", nm.GetCTName().Value);
}
//[Test]
//public void TestProtectSheet_lowlevel()
//{
// XSSFWorkbook wb = new XSSFWorkbook();
// XSSFSheet sheet = (XSSFSheet)wb.CreateSheet();
// CT_SheetProtection pr = sheet.GetCTWorksheet().sheetProtection;
// Assert.IsNull(pr, "CTSheetProtection should be null by default");
// String password = "Test";
// sheet.ProtectSheet(password);
// pr = sheet.GetCTWorksheet().sheetProtection;
// Assert.IsNotNull(pr, "CTSheetProtection should be not null");
// Assert.IsTrue(pr.sheet, "sheet protection should be on");
// Assert.IsTrue(pr.objects, "object protection should be on");
// Assert.IsTrue(pr.scenarios, "scenario protection should be on");
// String hash = HexDump.ShortToHex(PasswordRecord.HashPassword(password)).ToString().Substring(2);
// Assert.AreEqual(hash, pr.xgetPassword().StringValue, "well known value for top secret hash should be " + hash);
// sheet.ProtectSheet(null);
// Assert.IsNull(sheet.GetCTWorksheet().sheetProtection, "protectSheet(null) should unset CTSheetProtection");
//}
[Test]
public void Test49966()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("49966.xlsx");
CalculationChain calcChain = wb.GetCalculationChain();
Assert.IsNotNull(wb.GetCalculationChain());
Assert.AreEqual(3, calcChain.GetCTCalcChain().SizeOfCArray());
ISheet sheet = wb.GetSheetAt(0);
IRow row = sheet.GetRow(0);
sheet.RemoveRow(row);
Assert.AreEqual(0, calcChain.GetCTCalcChain().SizeOfCArray(), "XSSFSheet#RemoveRow did not clear calcChain entries");
//calcChain should be gone
wb = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(wb);
Assert.IsNull(wb.GetCalculationChain());
}
/**
* See bug #50829
*/
[Test]
public void TestTables()
{
XSSFWorkbook wb = XSSFTestDataSamples.OpenSampleWorkbook("WithTable.xlsx");
Assert.AreEqual(3, wb.NumberOfSheets);
// Check the table sheet
XSSFSheet s1 = (XSSFSheet)wb.GetSheetAt(0);
Assert.AreEqual("a", s1.GetRow(0).GetCell(0).RichStringCellValue.ToString());
Assert.AreEqual(1.0, s1.GetRow(1).GetCell(0).NumericCellValue);
List<XSSFTable> tables = s1.GetTables();
Assert.IsNotNull(tables);
Assert.AreEqual(1, tables.Count);
XSSFTable table = tables[0];
Assert.AreEqual("Tabella1", table.Name);
Assert.AreEqual("Tabella1", table.DisplayName);
// And the others
XSSFSheet s2 = (XSSFSheet)wb.GetSheetAt(1);
Assert.AreEqual(0, s2.GetTables().Count);
XSSFSheet s3 = (XSSFSheet)wb.GetSheetAt(2);
Assert.AreEqual(0, s3.GetTables().Count);
}
/**
* Test to trigger OOXML-LITE generating to include org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetCalcPr
*/
[Test]
public void TestSetForceFormulaRecalculation()
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = (XSSFSheet)workbook.CreateSheet("Sheet 1");
Assert.IsFalse(sheet.ForceFormulaRecalculation);
// Set
sheet.ForceFormulaRecalculation = (true);
Assert.AreEqual(true, sheet.ForceFormulaRecalculation);
// calcMode="manual" is unset when forceFormulaRecalculation=true
CT_CalcPr calcPr = workbook.GetCTWorkbook().AddNewCalcPr();
calcPr.calcMode = (ST_CalcMode.manual);
sheet.ForceFormulaRecalculation = (true);
Assert.AreEqual(ST_CalcMode.auto, calcPr.calcMode);
// Check
sheet.ForceFormulaRecalculation = (false);
Assert.AreEqual(false, sheet.ForceFormulaRecalculation);
// Save, re-load, and re-check
workbook = (XSSFWorkbook)XSSFTestDataSamples.WriteOutAndReadBack(workbook);
sheet = (XSSFSheet)workbook.GetSheet("Sheet 1");
Assert.AreEqual(false, sheet.ForceFormulaRecalculation);
}
[Test]
public void Bug54607()
{
// run with the file provided in the Bug-Report
runGetTopRow("54607.xlsx", true, 1, 0, 0);
runGetLeftCol("54607.xlsx", true, 0, 0, 0);
// run with some other flie to see
runGetTopRow("54436.xlsx", true, 0);
runGetLeftCol("54436.xlsx", true, 0);
runGetTopRow("TwoSheetsNoneHidden.xlsx", true, 0, 0);
runGetLeftCol("TwoSheetsNoneHidden.xlsx", true, 0, 0);
runGetTopRow("TwoSheetsNoneHidden.xls", false, 0, 0);
runGetLeftCol("TwoSheetsNoneHidden.xls", false, 0, 0);
}
private void runGetTopRow(String file, bool isXSSF, params int[] topRows)
{
IWorkbook wb;
if (isXSSF)
{
wb = XSSFTestDataSamples.OpenSampleWorkbook(file);
}
else
{
wb = HSSFTestDataSamples.OpenSampleWorkbook(file);
}
for (int si = 0; si < wb.NumberOfSheets; si++)
{
ISheet sh = wb.GetSheetAt(si);
Assert.IsNotNull(sh.SheetName);
Assert.AreEqual(topRows[si], sh.TopRow, "Did not match for sheet " + si);
}
// for XSSF also test with SXSSF
//if (isXSSF)
//{
// Workbook swb = new SXSSFWorkbook((XSSFWorkbook)wb);
// try
// {
// for (int si = 0; si < swb.getNumberOfSheets(); si++)
// {
// Sheet sh = swb.getSheetAt(si);
// assertNotNull(sh.getSheetName());
// assertEquals("Did not match for sheet " + si, topRows[si], sh.getTopRow());
// }
// }
// finally
// {
// swb.close();
// }
//}
}
private void runGetLeftCol(String file, bool isXSSF, params int[] topRows)
{
IWorkbook wb;
if (isXSSF)
{
wb = XSSFTestDataSamples.OpenSampleWorkbook(file);
}
else
{
wb = HSSFTestDataSamples.OpenSampleWorkbook(file);
}
for (int si = 0; si < wb.NumberOfSheets; si++)
{
ISheet sh = wb.GetSheetAt(si);
Assert.IsNotNull(sh.SheetName);
Assert.AreEqual(topRows[si], sh.LeftCol, "Did not match for sheet " + si);
}
// for XSSF also test with SXSSF
//if (isXSSF)
//{
// IWorkbook swb = new SXSSFWorkbook((XSSFWorkbook)wb);
// for (int si = 0; si < swb.NumberOfSheets; si++)
// {
// ISheet sh = swb.GetSheetAt(si);
// Assert.IsNotNull(sh.SheetName);
// Assert.AreEqual("Did not match for sheet " + si, topRows[si], sh.GetLeftCol());
// }
// swb.Close();
//}
}
private XSSFWorkbook SetupSheet()
{
//set up workbook
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
IRow row1 = sheet.CreateRow((short)0);
ICell cell = row1.CreateCell((short)0);
cell.SetCellValue("Names");
ICell cell2 = row1.CreateCell((short)1);
cell2.SetCellValue("#");
IRow row2 = sheet.CreateRow((short)1);
ICell cell3 = row2.CreateCell((short)0);
cell3.SetCellValue("Jane");
ICell cell4 = row2.CreateCell((short)1);
cell4.SetCellValue(3);
IRow row3 = sheet.CreateRow((short)2);
ICell cell5 = row3.CreateCell((short)0);
cell5.SetCellValue("John");
ICell cell6 = row3.CreateCell((short)1);
cell6.SetCellValue(3);
return wb;
}
[Test]
public void TestCreateTwoPivotTablesInOneSheet()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
XSSFPivotTable pivotTable2 = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("L5"), sheet);
Assert.IsNotNull(pivotTable2);
Assert.IsTrue(wb.PivotTables.Count > 1);
}
[Test]
public void TestCreateTwoPivotTablesInTwoSheets()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
Assert.IsNotNull(wb);
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable2 = sheet2.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"), sheet);
Assert.IsNotNull(pivotTable2);
Assert.IsTrue(wb.PivotTables.Count > 1);
}
[Test]
public void TestCreatePivotTable()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
Assert.IsNotNull(wb);
Assert.IsNotNull(sheet);
XSSFPivotTable pivotTable = sheet.CreatePivotTable(new AreaReference("A1:B2"), new CellReference("H5"));
Assert.IsNotNull(pivotTable);
Assert.IsTrue(wb.PivotTables.Count > 0);
}
[Test]
public void TestCreatePivotTableInOtherSheetThanDataSheet()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet1 = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable = sheet2.CreatePivotTable
(new AreaReference("A1:B2"), new CellReference("H5"), sheet1);
Assert.AreEqual(0, pivotTable.GetRowLabelColumns().Count);
Assert.AreEqual(1, wb.PivotTables.Count);
Assert.AreEqual(0, sheet1.GetPivotTables().Count);
Assert.AreEqual(1, sheet2.GetPivotTables().Count);
}
[Test]
public void TestCreatePivotTableInOtherSheetThanDataSheetUsingAreaReference()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
XSSFPivotTable pivotTable = sheet2.CreatePivotTable
(new AreaReference(sheet.SheetName + "!A$1:B$2"), new CellReference("H5"));
Assert.AreEqual(0, pivotTable.GetRowLabelColumns().Count);
}
[Test]
public void TestCreatePivotTableWithConflictingDataSheets()
{
XSSFWorkbook wb = SetupSheet();
XSSFSheet sheet = wb.GetSheetAt(0) as XSSFSheet;
XSSFSheet sheet2 = wb.CreateSheet() as XSSFSheet;
try
{
sheet2.CreatePivotTable(new AreaReference(sheet.SheetName + "!A$1:B$2"), new CellReference("H5"), sheet2);
}
catch (ArgumentException)
{
return;
}
Assert.Fail();
}
[Test]
public void TestReadFails()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
try
{
sheet.OnDocumentRead();
Assert.Fail("Throws exception because we cannot read here");
}
catch (POIXMLException e)
{
// expected here
}
}
[Test]
public void TestCreateComment()
{
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.CreateSheet() as XSSFSheet;
Assert.IsNotNull(sheet.CreateComment());
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Services.Protocols;
using DBlog.Tools.Web;
using System.Diagnostics;
using System.Text;
public partial class NoticeControl : BlogControl
{
private string mCssClass = "notice";
private string mStyle = string.Empty;
private bool mHtmlEncode = true;
private string mMessage = string.Empty;
private NoticeKind mNoticeKind = NoticeKind.Info;
public enum NoticeKind
{
Info,
Warning,
Error,
Question
};
public bool HtmlEncode
{
get
{
return DBlog.Tools.Web.ViewState<bool>.GetViewStateValue(
EnableViewState, ViewState, "HtmlEncode", mHtmlEncode);
}
set
{
DBlog.Tools.Web.ViewState<bool>.SetViewStateValue(
EnableViewState, ViewState, "HtmlEncode", value, ref mHtmlEncode);
}
}
protected void Page_Load(object sender, EventArgs e)
{
linkCollapseExpand.Attributes["onclick"] = string.Format("CollapseExpandDetail('{0}')", divDetail.ClientID);
}
public string Style
{
get
{
return DBlog.Tools.Web.ViewState<string>.GetViewStateValue(
EnableViewState, ViewState, "Style", mStyle);
}
set
{
DBlog.Tools.Web.ViewState<string>.SetViewStateValue(
EnableViewState, ViewState, "Style", value, ref mStyle);
}
}
public string CssClass
{
get
{
return DBlog.Tools.Web.ViewState<string>.GetViewStateValue(
EnableViewState, ViewState, "CssClass", mCssClass);
}
set
{
DBlog.Tools.Web.ViewState<string>.SetViewStateValue(
EnableViewState, ViewState, "CssClass", value, ref mCssClass);
}
}
protected override void OnPreRender(EventArgs e)
{
tableNotice.Attributes["class"] = string.Format("{0}_{1}", CssClass, Kind.ToString().ToLower());
imageMessage.ImageUrl = string.Format("images/site/{0}.gif", Kind.ToString().ToLower());
base.OnPreRender(e);
}
public Exception Exception
{
set
{
Kind = NoticeKind.Error;
HtmlEncode = false;
string detail = value.Message;
string message = value.Message.Split('\n')[0];
Exception ex_detail = value.InnerException;
while (ex_detail != null)
{
detail = detail + "\n" + ex_detail.Message;
ex_detail = ex_detail.InnerException;
}
string reportbugurl = string.Format("mailto:{0}?subject={1}&body={2}",
SessionManager.GetSetting(
"email", "[email protected]"),
Renderer.UrlEncode(UrlPathAndQuery),
Renderer.UrlEncode(message));
Message = string.Format("{0}<br><small>This may be a bug. If you believe you should not be getting this error, " +
"please <a href={1}>click here</a> to report it.</small>", message, reportbugurl);
Detail = detail;
StringBuilder s = new StringBuilder();
s.AppendFormat("User-raised exception from {0}: {1}\n{2}", value.Source, value.Message, value.StackTrace);
if (Request != null && !string.IsNullOrEmpty(Request.RawUrl)) s.AppendFormat("\nUrl: {0}", Request.RawUrl);
if (Request != null && Request.UrlReferrer != null) s.AppendFormat("\nReferrer: {0}", Request.UrlReferrer);
if (Request != null && !string.IsNullOrEmpty(Request.UserAgent)) s.AppendFormat("\nUser-agent: {0}", Request.UserAgent);
SessionManager.EventLogWriteEntry(s.ToString(), EventLogEntryType.Warning);
Exception ex_eventlog = value.InnerException;
while (ex_eventlog != null)
{
SessionManager.EventLogWriteEntry(string.Format("User-raised inner-exception from {0}: {1}\n{2}",
ex_eventlog.Source, ex_eventlog.Message, ex_eventlog.StackTrace),
EventLogEntryType.Warning);
ex_eventlog = ex_eventlog.InnerException;
}
}
}
protected string Message
{
get
{
return DBlog.Tools.Web.ViewState<string>.GetViewStateValue(
EnableViewState, ViewState, "Message", mMessage);
}
set
{
DBlog.Tools.Web.ViewState<string>.SetViewStateValue(
EnableViewState, ViewState, "Message", value, ref mMessage);
panelNotice.Visible = ! string.IsNullOrEmpty(value);
labelMessage.Text = HtmlEncode ? Renderer.Render(Message) : Message;
}
}
protected string Detail
{
get
{
return DBlog.Tools.Web.ViewState<string>.GetViewStateValue(
EnableViewState, ViewState, "Detail", mMessage);
}
set
{
DBlog.Tools.Web.ViewState<string>.SetViewStateValue(
EnableViewState, ViewState, "Detail", value, ref mMessage);
panelNotice.Visible = !string.IsNullOrEmpty(value);
labelDetail.Text = HtmlEncode ? Renderer.Render(Detail) : Detail;
}
}
public NoticeKind Kind
{
get
{
return DBlog.Tools.Web.ViewState<NoticeKind>.GetViewStateValue(
EnableViewState, ViewState, "NoticeKind", mNoticeKind);
}
set
{
DBlog.Tools.Web.ViewState<NoticeKind>.SetViewStateValue(
EnableViewState, ViewState, "NoticeKind", value, ref mNoticeKind);
panelNotice.CssClass = string.Format("{0}_{1}", CssClass, value.ToString().ToLower());
imageMessage.ImageUrl = string.Format("images/site/{0}.gif", value.ToString().ToLower());
}
}
public string Warning
{
set
{
Kind = NoticeKind.Warning;
Message = value;
}
}
public string Info
{
set
{
Kind = NoticeKind.Info;
Message = value;
}
}
public string Question
{
set
{
Kind = NoticeKind.Question;
Message = value;
}
}
public new string Error
{
set
{
Kind = NoticeKind.Error;
Message = value;
}
}
}
| |
// 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;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace System.Drawing.Internal
{
/// <summary>
/// Represents a Win32 device context. Provides operations for setting some of the properties of a device context.
/// It's the managed wrapper for an HDC.
///
/// This class is divided into two files separating the code that needs to be compiled into reatail builds and
/// debugging code.
/// </summary>
internal sealed partial class DeviceContext : MarshalByRefObject, IDeviceContext, IDisposable
{
/// <summary>
/// This class is a wrapper to a Win32 device context, and the Hdc property is the way to get a
/// handle to it.
///
/// The hDc is released/deleted only when owned by the object, meaning it was created internally;
/// in this case, the object is responsible for releasing/deleting it.
/// In the case the object is created from an exisiting hdc, it is not released; this is consistent
/// with the Win32 guideline that says if you call GetDC/CreateDC/CreatIC/CreateEnhMetafile, you are
/// responsible for calling ReleaseDC/DeleteDC/DeleteEnhMetafile respectivelly.
///
/// This class implements some of the operations commonly performed on the properties of a dc in WinForms,
/// specially for interacting with GDI+, like clipping and coordinate transformation.
/// Several properties are not persisted in the dc but instead they are set/reset during a more comprehensive
/// operation like text rendering or painting; for instance text alignment is set and reset during DrawText (GDI),
/// DrawString (GDI+).
///
/// Other properties are persisted from operation to operation until they are reset, like clipping,
/// one can make several calls to Graphics or WindowsGraphics obect after setting the dc clip area and
/// before resetting it; these kinds of properties are the ones implemented in this class.
/// This kind of properties place an extra chanllenge in the scenario where a DeviceContext is obtained
/// from a Graphics object that has been used with GDI+, because GDI+ saves the hdc internally, rendering the
/// DeviceContext underlying hdc out of sync. DeviceContext needs to support these kind of properties to
/// be able to keep the GDI+ and GDI HDCs in sync.
///
/// A few other persisting properties have been implemented in DeviceContext2, among them:
/// 1. Window origin.
/// 2. Bounding rectangle.
/// 3. DC origin.
/// 4. View port extent.
/// 5. View port origin.
/// 6. Window extent
///
/// Other non-persisted properties just for information: Background/Forground color, Palette, Color adjustment,
/// Color space, ICM mode and profile, Current pen position, Binary raster op (not supported by GDI+),
/// Background mode, Logical Pen, DC pen color, ARc direction, Miter limit, Logical brush, DC brush color,
/// Brush origin, Polygon filling mode, Bitmap stretching mode, Logical font, Intercharacter spacing,
/// Font mapper flags, Text alignment, Test justification, Layout, Path, Meta region.
/// See book "Windows Graphics Programming - Feng Yuang", P315 - Device Context Attributes.
/// </summary>
private IntPtr _hDC;
private DeviceContextType _dcType;
public event EventHandler Disposing;
private bool _disposed;
// We cache the hWnd when creating the dc from one, to provide support forIDeviceContext.GetHdc/ReleaseHdc.
// This hWnd could be null, in such case it is referring to the screen.
private IntPtr _hWnd = (IntPtr)(-1); // Unlikely to be a valid hWnd.
private IntPtr _hInitialPen;
private IntPtr _hInitialBrush;
private IntPtr _hInitialBmp;
private IntPtr _hInitialFont;
private IntPtr _hCurrentPen;
private IntPtr _hCurrentBrush;
private IntPtr _hCurrentBmp;
private IntPtr _hCurrentFont;
private Stack _contextStack;
#if GDI_FINALIZATION_WATCH
private string AllocationSite = DbgUtil.StackTrace;
private string DeAllocationSite = "";
#endif
/// <summary>
/// This object's hdc. If this property is called, then the object will be used as an HDC wrapper, so the hdc
/// is cached and calls to GetHdc/ReleaseHdc won't PInvoke into GDI. Call Dispose to properly release the hdc.
/// </summary>
public IntPtr Hdc
{
get
{
if (_hDC == IntPtr.Zero)
{
if (_dcType == DeviceContextType.Display)
{
Debug.Assert(!_disposed, "Accessing a disposed DC, forcing recreation of HDC - this will generate a Handle leak!");
// Note: ReleaseDC must be called from the same thread. This applies only to HDC obtained
// from calling GetDC. This means Display DeviceContext objects should never be finalized.
_hDC = ((IDeviceContext)this).GetHdc(); // _hDC will be released on call to Dispose.
CacheInitialState();
}
#if GDI_FINALIZATION_WATCH
else
{
try { Debug.WriteLine(string.Format("Allocation stack:\r\n{0}\r\nDeallocation stack:\r\n{1}", AllocationSite, DeAllocationSite)); } catch {}
}
#endif
}
Debug.Assert(_hDC != IntPtr.Zero, "Attempt to use deleted HDC - DC type: " + _dcType);
return _hDC;
}
}
// Due to a problem with calling DeleteObject() on currently selected GDI objects, we now track the initial set
// of objects when a DeviceContext is created. Then, we also track which objects are currently selected in the
// DeviceContext. When a currently selected object is disposed, it is first replaced in the DC and then deleted.
private void CacheInitialState()
{
Debug.Assert(_hDC != IntPtr.Zero, "Cannot get initial state without a valid HDC");
_hCurrentPen = _hInitialPen = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_PEN);
_hCurrentBrush = _hInitialBrush = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_BRUSH);
_hCurrentBmp = _hInitialBmp = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_BITMAP);
_hCurrentFont = _hInitialFont = IntUnsafeNativeMethods.GetCurrentObject(new HandleRef(this, _hDC), IntNativeMethods.OBJ_FONT);
}
/// <summary>
/// Constructor to contruct a DeviceContext object from an window handle.
/// </summary>
private DeviceContext(IntPtr hWnd)
{
_hWnd = hWnd;
_dcType = DeviceContextType.Display;
DeviceContexts.AddDeviceContext(this);
// the hDc will be created on demand.
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr(String.Format( "DeviceContext( hWnd=0x{0:x8} )", unchecked((int) hWnd))));
#endif
}
/// <summary>
/// Constructor to contruct a DeviceContext object from an existing Win32 device context handle.
/// </summary>
private DeviceContext(IntPtr hDC, DeviceContextType dcType)
{
_hDC = hDC;
_dcType = dcType;
CacheInitialState();
DeviceContexts.AddDeviceContext(this);
if (dcType == DeviceContextType.Display)
{
_hWnd = IntUnsafeNativeMethods.WindowFromDC(new HandleRef(this, _hDC));
}
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DeviceContext( hDC=0x{0:X8}, Type={1} )", unchecked((int) hDC), dcType) ));
#endif
}
/// <summary>
/// CreateDC creates a DeviceContext object wrapping an hdc created with the Win32 CreateDC function.
/// </summary>
public static DeviceContext CreateDC(string driverName, string deviceName, string fileName, HandleRef devMode)
{
// Note: All input params can be null but not at the same time. See MSDN for information.
IntPtr hdc = IntUnsafeNativeMethods.CreateDC(driverName, deviceName, fileName, devMode);
return new DeviceContext(hdc, DeviceContextType.NamedDevice);
}
/// <summary>
/// CreateIC creates a DeviceContext object wrapping an hdc created with the Win32 CreateIC function.
/// </summary>
public static DeviceContext CreateIC(string driverName, string deviceName, string fileName, HandleRef devMode)
{
// Note: All input params can be null but not at the same time. See MSDN for information.
IntPtr hdc = IntUnsafeNativeMethods.CreateIC(driverName, deviceName, fileName, devMode);
return new DeviceContext(hdc, DeviceContextType.Information);
}
/// <summary>
/// Creates a DeviceContext object wrapping a memory DC compatible with the specified device.
/// </summary>
public static DeviceContext FromCompatibleDC(IntPtr hdc)
{
// If hdc is null, the function creates a memory DC compatible with the application's current screen.
// Win2K+: (See CreateCompatibleDC in the MSDN).
// In this case the thread that calls CreateCompatibleDC owns the HDC that is created. When this thread is destroyed,
// the HDC is no longer valid.
IntPtr compatibleDc = IntUnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, hdc));
return new DeviceContext(compatibleDc, DeviceContextType.Memory);
}
/// <summary>
/// Used for wrapping an existing hdc. In this case, this object doesn't own the hdc so calls to
/// GetHdc/ReleaseHdc don't PInvoke into GDI.
/// </summary>
public static DeviceContext FromHdc(IntPtr hdc)
{
Debug.Assert(hdc != IntPtr.Zero, "hdc == 0");
return new DeviceContext(hdc, DeviceContextType.Unknown);
}
/// <summary>
/// When hwnd is null, we are getting the screen DC.
/// </summary>
public static DeviceContext FromHwnd(IntPtr hwnd) => new DeviceContext(hwnd);
~DeviceContext() => Dispose(false);
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
internal void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
Disposing?.Invoke(this, EventArgs.Empty);
_disposed = true;
switch (_dcType)
{
case DeviceContextType.Display:
Debug.Assert(disposing, "WARNING: Finalizing a Display DeviceContext.\r\nReleaseDC may fail when not called from the same thread GetDC was called from.");
((IDeviceContext)this).ReleaseHdc();
break;
case DeviceContextType.Information:
case DeviceContextType.NamedDevice:
// CreateDC and CreateIC add an HDC handle to the HandleCollector; to remove it properly we need
// to call DeleteHDC.
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteHDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
#endif
IntUnsafeNativeMethods.DeleteHDC(new HandleRef(this, _hDC));
_hDC = IntPtr.Zero;
break;
case DeviceContextType.Memory:
// CreatCompatibleDC adds a GDI handle to HandleCollector, to remove it properly we need to call
// DeleteDC.
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("DC.DeleteDC(hdc=0x{0:x8})", unchecked((int) _hDC))));
#endif
IntUnsafeNativeMethods.DeleteDC(new HandleRef(this, _hDC));
_hDC = IntPtr.Zero;
break;
// case DeviceContextType.Metafile: - not yet supported.
case DeviceContextType.Unknown:
default:
return;
// do nothing, the hdc is not owned by this object.
// in this case it is ok if disposed throught finalization.
}
DbgUtil.AssertFinalization(this, disposing);
}
/// <summary>
/// Explicit interface method implementation to hide them a bit for usability reasons so the object is seen as
/// a wrapper around an hdc that is always available, and for performance reasons since it caches the hdc if
/// used in this way.
/// </summary>
IntPtr IDeviceContext.GetHdc()
{
if (_hDC == IntPtr.Zero)
{
Debug.Assert(_dcType == DeviceContextType.Display, "Calling GetDC from a non display/window device.");
// Note: for common DCs, GetDC assigns default attributes to the DC each time it is retrieved.
// For example, the default font is System.
_hDC = IntUnsafeNativeMethods.GetDC(new HandleRef(this, _hWnd));
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("hdc[0x{0:x8}]=DC.GetHdc(hWnd=0x{1:x8})", unchecked((int) _hDC), unchecked((int) _hWnd))));
#endif
}
return _hDC;
}
///<summary>
/// If the object was created from a DC, this object doesn't 'own' the dc so we just ignore this call.
///</summary>
void IDeviceContext.ReleaseHdc()
{
if (_hDC != IntPtr.Zero && _dcType == DeviceContextType.Display)
{
#if TRACK_HDC
int retVal =
#endif
IntUnsafeNativeMethods.ReleaseDC(new HandleRef(this, _hWnd), new HandleRef(this, _hDC));
// Note: retVal == 0 means it was not released but doesn't necessarily means an error; class or private DCs are never released.
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("[ret={0}]=DC.ReleaseDC(hDc=0x{1:x8}, hWnd=0x{2:x8})", retVal, unchecked((int) _hDC), unchecked((int) _hWnd))));
#endif
_hDC = IntPtr.Zero;
}
}
/// <summary>
/// Restores the device context to the specified state. The DC is restored by popping state information off a
/// stack created by earlier calls to the SaveHdc function.
/// The stack can contain the state information for several instances of the DC. If the state specified by the
/// specified parameter is not at the top of the stack, RestoreDC deletes all state information between the top
/// of the stack and the specified instance.
/// Specifies the saved state to be restored. If this parameter is positive, nSavedDC represents a specific
/// instance of the state to be restored. If this parameter is negative, nSavedDC represents an instance relative
/// to the current state. For example, -1 restores the most recently saved state.
/// See MSDN for more info.
/// </summary>
public void RestoreHdc()
{
#if TRACK_HDC
bool result =
#endif
// Note: Don't use the Hdc property here, it would force handle creation.
IntUnsafeNativeMethods.RestoreDC(new HandleRef(this, _hDC), -1);
#if TRACK_HDC
// Note: Winforms may call this method during app exit at which point the DC may have been finalized already causing this assert to popup.
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("ret[0]=DC.RestoreHdc(hDc=0x{1:x8}, state={2})", result, unchecked((int) _hDC), restoreState) ));
#endif
Debug.Assert(_contextStack != null, "Someone is calling RestoreHdc() before SaveHdc()");
if (_contextStack != null)
{
GraphicsState g = (GraphicsState)_contextStack.Pop();
_hCurrentBmp = g.hBitmap;
_hCurrentBrush = g.hBrush;
_hCurrentPen = g.hPen;
_hCurrentFont = g.hFont;
}
#if OPTIMIZED_MEASUREMENTDC
// in this case, GDI will copy back the previously saved font into the DC.
// we dont actually know what the font is in our measurement DC so
// we need to clear it off.
MeasurementDCInfo.ResetIfIsMeasurementDC(_hDC);
#endif
}
/// <summary>
/// Saves the current state of the device context by copying data describing selected objects and graphic
/// modes (such as the bitmap, brush, palette, font, pen, region, drawing mode, and mapping mode) to a
/// context stack.
/// The SaveDC function can be used any number of times to save any number of instances of the DC state.
/// A saved state can be restored by using the RestoreHdc method.
/// See MSDN for more details.
/// </summary>
public int SaveHdc()
{
HandleRef hdc = new HandleRef(this, _hDC);
int state = IntUnsafeNativeMethods.SaveDC(hdc);
if (_contextStack == null)
{
_contextStack = new Stack();
}
GraphicsState g = new GraphicsState();
g.hBitmap = _hCurrentBmp;
g.hBrush = _hCurrentBrush;
g.hPen = _hCurrentPen;
g.hFont = _hCurrentFont;
_contextStack.Push(g);
#if TRACK_HDC
Debug.WriteLine( DbgUtil.StackTraceToStr( String.Format("state[0]=DC.SaveHdc(hDc=0x{1:x8})", state, unchecked((int) _hDC)) ));
#endif
return state;
}
/// <summary>
/// Selects a region as the current clipping region for the device context.
/// Remarks (From MSDN):
/// - Only a copy of the selected region is used. The region itself can be selected for any number of other device contexts or it can be deleted.
/// - The SelectClipRgn function assumes that the coordinates for a region are specified in device units.
/// - To remove a device-context's clipping region, specify a NULL region handle.
/// </summary>
public void SetClip(WindowsRegion region)
{
HandleRef hdc = new HandleRef(this, _hDC);
HandleRef hRegion = new HandleRef(region, region.HRegion);
IntUnsafeNativeMethods.SelectClipRgn(hdc, hRegion);
}
///<summary>
/// Creates a new clipping region from the intersection of the current clipping region and the specified rectangle.
///</summary>
public void IntersectClip(WindowsRegion wr)
{
//if the incoming windowsregion is infinite, there is no need to do any intersecting.
if (wr.HRegion == IntPtr.Zero)
{
return;
}
WindowsRegion clip = new WindowsRegion(0, 0, 0, 0);
try
{
int result = IntUnsafeNativeMethods.GetClipRgn(new HandleRef(this, _hDC), new HandleRef(clip, clip.HRegion));
// If the function succeeds and there is a clipping region for the given device context, the return value is 1.
if (result == 1)
{
Debug.Assert(clip.HRegion != IntPtr.Zero);
wr.CombineRegion(clip, wr, RegionCombineMode.AND); //1 = AND (or Intersect)
}
SetClip(wr);
}
finally
{
clip.Dispose();
}
}
/// <summary>
/// Modifies the viewport origin for a device context using the specified horizontal and vertical offsets in
/// logical units.
/// </summary>
public void TranslateTransform(int dx, int dy)
{
IntNativeMethods.POINT orgn = new IntNativeMethods.POINT();
IntUnsafeNativeMethods.OffsetViewportOrgEx(new HandleRef(this, _hDC), dx, dy, orgn);
}
/// <summary>
/// </summary>
public override bool Equals(object obj)
{
DeviceContext other = obj as DeviceContext;
if (other == this)
{
return true;
}
if (other == null)
{
return false;
}
// Note: Use property instead of field so the HDC is initialized. Also, this avoid serialization issues (the obj could be a proxy that does not have access to private fields).
return other.Hdc == _hDC;
}
/// <summary>
/// This allows collections to treat DeviceContext objects wrapping the same HDC as the same objects.
/// </summary>
public override int GetHashCode() => _hDC.GetHashCode();
internal class GraphicsState
{
internal IntPtr hBrush;
internal IntPtr hFont;
internal IntPtr hPen;
internal IntPtr hBitmap;
}
}
}
| |
// 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.Diagnostics;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Microsoft.VisualStudio.Debugger.Metadata;
using Roslyn.Utilities;
using MethodAttributes = System.Reflection.MethodAttributes;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class TypeHelpers
{
internal const BindingFlags MemberBindingFlags = BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.DeclaredOnly;
internal static void AppendTypeMembers(
this Type type,
ArrayBuilder<MemberAndDeclarationInfo> includedMembers,
Predicate<MemberInfo> predicate,
Type declaredType,
DkmClrAppDomain appDomain,
bool includeInherited,
bool hideNonPublic)
{
Debug.Assert(!type.IsInterface);
var memberLocation = DeclarationInfo.FromSubTypeOfDeclaredType;
var previousDeclarationMap = includeInherited ? new Dictionary<string, DeclarationInfo>() : null;
int inheritanceLevel = 0;
while (!type.IsObject())
{
if (type.Equals(declaredType))
{
Debug.Assert(memberLocation == DeclarationInfo.FromSubTypeOfDeclaredType);
memberLocation = DeclarationInfo.FromDeclaredTypeOrBase;
}
// Get the state from DebuggerBrowsableAttributes for the members of the current type.
var browsableState = DkmClrType.Create(appDomain, type).GetDebuggerBrowsableAttributeState();
// Hide non-public members if hideNonPublic is specified (intended to reflect the
// DkmInspectionContext's DkmEvaluationFlags), and the type is from an assembly
// with no symbols.
var hideNonPublicBehavior = DeclarationInfo.None;
if (hideNonPublic)
{
var moduleInstance = appDomain.FindClrModuleInstance(type.Module.ModuleVersionId);
if (moduleInstance == null || moduleInstance.Module == null)
{
// Synthetic module or no symbols loaded.
hideNonPublicBehavior = DeclarationInfo.HideNonPublic;
}
}
foreach (var member in type.GetMembers(MemberBindingFlags))
{
if (!predicate(member))
{
continue;
}
var memberName = member.Name;
// This represents information about the immediately preceding (more derived)
// declaration with the same name as the current member.
var previousDeclaration = DeclarationInfo.None;
var memberNameAlreadySeen = false;
if (includeInherited)
{
memberNameAlreadySeen = previousDeclarationMap.TryGetValue(memberName, out previousDeclaration);
if (memberNameAlreadySeen)
{
// There was a name conflict, so we'll need to include the declaring
// type of the member to disambiguate.
previousDeclaration |= DeclarationInfo.IncludeTypeInMemberName;
}
// Update previous member with name hiding (casting) and declared location information for next time.
previousDeclarationMap[memberName] =
(previousDeclaration & ~(DeclarationInfo.RequiresExplicitCast |
DeclarationInfo.FromSubTypeOfDeclaredType)) |
member.AccessingBaseMemberWithSameNameRequiresExplicitCast() |
memberLocation;
}
Debug.Assert(memberNameAlreadySeen != (previousDeclaration == DeclarationInfo.None));
// Decide whether to include this member in the list of members to display.
if (!memberNameAlreadySeen || previousDeclaration.IsSet(DeclarationInfo.RequiresExplicitCast))
{
DkmClrDebuggerBrowsableAttributeState? browsableStateValue = null;
if (browsableState != null)
{
DkmClrDebuggerBrowsableAttributeState value;
if (browsableState.TryGetValue(memberName, out value))
{
browsableStateValue = value;
}
}
if (memberLocation.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the current type is a sub-type of the declared type, then
// we always need to insert a cast to access the member
previousDeclaration |= DeclarationInfo.RequiresExplicitCast;
}
else if (previousDeclaration.IsSet(DeclarationInfo.FromSubTypeOfDeclaredType))
{
// If the immediately preceding member (less derived) was
// declared on a sub-type of the declared type, then we'll
// ignore the casting bit. Accessing a member through the
// declared type is the same as casting to that type, so
// the cast would be redundant.
previousDeclaration &= ~DeclarationInfo.RequiresExplicitCast;
}
previousDeclaration |= hideNonPublicBehavior;
includedMembers.Add(new MemberAndDeclarationInfo(member, browsableStateValue, previousDeclaration, inheritanceLevel));
}
}
if (!includeInherited)
{
break;
}
type = type.BaseType;
inheritanceLevel++;
}
includedMembers.Sort(MemberAndDeclarationInfo.Comparer);
}
private static DeclarationInfo AccessingBaseMemberWithSameNameRequiresExplicitCast(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return DeclarationInfo.RequiresExplicitCast;
case MemberTypes.Property:
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if ((getMethod != null) &&
(!getMethod.IsVirtual || ((getMethod.Attributes & MethodAttributes.VtableLayoutMask) == MethodAttributes.NewSlot)))
{
return DeclarationInfo.RequiresExplicitCast;
}
return DeclarationInfo.None;
default:
throw ExceptionUtilities.UnexpectedValue(member.MemberType);
}
}
internal static bool IsVisibleMember(MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return true;
case MemberTypes.Property:
return GetNonIndexerGetMethod((PropertyInfo)member) != null;
}
return false;
}
/// <summary>
/// Returns true if the member is public or protected.
/// </summary>
internal static bool IsPublic(this MemberInfo member)
{
// Matches native EE which includes protected members.
switch (member.MemberType)
{
case MemberTypes.Field:
{
var field = (FieldInfo)member;
var attributes = field.Attributes;
return ((attributes & System.Reflection.FieldAttributes.Public) == System.Reflection.FieldAttributes.Public) ||
((attributes & System.Reflection.FieldAttributes.Family) == System.Reflection.FieldAttributes.Family);
}
case MemberTypes.Property:
{
// Native EE uses the accessibility of the property rather than getter
// so "public object P { private get; set; }" is treated as public.
// Instead, we drop properties if the getter is inaccessible.
var getMethod = GetNonIndexerGetMethod((PropertyInfo)member);
if (getMethod == null)
{
return false;
}
var attributes = getMethod.Attributes;
return ((attributes & System.Reflection.MethodAttributes.Public) == System.Reflection.MethodAttributes.Public) ||
((attributes & System.Reflection.MethodAttributes.Family) == System.Reflection.MethodAttributes.Family);
}
default:
return false;
}
}
private static MethodInfo GetNonIndexerGetMethod(PropertyInfo property)
{
return (property.GetIndexParameters().Length == 0) ?
property.GetGetMethod(nonPublic: true) :
null;
}
internal static bool IsBoolean(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Boolean;
}
internal static bool IsCharacter(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Char;
}
internal static bool IsDecimal(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.Decimal;
}
internal static bool IsDateTime(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.DateTime;
}
internal static bool IsObject(this Type type)
{
bool result = type.IsClass && (type.BaseType == null) && !type.IsPointer;
Debug.Assert(result == type.IsMscorlibType("System", "Object"));
return result;
}
internal static bool IsValueType(this Type type)
{
return type.IsMscorlibType("System", "ValueType");
}
internal static bool IsString(this Type type)
{
return Type.GetTypeCode(type) == TypeCode.String;
}
internal static bool IsVoid(this Type type)
{
return type.IsMscorlibType("System", "Void") && !type.IsGenericType;
}
internal static bool IsIEnumerable(this Type type)
{
return type.IsMscorlibType("System.Collections", "IEnumerable");
}
internal static bool IsIEnumerableOfT(this Type type)
{
return type.IsMscorlibType("System.Collections.Generic", "IEnumerable`1");
}
internal static bool IsTypeVariables(this Type type)
{
return type.IsType(null, "<>c__TypeVariables");
}
/// <summary>
/// Returns type argument if the type is
/// Nullable<T>, otherwise null.
/// </summary>
internal static Type GetNullableTypeArgument(this Type type)
{
if (type.IsMscorlibType("System", "Nullable`1"))
{
var typeArgs = type.GetGenericArguments();
if (typeArgs.Length == 1)
{
return typeArgs[0];
}
}
return null;
}
internal static bool IsNullable(this Type type)
{
return type.GetNullableTypeArgument() != null;
}
internal static DkmClrValue GetFieldValue(this DkmClrValue value, string name, DkmInspectionContext inspectionContext)
{
return value.GetMemberValue(name, (int)MemberTypes.Field, ParentTypeName: null, InspectionContext: inspectionContext);
}
internal static DkmClrValue GetNullableValue(this DkmClrValue value, DkmInspectionContext inspectionContext)
{
Debug.Assert(value.Type.GetLmrType().IsNullable());
var hasValue = value.GetFieldValue(InternalWellKnownMemberNames.NullableHasValue, inspectionContext);
if (object.Equals(hasValue.HostObjectValue, false))
{
return null;
}
return value.GetFieldValue(InternalWellKnownMemberNames.NullableValue, inspectionContext);
}
internal static Type GetBaseTypeOrNull(this Type underlyingType, DkmClrAppDomain appDomain, out DkmClrType type)
{
Debug.Assert((underlyingType.BaseType != null) || underlyingType.IsPointer || underlyingType.IsArray, "BaseType should only return null if the underlyingType is a pointer or array.");
underlyingType = underlyingType.BaseType;
type = (underlyingType != null) ? DkmClrType.Create(appDomain, underlyingType) : null;
return underlyingType;
}
/// <summary>
/// Get the first attribute from <see cref="DkmClrType.GetEvalAttributes"/> (including inherited attributes)
/// that is of type T, as well as the type that it targeted.
/// </summary>
internal static bool TryGetEvalAttribute<T>(this DkmClrType type, out DkmClrType attributeTarget, out T evalAttribute)
where T : DkmClrEvalAttribute
{
attributeTarget = null;
evalAttribute = null;
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
evalAttribute = attribute as T;
if (evalAttribute != null)
{
attributeTarget = type;
return true;
}
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
return false;
}
/// <summary>
/// Returns the set of DebuggerBrowsableAttribute state for the
/// members of the type, indexed by member name, or null if there
/// are no DebuggerBrowsableAttributes on members of the type.
/// </summary>
private static Dictionary<string, DkmClrDebuggerBrowsableAttributeState> GetDebuggerBrowsableAttributeState(this DkmClrType type)
{
Dictionary<string, DkmClrDebuggerBrowsableAttributeState> result = null;
foreach (var attribute in type.GetEvalAttributes())
{
var browsableAttribute = attribute as DkmClrDebuggerBrowsableAttribute;
if (browsableAttribute == null)
{
continue;
}
if (result == null)
{
result = new Dictionary<string, DkmClrDebuggerBrowsableAttributeState>();
}
result.Add(browsableAttribute.TargetMember, browsableAttribute.State);
}
return result;
}
/// <summary>
/// Extracts information from the first <see cref="DebuggerDisplayAttribute"/> on the runtime type of <paramref name="value"/>, if there is one.
/// </summary>
internal static bool TryGetDebuggerDisplayInfo(this DkmClrValue value, out DebuggerDisplayInfo displayInfo)
{
displayInfo = default(DebuggerDisplayInfo);
// The native EE does not consider DebuggerDisplayAttribute
// on null or error instances.
if (value.IsError() || value.IsNull)
{
return false;
}
var clrType = value.Type;
DkmClrType attributeTarget;
DkmClrDebuggerDisplayAttribute attribute;
if (clrType.TryGetEvalAttribute(out attributeTarget, out attribute)) // First, as in dev12.
{
displayInfo = new DebuggerDisplayInfo(attributeTarget, attribute);
return true;
}
return false;
}
/// <summary>
/// Returns the array of <see cref="DkmCustomUIVisualizerInfo"/> objects of the type from its <see cref="DkmClrDebuggerVisualizerAttribute"/> attributes,
/// or null if the type has no [DebuggerVisualizer] attributes associated with it.
/// </summary>
internal static DkmCustomUIVisualizerInfo[] GetDebuggerCustomUIVisualizerInfo(this DkmClrType type)
{
var builder = ArrayBuilder<DkmCustomUIVisualizerInfo>.GetInstance();
var appDomain = type.AppDomain;
var underlyingType = type.GetLmrType();
while ((underlyingType != null) && !underlyingType.IsObject())
{
foreach (var attribute in type.GetEvalAttributes())
{
var visualizerAttribute = attribute as DkmClrDebuggerVisualizerAttribute;
if (visualizerAttribute == null)
{
continue;
}
builder.Add(DkmCustomUIVisualizerInfo.Create((uint)builder.Count,
visualizerAttribute.VisualizerDescription,
visualizerAttribute.VisualizerDescription,
// ClrCustomVisualizerVSHost is a registry entry that specifies the CLSID of the
// IDebugCustomViewer class that will be instantiated to display the custom visualizer.
"ClrCustomVisualizerVSHost",
visualizerAttribute.UISideVisualizerTypeName,
visualizerAttribute.UISideVisualizerAssemblyName,
visualizerAttribute.UISideVisualizerAssemblyLocation,
visualizerAttribute.DebuggeeSideVisualizerTypeName,
visualizerAttribute.DebuggeeSideVisualizerAssemblyName));
}
underlyingType = underlyingType.GetBaseTypeOrNull(appDomain, out type);
}
var result = (builder.Count > 0) ? builder.ToArray() : null;
builder.Free();
return result;
}
internal static DkmClrType GetProxyType(this DkmClrType type)
{
DkmClrType attributeTarget;
DkmClrDebuggerTypeProxyAttribute attribute;
if (type.TryGetEvalAttribute(out attributeTarget, out attribute))
{
var targetedType = attributeTarget.GetLmrType();
var proxyType = attribute.ProxyType;
var underlyingProxy = proxyType.GetLmrType();
if (underlyingProxy.IsGenericType && targetedType.IsGenericType)
{
var typeArgs = targetedType.GetGenericArguments();
// Drop the proxy type if the arity does not match.
if (typeArgs.Length != underlyingProxy.GetGenericArguments().Length)
{
return null;
}
// Substitute target type arguments for proxy type arguments.
var constructedProxy = underlyingProxy.Substitute(underlyingProxy, typeArgs);
proxyType = DkmClrType.Create(type.AppDomain, constructedProxy);
}
return proxyType;
}
return null;
}
/// <summary>
/// Substitute references to type parameters from 'typeDef'
/// with type arguments from 'typeArgs' in type 'type'.
/// </summary>
internal static Type Substitute(this Type type, Type typeDef, Type[] typeArgs)
{
Debug.Assert(typeDef.IsGenericTypeDefinition);
Debug.Assert(typeDef.GetGenericArguments().Length == typeArgs.Length);
if (type.IsGenericType)
{
var builder = ArrayBuilder<Type>.GetInstance();
foreach (var t in type.GetGenericArguments())
{
builder.Add(t.Substitute(typeDef, typeArgs));
}
var typeDefinition = type.GetGenericTypeDefinition();
return typeDefinition.MakeGenericType(builder.ToArrayAndFree());
}
else if (type.IsArray)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
var n = type.GetArrayRank();
return (n == 1) ? elementType.MakeArrayType() : elementType.MakeArrayType(n);
}
else if (type.IsPointer)
{
var elementType = type.GetElementType();
elementType = elementType.Substitute(typeDef, typeArgs);
return elementType.MakePointerType();
}
else if (type.IsGenericParameter)
{
if (type.DeclaringType.Equals(typeDef))
{
var ordinal = type.GenericParameterPosition;
return typeArgs[ordinal];
}
}
return type;
}
// Returns the IEnumerable interface implemented by the given type,
// preferring System.Collections.Generic.IEnumerable<T> over
// System.Collections.IEnumerable. If there are multiple implementations
// of IEnumerable<T> on base and derived types, the implementation on
// the most derived type is returned. If there are multiple implementations
// of IEnumerable<T> on the same type, it is undefined which is returned.
internal static Type GetIEnumerableImplementationIfAny(this Type type)
{
var t = type;
do
{
foreach (var @interface in t.GetInterfacesOnType())
{
if (@interface.IsIEnumerableOfT())
{
// Return the first implementation of IEnumerable<T>.
return @interface;
}
}
t = t.BaseType;
} while (t != null);
foreach (var @interface in type.GetInterfaces())
{
if (@interface.IsIEnumerable())
{
return @interface;
}
}
return null;
}
internal static bool IsEmptyResultsViewException(this Type type)
{
return type.IsType("System.Linq", "SystemCore_EnumerableDebugViewEmptyException");
}
internal static bool IsOrInheritsFrom(this Type type, Type baseType)
{
Debug.Assert(type != null);
Debug.Assert(baseType != null);
Debug.Assert(!baseType.IsInterface);
if (type.IsInterface)
{
return false;
}
do
{
if (type.Equals(baseType))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
private static bool IsMscorlib(this Assembly assembly)
{
return assembly.GetReferencedAssemblies().Length == 0;
}
private static bool IsMscorlibType(this Type type, string @namespace, string name)
{
// Ignore IsMscorlib for now since type.Assembly returns
// System.Runtime.dll for some types in mscorlib.dll.
// TODO: Re-enable commented out check.
return type.IsType(@namespace, name) /*&& type.Assembly.IsMscorlib()*/;
}
internal static bool IsOrInheritsFrom(this Type type, string @namespace, string name)
{
do
{
if (type.IsType(@namespace, name))
{
return true;
}
type = type.BaseType;
}
while (type != null);
return false;
}
internal static bool IsType(this Type type, string @namespace, string name)
{
Debug.Assert((@namespace == null) || (@namespace.Length > 0)); // Type.Namespace is null not empty.
Debug.Assert(!string.IsNullOrEmpty(name));
return string.Equals(type.Namespace, @namespace, StringComparison.Ordinal) &&
string.Equals(type.Name, name, StringComparison.Ordinal);
}
}
}
| |
//
// Copyright (c) 2004-2018 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.Layouts
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using NLog.Layouts;
using Xunit;
public class CsvLayoutTests : NLogTestBase
{
[Fact]
public void EndToEndTest()
{
string tempFile = string.Empty;
try
{
tempFile = Path.GetTempFileName();
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='" + tempFile + @"'>
<layout type='CSVLayout'>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
<delimiter>Comma</delimiter>
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText(tempFile))
{
Assert.Equal("level,message,counter", sr.ReadLine());
Assert.Equal("Debug,msg,1", sr.ReadLine());
Assert.Equal("Info,msg2,2", sr.ReadLine());
Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
/// <summary>
/// Custom header overwrites file headers
///
/// Note: maybe changed with an option in the future
/// </summary>
[Fact]
public void CustomHeaderTest()
{
string tempFile = string.Empty;
try
{
tempFile = Path.GetTempFileName();
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='" + tempFile + @"'>
<layout type='CSVLayout'>
<header>headertest</header>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
<delimiter>Comma</delimiter>
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText(tempFile))
{
Assert.Equal("headertest", sr.ReadLine());
// Assert.Equal("level,message,counter", sr.ReadLine());
Assert.Equal("Debug,msg,1", sr.ReadLine());
Assert.Equal("Info,msg2,2", sr.ReadLine());
Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
[Fact]
public void NoHeadersTest()
{
string tempFile = string.Empty;
try
{
tempFile = Path.GetTempFileName();
LogManager.Configuration = CreateConfigurationFromString(@"
<nlog>
<targets>
<target name='f' type='File' fileName='" + tempFile + @"'>
<layout type='CSVLayout' withHeader='false'>
<delimiter>Comma</delimiter>
<column name='level' layout='${level}' />
<column name='message' layout='${message}' />
<column name='counter' layout='${counter}' />
</layout>
</target>
</targets>
<rules>
<logger name='*' minlevel='Debug' writeTo='f' />
</rules>
</nlog>");
ILogger logger = LogManager.GetLogger("A");
logger.Debug("msg");
logger.Info("msg2");
logger.Warn("Message with, a comma");
using (StreamReader sr = File.OpenText(tempFile))
{
Assert.Equal("Debug,msg,1", sr.ReadLine());
Assert.Equal("Info,msg2,2", sr.ReadLine());
Assert.Equal("Warn,\"Message with, a comma\",3", sr.ReadLine());
}
}
finally
{
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
}
}
[Fact]
public void CsvLayoutRenderingNoQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Nothing,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.Equal("2010-01-01 12:34:56.0000" + sep + "Info" + sep + "hello, world", csvLayout.Render(ev));
Assert.Equal("date" + sep + "level" + sep + "message;text", csvLayout.Header.Render(ev));
}
}
[Fact]
public void CsvLayoutRenderingFullQuoting()
{
var delimiters = new Dictionary<CsvColumnDelimiterMode, string>
{
{ CsvColumnDelimiterMode.Auto, CultureInfo.CurrentCulture.TextInfo.ListSeparator },
{ CsvColumnDelimiterMode.Comma, "," },
{ CsvColumnDelimiterMode.Semicolon, ";" },
{ CsvColumnDelimiterMode.Space, " " },
{ CsvColumnDelimiterMode.Tab, "\t" },
{ CsvColumnDelimiterMode.Pipe, "|" },
{ CsvColumnDelimiterMode.Custom, "zzz" },
};
foreach (var delim in delimiters)
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.All,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = delim.Key,
CustomColumnDelimiter = "zzz",
};
var ev = new LogEventInfo();
ev.TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56);
ev.Level = LogLevel.Info;
ev.Message = "hello, world";
string sep = delim.Value;
Assert.Equal("'2010-01-01 12:34:56.0000'" + sep + "'Info'" + sep + "'hello, world'", csvLayout.Render(ev));
Assert.Equal("'date'" + sep + "'level'" + sep + "'message;text'", csvLayout.Header.Render(ev));
}
}
[Fact]
public void CsvLayoutRenderingAutoQuoting()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message;text", "${message}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
// no quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;hello, world",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
}));
// multi-line string - requires quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello\rworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\rworld"
}));
// multi-line string - requires quoting
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello\nworld'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello\nworld"
}));
// quote character used in string, will be quoted and doubled
Assert.Equal(
"2010-01-01 12:34:56.0000;Info;'hello''world'",
csvLayout.Render(new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello'world"
}));
Assert.Equal("date;level;'message;text'", csvLayout.Header.Render(LogEventInfo.CreateNullEvent()));
}
[Fact]
public void CsvLayoutCachingTest()
{
var csvLayout = new CsvLayout()
{
Quoting = CsvQuotingMode.Auto,
Columns =
{
new CsvColumn("date", "${longdate}"),
new CsvColumn("level", "${level}"),
new CsvColumn("message", "${message}"),
new CsvColumn("threadid", "${threadid}"),
},
QuoteChar = "'",
Delimiter = CsvColumnDelimiterMode.Semicolon,
};
var e1 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 56),
Level = LogLevel.Info,
Message = "hello, world"
};
var e2 = new LogEventInfo
{
TimeStamp = new DateTime(2010, 01, 01, 12, 34, 57),
Level = LogLevel.Info,
Message = "hello, world"
};
var r11 = csvLayout.Render(e1);
var r12 = csvLayout.Render(e1);
var r21 = csvLayout.Render(e2);
var r22 = csvLayout.Render(e2);
var h11 = csvLayout.Header.Render(e1);
var h21 = csvLayout.Header.Render(e2);
Assert.Same(r11, r12);
Assert.Same(r21, r22);
Assert.NotSame(r11, r21);
Assert.NotSame(r12, r22);
Assert.NotSame(h11, h21);
Assert.Equal(h11, h21);
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FanOut.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Event;
using Akka.Pattern;
using Reactive.Streams;
namespace Akka.Streams.Implementation
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public class OutputBunch<T>
{
#region internal classes
private sealed class FanoutOutputs : SimpleOutputs
{
private readonly int _id;
public FanoutOutputs(int id, IActorRef actor, IPump pump) : base(actor, pump)
{
_id = id;
}
public new ISubscription CreateSubscription() => new FanOut.SubstreamSubscription(Actor, _id);
}
#endregion
private readonly int _outputCount;
private bool _bunchCancelled;
private readonly FanoutOutputs[] _outputs;
private readonly bool[] _marked;
private int _markedCount;
private readonly bool[] _pending;
private int _markedPending;
private readonly bool[] _cancelled;
private int _markedCanceled;
private readonly bool[] _completed;
private readonly bool[] _errored;
private bool _unmarkCancelled = true;
private int _preferredId;
/// <summary>
/// TBD
/// </summary>
/// <param name="outputCount">TBD</param>
/// <param name="impl">TBD</param>
/// <param name="pump">TBD</param>
public OutputBunch(int outputCount, IActorRef impl, IPump pump)
{
_outputCount = outputCount;
_outputs = new FanoutOutputs[outputCount];
for (var i = 0; i < outputCount; i++)
_outputs[i] = new FanoutOutputs(i, impl, pump);
_marked = new bool[outputCount];
_pending = new bool[outputCount];
_cancelled = new bool[outputCount];
_completed = new bool[outputCount];
_errored = new bool[outputCount];
AllOfMarkedOutputs = new LambdaTransferState(
isCompleted: () => _markedCanceled > 0 || _markedCount == 0,
isReady: () => _markedPending == _markedCount);
AnyOfMarkedOutputs = new LambdaTransferState(
isCompleted: () => _markedCanceled == _markedCount,
isReady: () => _markedPending > 0);
// FIXME: Eliminate re-wraps
SubReceive = new SubReceive(message => message.Match()
.With<FanOut.ExposedPublishers<T>>(exposed =>
{
var publishers = exposed.Publishers.GetEnumerator();
var outputs = _outputs.AsEnumerable().GetEnumerator();
while (publishers.MoveNext() && outputs.MoveNext())
outputs.Current.SubReceive.CurrentReceive(new ExposedPublisher(publishers.Current));
})
.With<FanOut.SubstreamRequestMore>(more =>
{
if (more.Demand < 1)
// According to Reactive Streams Spec 3.9, with non-positive demand must yield onError
Error(more.Id, ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException);
else
{
if (_marked[more.Id] && !_pending[more.Id])
_markedPending += 1;
_pending[more.Id] = true;
_outputs[more.Id].SubReceive.CurrentReceive(new RequestMore(null, more.Demand));
}
})
.With<FanOut.SubstreamCancel>(cancel =>
{
if (_unmarkCancelled)
UnmarkOutput(cancel.Id);
if (_marked[cancel.Id] && !_cancelled[cancel.Id])
_markedCanceled += 1;
_cancelled[cancel.Id] = true;
OnCancel(cancel.Id);
_outputs[cancel.Id].SubReceive.CurrentReceive(new Cancel(null));
})
.With<FanOut.SubstreamSubscribePending>(pending => _outputs[pending.Id].SubReceive.CurrentReceive(SubscribePending.Instance))
.WasHandled);
}
/// <summary>
/// Will only transfer an element when all marked outputs
/// have demand, and will complete as soon as any of the marked
/// outputs have canceled.
/// </summary>
public readonly TransferState AllOfMarkedOutputs;
/// <summary>
/// Will transfer an element when any of the marked outputs
/// have demand, and will complete when all of the marked
/// outputs have canceled.
/// </summary>
public readonly TransferState AnyOfMarkedOutputs;
/// <summary>
/// TBD
/// </summary>
public readonly SubReceive SubReceive;
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
/// <returns>TBD</returns>
public bool IsPending(int output) => _pending[output];
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
/// <returns>TBD</returns>
public bool IsCompleted(int output) => _completed[output];
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
/// <returns>TBD</returns>
public bool IsCancelled(int output) => _cancelled[output];
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
/// <returns>TBD</returns>
public bool IsErrored(int output) => _errored[output];
/// <summary>
/// TBD
/// </summary>
public void Complete()
{
if (!_bunchCancelled)
{
_bunchCancelled = true;
for (var i = 0; i < _outputs.Length; i++)
Complete(i);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
public void Complete(int output)
{
if (!_completed[output] && !_errored[output] && !_cancelled[output])
{
_outputs[output].Complete();
_completed[output] = true;
UnmarkOutput(output);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="e">TBD</param>
public void Cancel(Exception e)
{
if (!_bunchCancelled)
{
_bunchCancelled = true;
for (var i = 0; i < _outputs.Length; i++)
Error(i, e);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
/// <param name="e">TBD</param>
public void Error(int output, Exception e)
{
if (!_errored[output] && !_cancelled[output] && !_completed[output])
{
_outputs[output].Error(e);
_errored[output] = true;
UnmarkOutput(output);
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
public void MarkOutput(int output)
{
if (!_marked[output])
{
if (_cancelled[output])
_markedCanceled += 1;
if (_pending[output])
_markedPending += 1;
_marked[output] = true;
_markedCount += 1;
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
public void UnmarkOutput(int output)
{
if (_marked[output])
{
if (_cancelled[output])
_markedCanceled -= 1;
if (_pending[output])
_markedPending -= 1;
_marked[output] = false;
_markedCount -= 1;
}
}
/// <summary>
/// TBD
/// </summary>
public void MarkAllOutputs()
{
for (var i = 0; i < _outputCount; i++)
MarkOutput(i);
}
/// <summary>
/// TBD
/// </summary>
public void UnmarkAllOutputs()
{
for (var i = 0; i < _outputCount; i++)
UnmarkOutput(i);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="enabled">TBD</param>
public void UnmarkCancelledOutputs(bool enabled) => _unmarkCancelled = enabled;
/// <summary>
/// TBD
/// </summary>
/// <exception cref="ArgumentException">TBD</exception>
/// <returns>TBD</returns>
public int IdToEnqueue()
{
var id = _preferredId;
while (!(_marked[id] && _pending[id]))
{
id += 1;
if (id == _outputCount)
id = 0;
if (id != _preferredId)
throw new ArgumentException("Tried to enqueue without waiting for any demand");
}
return id;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
/// <param name="element">TBD</param>
public void Enqueue(int id, T element)
{
var output = _outputs[id];
output.EnqueueOutputElement(element);
if (!output.IsDemandAvailable)
{
if (_marked[id])
_markedPending -= 1;
_pending[id] = false;
}
}
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
public void EnqueueMarked(T element)
{
for (var id = 0; id < _outputCount; id++)
if (_marked[id])
Enqueue(id, element);
}
/// <summary>
/// TBD
/// </summary>
/// <returns>TBD</returns>
public int IdToEnqueueAndYield()
{
var id = IdToEnqueue();
_preferredId = id + 1;
if (_preferredId == _outputCount)
_preferredId = 0;
return id;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
public void EnqueueAndYield(T element) => Enqueue(IdToEnqueueAndYield(), element);
/// <summary>
/// TBD
/// </summary>
/// <param name="element">TBD</param>
/// <param name="preferred">TBD</param>
public void EnqueueAndPrefer(T element, int preferred)
{
var id = IdToEnqueue();
_preferredId = preferred;
Enqueue(id, element);
}
/// <summary>
/// TBD
/// </summary>
/// <param name="output">TBD</param>
public void OnCancel(int output)
{
}
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
/// <returns>TBD</returns>
public TransferState DemandAvailableFor(int id) =>
new LambdaTransferState(isReady: () => _pending[id],
isCompleted: () => _cancelled[id] || _completed[id] || _errored[id]);
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
/// <returns>TBD</returns>
public TransferState DemandOrCancelAvailableFor(int id)
=> new LambdaTransferState(isReady: () => _pending[id] || _cancelled[id], isCompleted: () => false);
}
/// <summary>
/// INTERNAL API
/// </summary>
public static class FanOut
{
/// <summary>
/// TBD
/// </summary>
[Serializable]
public struct SubstreamRequestMore : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly int Id;
/// <summary>
/// TBD
/// </summary>
public readonly long Demand;
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
/// <param name="demand">TBD</param>
public SubstreamRequestMore(int id, long demand)
{
Id = id;
Demand = demand;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
public struct SubstreamCancel : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly int Id;
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
public SubstreamCancel(int id)
{
Id = id;
}
}
/// <summary>
/// TBD
/// </summary>
[Serializable]
public struct SubstreamSubscribePending : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly int Id;
/// <summary>
/// TBD
/// </summary>
/// <param name="id">TBD</param>
public SubstreamSubscribePending(int id)
{
Id = id;
}
}
/// <summary>
/// TBD
/// </summary>
public class SubstreamSubscription : ISubscription
{
private readonly IActorRef _parent;
private readonly int _id;
/// <summary>
/// TBD
/// </summary>
/// <param name="parent">TBD</param>
/// <param name="id">TBD</param>
public SubstreamSubscription(IActorRef parent, int id)
{
_parent = parent;
_id = id;
}
/// <summary>
/// TBD
/// </summary>
/// <param name="elements">TBD</param>
public void Request(long elements) => _parent.Tell(new SubstreamRequestMore(_id, elements));
/// <summary>
/// TBD
/// </summary>
public void Cancel() => _parent.Tell(new SubstreamCancel(_id));
/// <inheritdoc/>
public override string ToString() => "SubstreamSubscription" + GetHashCode();
}
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
[Serializable]
public struct ExposedPublishers<T> : INoSerializationVerificationNeeded, IDeadLetterSuppression
{
/// <summary>
/// TBD
/// </summary>
public readonly ImmutableList<ActorPublisher<T>> Publishers;
/// <summary>
/// TBD
/// </summary>
/// <param name="publishers">TBD</param>
public ExposedPublishers(ImmutableList<ActorPublisher<T>> publishers)
{
Publishers = publishers;
}
}
}
/// <summary>
/// INTERNAL API
/// </summary>
/// <typeparam name="T">TBD</typeparam>
public abstract class FanOut<T> : ActorBase, IPump
{
#region internal classes
private sealed class AnonymousBatchingInputBuffer : BatchingInputBuffer
{
private readonly FanOut<T> _pump;
public AnonymousBatchingInputBuffer(int count, FanOut<T> pump) : base(count, pump)
{
_pump = pump;
}
protected override void OnError(Exception e) => _pump.Fail(e);
}
#endregion
private readonly ActorMaterializerSettings _settings;
/// <summary>
/// TBD
/// </summary>
protected readonly OutputBunch<T> OutputBunch;
/// <summary>
/// TBD
/// </summary>
protected readonly BatchingInputBuffer PrimaryInputs;
/// <summary>
/// TBD
/// </summary>
/// <param name="settings">TBD</param>
/// <param name="outputCount">TBD</param>
protected FanOut(ActorMaterializerSettings settings, int outputCount)
{
_log = Context.GetLogger();
_settings = settings;
OutputBunch = new OutputBunch<T>(outputCount, Self, this);
PrimaryInputs = new AnonymousBatchingInputBuffer(settings.MaxInputBufferSize, this);
this.Init();
}
#region Actor implementation
/// <summary>
/// TBD
/// </summary>
protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger());
private ILoggingAdapter _log;
/// <summary>
/// TBD
/// </summary>
protected override void PostStop()
{
PrimaryInputs.Cancel();
OutputBunch.Cancel(new AbruptTerminationException(Self));
}
/// <summary>
/// TBD
/// </summary>
/// <param name="reason">TBD</param>
/// <exception cref="IllegalStateException">
/// This exception is thrown automatically since the actor cannot be restarted.
/// </exception>
protected override void PostRestart(Exception reason)
{
base.PostRestart(reason);
throw new IllegalStateException("This actor cannot be restarted");
}
/// <summary>
/// TBD
/// </summary>
/// <param name="e">TBD</param>
protected void Fail(Exception e)
{
if (_settings.IsDebugLogging)
Log.Debug($"fail due to: {e.Message}");
PrimaryInputs.Cancel();
OutputBunch.Cancel(e);
Pump();
}
/// <summary>
/// TBD
/// </summary>
/// <param name="message">TBD</param>
/// <returns>TBD</returns>
protected override bool Receive(object message)
{
return PrimaryInputs.SubReceive.CurrentReceive(message) ||
OutputBunch.SubReceive.CurrentReceive(message);
}
#endregion
#region Pump implementation
/// <summary>
/// TBD
/// </summary>
public TransferState TransferState { get; set; }
/// <summary>
/// TBD
/// </summary>
public Action CurrentAction { get; set; }
/// <summary>
/// TBD
/// </summary>
public bool IsPumpFinished => this.IsPumpFinished();
/// <summary>
/// TBD
/// </summary>
/// <param name="waitForUpstream">TBD</param>
/// <param name="andThen">TBD</param>
public void InitialPhase(int waitForUpstream, TransferPhase andThen)
=> Pumps.InitialPhase(this, waitForUpstream, andThen);
/// <summary>
/// TBD
/// </summary>
/// <param name="waitForUpstream">TBD</param>
public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream);
/// <summary>
/// TBD
/// </summary>
public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this);
/// <summary>
/// TBD
/// </summary>
/// <param name="phase">TBD</param>
public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase);
/// <summary>
/// TBD
/// </summary>
public void Pump() => Pumps.Pump(this);
/// <summary>
/// TBD
/// </summary>
/// <param name="e">TBD</param>
public void PumpFailed(Exception e) => Fail(e);
/// <summary>
/// TBD
/// </summary>
public void PumpFinished()
{
PrimaryInputs.Cancel();
OutputBunch.Complete();
Context.Stop(Self);
}
#endregion
}
/// <summary>
/// INTERNAL API
/// </summary>
internal static class Unzip
{
/// <summary>
/// TBD
/// </summary>
/// <typeparam name="T">TBD</typeparam>
/// <param name="settings">TBD</param>
/// <returns>TBD</returns>
public static Props Props<T>(ActorMaterializerSettings settings)
=> Actor.Props.Create(() => new Unzip<T>(settings, 2)).WithDeploy(Deploy.Local);
}
/// <summary>
/// INTERNAL API
/// TODO Find out where this class will be used and check if the type parameter fit
/// since we need to cast messages into a tuple and therefore maybe need additional type parameters
/// </summary>
/// <typeparam name="T">TBD</typeparam>
internal sealed class Unzip<T> : FanOut<T>
{
/// <summary>
/// TBD
/// </summary>
/// <param name="settings">TBD</param>
/// <param name="outputCount">TBD</param>
/// <exception cref="ArgumentException">TBD
/// This exception is thrown when the elements in <see cref="Akka.Streams.Implementation.FanOut{T}.PrimaryInputs"/>
/// are of an unknown type.
/// </exception>>
public Unzip(ActorMaterializerSettings settings, int outputCount = 2) : base(settings, outputCount)
{
OutputBunch.MarkAllOutputs();
InitialPhase(1, new TransferPhase(PrimaryInputs.NeedsInput.And(OutputBunch.AllOfMarkedOutputs), () =>
{
var message = PrimaryInputs.DequeueInputElement();
var tuple = message as Tuple<T, T>;
if (tuple == null)
throw new ArgumentException($"Unable to unzip elements of type {message.GetType().Name}");
OutputBunch.Enqueue(0, tuple.Item1);
OutputBunch.Enqueue(1, tuple.Item2);
}));
}
}
}
| |
// 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.Runtime.Remoting;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Globalization;
using System.Diagnostics.Contracts;
namespace System
{
#if FEATURE_SERIALIZATION
[Serializable]
#endif
internal sealed class DelegateSerializationHolder : IObjectReference, ISerializable
{
#region Static Members
[System.Security.SecurityCritical] // auto-generated
internal static DelegateEntry GetDelegateSerializationInfo(
SerializationInfo info, Type delegateType, Object target, MethodInfo method, int targetIndex)
{
// Used for MulticastDelegate
if (method == null)
throw new ArgumentNullException("method");
Contract.EndContractBlock();
if (!method.IsPublic || (method.DeclaringType != null && !method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
Type c = delegateType.BaseType;
if (c == null || (c != typeof(Delegate) && c != typeof(MulticastDelegate)))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDelegate"),"type");
if (method.DeclaringType == null)
throw new NotSupportedException(Environment.GetResourceString("NotSupported_GlobalMethodSerialization"));
DelegateEntry de = new DelegateEntry(delegateType.FullName, delegateType.Module.Assembly.FullName, target,
method.ReflectedType.Module.Assembly.FullName, method.ReflectedType.FullName, method.Name);
if (info.MemberCount == 0)
{
info.SetType(typeof(DelegateSerializationHolder));
info.AddValue("Delegate",de,typeof(DelegateEntry));
}
// target can be an object so it needs to be added to the info, or else a fixup is needed
// when deserializing, and the fixup will occur too late. If it is added directly to the
// info then the rules of deserialization will guarantee that it will be available when
// needed
if (target != null)
{
String targetName = "target" + targetIndex;
info.AddValue(targetName, de.target);
de.target = targetName;
}
// Due to a number of additions (delegate signature binding relaxation, delegates with open this or closed over the
// first parameter and delegates over generic methods) we need to send a deal more information than previously. We can
// get this by serializing the target MethodInfo. We still need to send the same information as before though (the
// DelegateEntry above) for backwards compatibility. And we want to send the MethodInfo (which is serialized via an
// ISerializable holder) as a top-level child of the info for the same reason as the target above -- we wouldn't have an
// order of deserialization guarantee otherwise.
String methodInfoName = "method" + targetIndex;
info.AddValue(methodInfoName, method);
return de;
}
#endregion
#region Definitions
[Serializable]
internal class DelegateEntry
{
#region Internal Data Members
internal String type;
internal String assembly;
internal Object target;
internal String targetTypeAssembly;
internal String targetTypeName;
internal String methodName;
internal DelegateEntry delegateEntry;
#endregion
#region Constructor
internal DelegateEntry(
String type, String assembly, Object target, String targetTypeAssembly, String targetTypeName, String methodName)
{
this.type = type;
this.assembly = assembly;
this.target = target;
this.targetTypeAssembly = targetTypeAssembly;
this.targetTypeName = targetTypeName;
this.methodName = methodName;
}
#endregion
#region Internal Members
internal DelegateEntry Entry
{
get { return delegateEntry; }
set { delegateEntry = value; }
}
#endregion
}
#endregion
#region Private Data Members
private DelegateEntry m_delegateEntry;
private MethodInfo[] m_methods;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
private DelegateSerializationHolder(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
bool bNewWire = true;
try
{
m_delegateEntry = (DelegateEntry)info.GetValue("Delegate", typeof(DelegateEntry));
}
catch
{
// Old wire format
m_delegateEntry = OldDelegateWireFormat(info, context);
bNewWire = false;
}
if (bNewWire)
{
// retrieve the targets
DelegateEntry deiter = m_delegateEntry;
int count = 0;
while (deiter != null)
{
if (deiter.target != null)
{
string stringTarget = deiter.target as string; //need test to pass older wire format
if (stringTarget != null)
deiter.target = info.GetValue(stringTarget, typeof(Object));
}
count++;
deiter = deiter.delegateEntry;
}
// If the sender is as recent as us they'll have provided MethodInfos for each delegate. Look for these and pack
// them into an ordered array if present.
MethodInfo[] methods = new MethodInfo[count];
int i;
for (i = 0; i < count; i++)
{
String methodInfoName = "method" + i;
methods[i] = (MethodInfo)info.GetValueNoThrow(methodInfoName, typeof(MethodInfo));
if (methods[i] == null)
break;
}
// If we got the info then make the array available for deserialization.
if (i == count)
m_methods = methods;
}
}
#endregion
#region Private Members
private void ThrowInsufficientState(string field)
{
throw new SerializationException(
Environment.GetResourceString("Serialization_InsufficientDeserializationState", field));
}
private DelegateEntry OldDelegateWireFormat(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
String delegateType = info.GetString("DelegateType");
String delegateAssembly = info.GetString("DelegateAssembly");
Object target = info.GetValue("Target", typeof(Object));
String targetTypeAssembly = info.GetString("TargetTypeAssembly");
String targetTypeName = info.GetString("TargetTypeName");
String methodName = info.GetString("MethodName");
return new DelegateEntry(delegateType, delegateAssembly, target, targetTypeAssembly, targetTypeName, methodName);
}
[System.Security.SecurityCritical]
private Delegate GetDelegate(DelegateEntry de, int index)
{
Delegate d;
try
{
if (de.methodName == null || de.methodName.Length == 0)
ThrowInsufficientState("MethodName");
if (de.assembly == null || de.assembly.Length == 0)
ThrowInsufficientState("DelegateAssembly");
if (de.targetTypeName == null || de.targetTypeName.Length == 0)
ThrowInsufficientState("TargetTypeName");
// We cannot use Type.GetType directly, because of AppCompat - assembly names starting with '[' would fail to load.
RuntimeType type = (RuntimeType)Assembly.GetType_Compat(de.assembly, de.type);
RuntimeType targetType = (RuntimeType)Assembly.GetType_Compat(de.targetTypeAssembly, de.targetTypeName);
// If we received the new style delegate encoding we already have the target MethodInfo in hand.
if (m_methods != null)
{
#if FEATURE_REMOTING
Object target = de.target != null ? RemotingServices.CheckCast(de.target, targetType) : null;
#else
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
Object target=de.target;
#endif
d = Delegate.CreateDelegateNoSecurityCheck(type, target, m_methods[index]);
}
else
{
if (de.target != null)
#if FEATURE_REMOTING
d = Delegate.CreateDelegate(type, RemotingServices.CheckCast(de.target, targetType), de.methodName);
#else
{
if(!targetType.IsInstanceOfType(de.target))
throw new InvalidCastException();
d = Delegate.CreateDelegate(type, de.target, de.methodName);
}
#endif
else
d = Delegate.CreateDelegate(type, targetType, de.methodName);
}
if ((d.Method != null && !d.Method.IsPublic) || (d.Method.DeclaringType != null && !d.Method.DeclaringType.IsVisible))
new ReflectionPermission(ReflectionPermissionFlag.MemberAccess).Demand();
}
catch (Exception e)
{
if (e is SerializationException)
throw e;
throw new SerializationException(e.Message, e);
}
return d;
}
#endregion
#region IObjectReference
[System.Security.SecurityCritical] // auto-generated
public Object GetRealObject(StreamingContext context)
{
int count = 0;
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
count++;
int maxindex = count - 1;
if (count == 1)
{
return GetDelegate(m_delegateEntry, 0);
}
else
{
object[] invocationList = new object[count];
for (DelegateEntry de = m_delegateEntry; de != null; de = de.Entry)
{
// Be careful to match the index we pass to GetDelegate (used to look up extra information for each delegate) to
// the order we process the entries: we're actually looking at them in reverse order.
--count;
invocationList[count] = GetDelegate(de, maxindex - count);
}
return ((MulticastDelegate)invocationList[0]).NewMulticastDelegate(invocationList, invocationList.Length);
}
}
#endregion
#region ISerializable
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotSupportedException(Environment.GetResourceString("NotSupported_DelegateSerHolderSerial"));
}
#endregion
}
}
| |
#region Using
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using String = Messages.std_msgs.String;
#endregion
namespace Messages
{
[System.Diagnostics.DebuggerStepThrough]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static class SerializationHelper
{
private static bool WHAT_IS_HAPPENING;
public static void ShowDeserializationSteps()
{
WHAT_IS_HAPPENING = true;
}
static Dictionary<Type, MsgTypes> GetMessageTypeMemo = new Dictionary<Type, MsgTypes>();
//[DebuggerStepThrough]
public static MsgTypes GetMessageType(Type t)
{
MsgTypes mt;
//gross, but it gets the job done
if (t == typeof(Boolean) && !GetMessageTypeMemo.ContainsKey(t)) //ERIC
lock (GetMessageTypeMemo)
{
if (!GetMessageTypeMemo.ContainsKey(t))
GetMessageTypeMemo.Add(t, (MsgTypes) Enum.Parse(typeof (MsgTypes), "std_msgs__Bool")); //ERIC
}
if (GetMessageTypeMemo.ContainsKey(t))
return GetMessageTypeMemo[t];
lock (GetMessageTypeMemo)
{
if (GetMessageTypeMemo.ContainsKey(t))
return GetMessageTypeMemo[t];
mt = GetMessageType(t.FullName);
GetMessageTypeMemo.Add(t, mt);
return mt;
}
}
//[DebuggerStepThrough]
public static Type GetType(string s)
{
Type ret;
MsgTypes mt = GetMessageType(s);
if (mt == MsgTypes.Unknown)
ret = Type.GetType(s, true, true);
else
ret = IRosMessage.generate(mt).GetType();
// Console.WriteLine(s + "=" + ret.Name);
return ret;
}
static Dictionary<string, MsgTypes> GetMessageTypeMemoString = new Dictionary<string, MsgTypes>();
//[DebuggerStepThrough]
public static MsgTypes GetMessageType(string s)
{
//Console.WriteLine("LOOKING FOR: " + s + "'s type");
lock (GetMessageTypeMemoString)
{
if (GetMessageTypeMemoString.ContainsKey(s))
return GetMessageTypeMemoString[s];
if (s.Contains("TimeData"))
{
GetMessageTypeMemoString.Add(s, MsgTypes.std_msgs__Time);
return MsgTypes.std_msgs__Time;
}
if (!s.Contains("Messages"))
{
if (s.Contains("System."))
{
Array types = Enum.GetValues(typeof(MsgTypes));
string test = s.Replace("[]", "").Split('.')[1];
string testmsgtype;
MsgTypes m = MsgTypes.Unknown;
for (int i = 0; i < types.Length; i++)
{
testmsgtype = types.GetValue(i).ToString();
if (!testmsgtype.Contains("std_msgs")) continue;
string[] pieces = testmsgtype.Split(new[] { '_' }, StringSplitOptions.RemoveEmptyEntries);
testmsgtype = pieces[pieces.Length - 1];
if (testmsgtype.ToLower().Equals(test.ToLower()))
{
m = (MsgTypes)types.GetValue(i);
break;
}
}
GetMessageTypeMemoString.Add(s, m);
return m;
}
return MsgTypes.Unknown;
}
MsgTypes ms = (MsgTypes)Enum.Parse(typeof(MsgTypes), s.Replace("Messages.", "").Replace(".", "__").Replace("[]", ""));
GetMessageTypeMemoString.Add(s, ms);
return ms;
}
}
[DebuggerStepThrough]
public static bool IsSizeKnown(Type T, bool recurse)
{
if (T == typeof(string) || T == typeof(String) ||
(T.FullName != null && T.FullName.Contains("Messages.std_msgs.String")) /*|| T.IsArray ERIC*/)
return false;
if (T.FullName.Contains("System.") || T.FullName.Contains("Messages.std_msgs.Time") || T.FullName.Contains("Messages.std_msgs.Duration"))
return true;
if (!recurse || !T.FullName.Contains("Messages")) return true;
FieldInfo[] infos = T.GetFields();
bool b = true;
foreach (FieldInfo info in infos)
{
string fullName = info.FieldType.FullName;
if (fullName != null)
{
if (fullName.Contains("Messages."))
{
MsgTypes MT = GetMessageType(info.FieldType);
IRosMessage TI = IRosMessage.generate(MT);
b &= IsSizeKnown(TI.GetType(), true); //TI.Fields[info.Name].Type != typeof(string) && TI.Fields[info.Name].Type != typeof(String) && (!TI.Fields[info.Name].IsArray || TI.Fields[info.Name].Length != -1);
}
else
b &= !info.FieldType.IsArray && info.FieldType != typeof(string);
}
if (!b)
break;
}
return b;
}
internal static T Deserialize<T>(byte[] bytes) where T : IRosMessage, new()
{
return Deserialize<T>(bytes, null);
}
internal static T Deserialize<T>(byte[] bytes, Type container) where T : IRosMessage, new()
{
int dontcare = 0;
return _deserialize(typeof(T), container, bytes, out dontcare, IsSizeKnown(typeof(T), true)) as T;
}
public static object deserialize(Type T, Type container, byte[] bytes, out int amountread)
{
return deserialize(T, container, bytes, out amountread, false);
}
public static object deserialize(Type T, Type container, byte[] bytes, out int amountread, bool sizeknown)
{
try
{
return _deserialize(T, container, bytes, out amountread, sizeknown);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
amountread = 0;
return null;
}
private static Dictionary<MsgTypes, FieldInfo[]> speedyFields = new Dictionary<MsgTypes, FieldInfo[]>();
private static Dictionary<MsgTypes, List<string>> importantfieldnames = new Dictionary<MsgTypes, List<string>>();
public static FieldInfo[] GetFields(Type T, ref object instance, out IRosMessage msg)
{
if (instance == null)
{
if (T.IsArray)
instance = Array.CreateInstance(T.GetElementType(), 0);
else
instance = Activator.CreateInstance(T);
}
IRosMessage MSG = instance as IRosMessage;
if (MSG == null)
{
msg = MSG;
return instance.GetType().GetFields();
}
MsgTypes MT = MSG.msgtype;
if (MT != MsgTypes.Unknown)
{
msg = MSG;
return msg.GetType().GetFields().Where((fi => MSG.Fields.Keys.Contains(fi.Name) && !fi.IsStatic)).ToArray();
}
throw new Exception("GetFields is weaksauce");
}
public static string dumphex(byte[] test)
{
if (test == null)
return "dumphex(null)";
string s = "";
for (int i = 0; i < test.Length; i++)
s += (test[i] < 16 ? "0" : "") + test[i].ToString("x") + " ";
return s;
}
private static object _deserialize(Type T, Type container, byte[] bytes, out int amountread, bool sizeknown)
{
if (bytes == null && !WHAT_IS_HAPPENING || bytes.Length == 0 && !WHAT_IS_HAPPENING)
{
// Console.WriteLine("Deserializing empty array?");
amountread = 0;
return null;
}
object thestructure = null;
if (T.FullName.Contains("System.") && !T.IsCOMObject && !T.IsArray && T != typeof(string))
{
thestructure = new object();
int size = Marshal.SizeOf(T);
IntPtr mem = IntPtr.Zero;
if (bytes.Length != 0)
{
mem = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, mem, size);
}
amountread = size;
if (WHAT_IS_HAPPENING)
{
/*
Console.WriteLine("//deserialize: " + T.FullName);
/*Console.WriteLine(string.Format(@" $A = new {0}();
IntPtr $B = Marshal.AllocHGlobal({1})
Marshal.Copy(bytes, 0, $B, {1});
$A = Marshal.PtrToStructure($B, typeof({0}));
", T.FullName, Marshal.SizeOf(T)));*/
}
if (mem == IntPtr.Zero) return null;
object obj = Marshal.PtrToStructure(mem, T);
Marshal.FreeHGlobal(mem);
return obj;
}
IRosMessage MSG;
int startingpos = 0, currpos = 0;
/*if (container==null)
currpos = 4;*/
MsgTypes MT = MsgTypes.Unknown;
FieldInfo[] infos = GetFields(T, ref thestructure, out MSG);
if (MSG != null)
MT = MSG.msgtype;
startingpos = currpos;
int currinfo = 0;
while ((currpos < bytes.Length || WHAT_IS_HAPPENING) && currinfo < infos.Length)
{
// Console.WriteLine(infos[currinfo].Name + "(" + currpos + "/" + bytes.Length + ")");
Type type = GetType(infos[currinfo].FieldType.FullName);
//Console.WriteLine("GetType returned: " + type.FullName);
Type realtype = infos[currinfo].FieldType;
MsgTypes msgtype = GetMessageType(type);
bool knownpiecelength = IsSizeKnown(realtype, true) && MSG.Fields != null && !MSG.Fields[infos[currinfo].Name].IsArray || MSG.Fields[infos[currinfo].Name].Length != -1;
if (realtype == typeof(Byte[])) //this is deplorable.
{
//SHORTCUT
byte[] PWNED;
MsgFieldInfo mfi = MSG.Fields[infos[currinfo].Name];
int num = mfi.Length;
if (mfi.Length == -1) //if -1, then array length not in definition
{
num = BitConverter.ToInt32(bytes, currpos);
currpos += 4;
}
PWNED = new byte[num];
Array.Copy(bytes, currpos, PWNED, 0, num);
currpos += PWNED.Length;
infos[currinfo].SetValue(thestructure, PWNED);
PWNED = null;
}
else if (realtype == typeof(Boolean[]))
{
bool[] PWNED;
MsgFieldInfo mfi = MSG.Fields[infos[currinfo].Name];
int num = mfi.Length;
if (mfi.Length == -1) //if -1, then array length not in definition
{
num = BitConverter.ToInt32(bytes, currpos);
currpos += 4;
}
PWNED = new bool[num];
for (int i = 0; i < num; i++ )
{
PWNED[i] = bytes[i + currpos] > 0;
}
currpos += PWNED.Length;
infos[currinfo].SetValue(thestructure, PWNED);
PWNED = null;
}
else if (knownpiecelength)
{
if (infos[currinfo].FieldType.IsArray && msgtype != MsgTypes.std_msgs__String)
//must have length defined, or else knownpiecelength would be false... so look it up in the dict!
{
Type TT = GetType(infos[currinfo].FieldType.GetElementType().FullName);
if (TT.IsArray)
throw new Exception("ERIC, YOU NEED TO MAKE DESERIALIZATION RECURSE!!!");
Array vals = (infos[currinfo].GetValue(thestructure) as Array);
if (vals != null)
{
for (int i = 0; i < vals.Length; i++)
{
MsgTypes mt = GetMessageType(TT);
int leng = 0;
Type et = realtype.GetElementType();
if (mt == MsgTypes.Unknown)
leng = Marshal.SizeOf(et);
if (leng == 0)
leng = Marshal.SizeOf(vals.GetValue(i));
if (leng == 0)
throw new Exception("LENGTH ENUMERATION FAIL IN DESERIALIZE!");
if (leng + currpos <= bytes.Length)
{
IntPtr pIP = Marshal.AllocHGlobal(leng);
Marshal.Copy(bytes, currpos, pIP, leng);
object o = Marshal.PtrToStructure(pIP, TT);
vals.SetValue(o, i);
Marshal.FreeHGlobal(pIP);
}
else
vals.SetValue(null, i);
currpos += leng;
}
}
infos[currinfo].SetValue(thestructure, vals);
}
else
{
if (type.FullName != null && type.FullName.Contains("Message"))
{
if (GetMessageType(realtype) == MsgTypes.std_msgs__Time || GetMessageType(realtype) == MsgTypes.std_msgs__Duration || infos[currinfo].FieldType == typeof(TimeData))
{
TimeData td;
if (currpos + 8 <= bytes.Length)
{
uint u1 = BitConverter.ToUInt32(bytes, currpos);
uint u2 = BitConverter.ToUInt32(bytes, currpos + 4);
td = new TimeData(u1, u2);
}
else
td = new TimeData(0, 0);
currpos += 8;
if (infos[currinfo].FieldType == typeof(TimeData))
infos[currinfo].SetValue(thestructure, td);
else if (GetMessageType(realtype) == MsgTypes.std_msgs__Time)
infos[currinfo].SetValue(thestructure, (object)new std_msgs.Time(td));
else
infos[currinfo].SetValue(thestructure, (object)new std_msgs.Duration(td));
}
else
{
byte[] piece = new byte[bytes.Length != 0 ? bytes.Length - currpos : 0];
if (bytes.Length != 0)
Array.Copy(bytes, currpos, piece, 0, piece.Length);
int len = 0;
object obj = _deserialize(realtype, T, piece, out len,
IsSizeKnown(realtype, true));
//if ((int)(infos[currinfo].Attributes & FieldAttributes.InitOnly) != 0)
infos[currinfo].SetValue(thestructure, obj);
currpos += len;
}
}
else if (msgtype == MsgTypes.std_msgs__Bool)
{
infos[currinfo].SetValue(thestructure, bytes[currpos] != 0);
currpos++;
}
else
{
int len = Marshal.SizeOf(infos[currinfo].GetValue(thestructure));
IntPtr pIP = Marshal.AllocHGlobal(len);
object obj = null;
if (currpos + len <= bytes.Length)
{
Marshal.Copy(bytes, currpos, pIP, len);
obj = Marshal.PtrToStructure(pIP, infos[currinfo].FieldType);
}
infos[currinfo].SetValue(thestructure, obj);
currpos += len;
}
}
}
else
{
Type ft = realtype;
if (ft.IsArray)
{
Type TT = ft.GetElementType();
Array val = infos[currinfo].GetValue(thestructure) as Array;
int chunklen = 0;
if (val == null)
{
if (currpos + 4 <= bytes.Length)
{
chunklen = BitConverter.ToInt32(bytes, currpos);
currpos += 4;
val = Array.CreateInstance(TT, chunklen);
}
else
{
currpos += 4;
val = Array.CreateInstance(TT, 0);
}
}
else
{
chunklen = val.Length;
}
if (TT == null)
throw new Exception("LENGTHLESS ARRAY FAIL -- ELEMENT TYPE IS NULL!");
if (TT.FullName.Contains("Message."))
throw new Exception("NOT YET, YOUNG PATAWAN");
MsgTypes mt = GetMessageType(TT);
if (mt == MsgTypes.std_msgs__Byte || mt == MsgTypes.std_msgs__UInt8 || mt == MsgTypes.std_msgs__Int8)
{
int num = val.Length;
byte[] PWNED = new byte[num];
if (currpos + num <= bytes.Length)
{
Array.Copy(bytes, currpos, PWNED, 0, num);
}
currpos += num;
infos[currinfo].SetValue(thestructure, PWNED);
}
else if (TT.FullName != null && TT.FullName.Contains("Message"))
{
for (int i = 0; i < chunklen; i++)
{
byte[] chunk = new byte[bytes.Length - currpos];
Array.Copy(bytes, currpos, chunk, 0, chunk.Length);
int len = 0;
object data = _deserialize(TT, T, chunk, out len,
IsSizeKnown(TT, false));
val.SetValue(data, i);
currpos += len;
}
infos[currinfo].SetValue(thestructure, val);
}
else if (TT == typeof (string))
{
for (int i = 0; i < chunklen; i++)
{
int len = 0;
if (currpos + 4 <= bytes.Length)
len = BitConverter.ToInt32(bytes, currpos);
byte[] piece = new byte[len];
currpos += 4;
if (currpos + len <= bytes.Length)
Array.Copy(bytes, currpos, piece, 0, len);
string str = Encoding.ASCII.GetString(piece);
val.SetValue(str, i);
currpos += len;
}
infos[currinfo].SetValue(thestructure, val);
}
else
{
int len = Marshal.SizeOf(TT);
IntPtr pIP = IntPtr.Zero;
if (currpos + len * chunklen <= bytes.Length)
{
pIP = Marshal.AllocHGlobal(len * chunklen);
Marshal.Copy(bytes, currpos, pIP, len * chunklen);
}
object o = null;
for (int i = 0; i < chunklen * len; i += len)
{
if (pIP != IntPtr.Zero)
o = Marshal.PtrToStructure(pIP, TT);
val.SetValue(o, i / len);
if (pIP != IntPtr.Zero)
pIP = new IntPtr(pIP.ToInt32() + len);
}
infos[currinfo].SetValue(thestructure, val);
currpos += chunklen * len;
}
}
else
{
if (ft.FullName != null && ft.FullName.Contains("Message"))
{
IRosMessage msg = (IRosMessage)Activator.CreateInstance(ft);
Type t = GetType(msg.GetType().FullName);
bool knownsize = IsSizeKnown(t, false) && MSG.Fields != null && !MSG.Fields[infos[currinfo].Name].IsArray || MSG.Fields[infos[currinfo].Name].Length != -1;
if (!knownsize && t.GetField("data").FieldType == typeof(string))
{
int len = -4;
if (currpos + 4 <= bytes.Length)
len = BitConverter.ToInt32(bytes, currpos);
byte[] smallerpiece = new byte[len + 4];
if (currpos + 4 <= bytes.Length)
Array.Copy(bytes, currpos, smallerpiece, 0, smallerpiece.Length);
int dontcare = 0;
msg = _deserialize(t, T, smallerpiece, out dontcare, false) as IRosMessage;
if (bytes.Length != 0 && dontcare != len + 4)
throw new Exception("WTF?!");
infos[currinfo].SetValue(thestructure, msg);
currpos += len + 4;
}
else // if (!knownsize)
{
byte[] smallerpiece = new byte[bytes.Length != 0 ? bytes.Length - currpos : 0];
if (bytes.Length != 0)
Array.Copy(bytes, currpos, smallerpiece, 0, smallerpiece.Length);
int len = 0;
msg = _deserialize(t, T, smallerpiece, out len, knownsize) as IRosMessage;
infos[currinfo].SetValue(thestructure, msg);
currpos += len;
}
/*else
{
throw new Exception("THIS BROKE SOMEHOW! FIX IT!");
}*/
}
else
{
if (infos[currinfo].FieldType == typeof(string))
{
int len = 0;
if (currpos + 4 <= bytes.Length)
len = BitConverter.ToInt32(bytes, currpos);
byte[] piece = new byte[len];
currpos += 4;
if (currpos + len <= bytes.Length)
Array.Copy(bytes, currpos, piece, 0, len);
string str = Encoding.ASCII.GetString(piece);
infos[currinfo].SetValue(thestructure, str);
currpos += len;
}
else
{
//Console.WriteLine("ZOMG HANDLE: " + infos[currinfo].FieldType.FullName);
amountread = currpos - startingpos;
return thestructure;
}
}
}
}
currinfo++;
}
amountread = currpos - startingpos;
infos = null;
bytes = null;
return thestructure;
}
internal static byte[] Serialize<T>(T outgoing)
where T : IRosMessage, new()
{
return Serialize(outgoing, false);
}
internal static byte[] Serialize<T>(T outgoing, bool partofsomethingelse)
where T : IRosMessage, new()
{
outgoing.Serialized = SlapChop(outgoing.GetType(), outgoing, partofsomethingelse);
return outgoing.Serialized;
}
public static byte[] SlapChop(Type T, object instance)
{
return SlapChop(T, instance, false);
}
public static byte[] SlapChop(Type T, object instance, bool partofsomethingelse)
{
IRosMessage msg;
FieldInfo[] infos = GetFields(T, ref instance, out msg);
Queue<byte[]> chunks = new Queue<byte[]>();
int totallength = 0;
MsgTypes MT = msg.msgtype;
foreach (FieldInfo info in infos)
{
if (info.Name.Contains("(")) continue;
if (msg.Fields[info.Name].IsConst) continue;
if (info.GetValue(instance) == null)
{
if (info.FieldType == typeof(string))
info.SetValue(instance, "");
else if (info.FieldType.IsArray)
info.SetValue(instance, Array.CreateInstance(info.FieldType.GetElementType(), 0));
else if (info.FieldType.FullName != null && !info.FieldType.FullName.Contains("Messages."))
info.SetValue(instance, 0);
else
info.SetValue(instance, Activator.CreateInstance(info.FieldType));
}
bool knownpiecelength = msg.Fields[info.Name].Type !=
typeof(string) &&
(!msg.Fields[info.Name].IsArray ||
msg.Fields[info.Name].Length != -1);
byte[] thischunk = NeedsMoreChunks(info.FieldType, info.GetValue(instance), ref knownpiecelength);
chunks.Enqueue(thischunk);
totallength += thischunk.Length;
}
byte[] wholeshebang = new byte[totallength];
int currpos = 0;
if (!partofsomethingelse)
{
wholeshebang = new byte[totallength + 4]; //THE WHOLE SHEBANG
byte[] len = BitConverter.GetBytes(totallength);
Array.Copy(len, 0, wholeshebang, 0, 4);
currpos = 4;
}
while (chunks.Count > 0)
{
byte[] chunk = chunks.Dequeue();
Array.Copy(chunk, 0, wholeshebang, currpos, chunk.Length);
currpos += chunk.Length;
}
return wholeshebang;
}
public static byte[] NeedsMoreChunks(Type T, object val, ref bool knownlength)
{
byte[] thischunk = null;
if (!T.IsArray)
{
if (T != typeof(TimeData) && T.Namespace.Contains("Message"))
{
IRosMessage msg = null;
if (val != null)
msg = val as IRosMessage;
else
msg = (IRosMessage)Activator.CreateInstance(T);
thischunk = msg.Serialize(true);
}
else if (T == typeof(byte) || T.HasElementType && T.GetElementType() == typeof(byte))
{
if (T.IsArray)
{
if (!knownlength)
{
Array ar = (val as Array);
byte[] nolen = new byte[ar.Length];
Array.Copy(ar, 0, nolen, 0, ar.Length);
thischunk = new byte[nolen.Length + 4];
byte[] bylen2 = BitConverter.GetBytes(nolen.Length);
Array.Copy(nolen, 0, thischunk, 4, nolen.Length);
Array.Copy(bylen2, thischunk, 4);
}
else
{
Array ar = (val as Array);
thischunk = new byte[ar.Length];
Array.Copy(ar, 0, thischunk, 0, ar.Length);
knownlength = false;
}
}
else
{
thischunk = new[] { (byte)val };
}
}
else if (val is string || T == typeof(string))
{
if (!knownlength)
{
if (val == null)
val = "";
byte[] nolen = Encoding.ASCII.GetBytes((string)val);
thischunk = new byte[nolen.Length + 4];
byte[] bylen2 = BitConverter.GetBytes(nolen.Length);
Array.Copy(nolen, 0, thischunk, 4, nolen.Length);
Array.Copy(bylen2, thischunk, 4);
}
else
{
thischunk = Encoding.ASCII.GetBytes((string)val);
knownlength = false;
}
}
else if (val is bool || T == typeof(bool))
{
thischunk = new byte[1];
thischunk[0] = (byte)((bool)val ? 1 : 0);
}
else
{
byte[] temp = new byte[Marshal.SizeOf(T)];
GCHandle h = GCHandle.Alloc(temp, GCHandleType.Pinned);
Marshal.StructureToPtr(val, h.AddrOfPinnedObject(), false);
h.Free();
thischunk = new byte[temp.Length + (knownlength ? 0 : 4)];
if (!knownlength)
{
byte[] bylen = BitConverter.GetBytes(temp.Length);
Array.Copy(bylen, 0, thischunk, 0, 4);
}
Array.Copy(temp, 0, thischunk, (knownlength ? 0 : 4), temp.Length);
}
}
else
{
int arraylength = 0;
Array valArray = val as Array;
List<byte> thechunk = new List<byte>();
for(int i=0;i<valArray.GetLength(0);i++)
{
if (valArray.GetValue(i) == null)
valArray.SetValue(Activator.CreateInstance(T.GetElementType()),i);
Type TT = valArray.GetValue(i).GetType();
MsgTypes mt = GetMessageType(TT);
bool piecelengthknown = mt != MsgTypes.std_msgs__String;
thechunk.AddRange(NeedsMoreChunks(TT, valArray.GetValue(i), ref piecelengthknown));
}
if (!knownlength)
{
thechunk.InsertRange(0, BitConverter.GetBytes(valArray.GetLength(0)));
}
return thechunk.ToArray();
}
return thischunk;
}
}
[System.Diagnostics.DebuggerStepThrough]
public class MsgFieldInfo
{
public string ConstVal;
public bool IsArray;
public bool IsConst;
public bool IsLiteral;
public bool IsMetaType;
public int Length = -1;
public string Name;
public Type Type;
public MsgTypes message_type;
[DebuggerStepThrough]
public MsgFieldInfo(string name, bool isliteral, Type type, bool isconst, string constval, bool isarray,
string lengths, bool meta, MsgTypes mt)
{
Name = name;
IsArray = isarray;
Type = type;
IsLiteral = isliteral;
IsMetaType = meta;
IsConst = isconst;
ConstVal = constval;
if (lengths == null) return;
if (lengths.Length > 0)
{
Length = int.Parse(lengths);
}
message_type = mt;
}
}
public enum ServiceMessageType
{
Not,
Request,
Response
}
[System.Diagnostics.DebuggerStepThrough]
public struct TimeData
{
public uint sec;
public uint nsec;
public TimeData(uint s, uint ns)
{
sec = s;
nsec = ns;
}
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using HETSAPI.Models;
namespace HETSAPI.ViewModels
{
/// <summary>
/// Current User View Model
/// </summary>
[DataContract]
public sealed class CurrentUserViewModel : IEquatable<CurrentUserViewModel>
{
/// <summary>
/// Current User View Model Constructor
/// </summary>
public CurrentUserViewModel()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CurrentUserViewModel" /> class.
/// </summary>
/// <param name="id">Id.</param>
/// <param name="givenName">GivenName.</param>
/// <param name="surname">Surname.</param>
/// <param name="email">Email.</param>
/// <param name="active">Active.</param>
/// <param name="smUserId">SmUserId.</param>
/// <param name="smAuthorizationDirectory">SmAuthorizationDirectory.</param>
/// <param name="userRoles">UserRoles.</param>
/// <param name="district">The District to which this User is affliated..</param>
public CurrentUserViewModel(int id, string givenName = null, string surname = null, string email = null, bool? active = null,
string smUserId = null, string smAuthorizationDirectory = null, List<UserRole> userRoles = null,
District district = null)
{
Id = id;
GivenName = givenName;
Surname = surname;
Email = email;
Active = active;
SmUserId = smUserId;
SmAuthorizationDirectory = smAuthorizationDirectory;
UserRoles = userRoles;
District = district;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id")]
public int? Id { get; set; }
/// <summary>
/// Gets or Sets GivenName
/// </summary>
[DataMember(Name="givenName")]
public string GivenName { get; set; }
/// <summary>
/// Gets or Sets Surname
/// </summary>
[DataMember(Name="surname")]
public string Surname { get; set; }
/// <summary>
/// Gets or Sets Email
/// </summary>
[DataMember(Name="email")]
public string Email { get; set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active")]
public bool? Active { get; set; }
/// <summary>
/// Gets or Sets SmUserId
/// </summary>
[DataMember(Name="smUserId")]
public string SmUserId { get; set; }
/// <summary>
/// Gets or Sets SmAuthorizationDirectory
/// </summary>
[DataMember(Name="smAuthorizationDirectory")]
public string SmAuthorizationDirectory { get; set; }
/// <summary>
/// Gets or Sets UserRoles
/// </summary>
[DataMember(Name="userRoles")]
public List<UserRole> UserRoles { get; set; }
/// <summary>
/// The District to which this User is affliated.
/// </summary>
/// <value>The District to which this User is affliated.</value>
[DataMember(Name="district")]
[MetaData (Description = "The District to which this User is affliated.")]
public District District { 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 CurrentUserViewModel {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" GivenName: ").Append(GivenName).Append("\n");
sb.Append(" Surname: ").Append(Surname).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" SmUserId: ").Append(SmUserId).Append("\n");
sb.Append(" SmAuthorizationDirectory: ").Append(SmAuthorizationDirectory).Append("\n");
sb.Append(" UserRoles: ").Append(UserRoles).Append("\n");
sb.Append(" District: ").Append(District).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)
{
if (obj is null) { return false; }
if (ReferenceEquals(this, obj)) { return true; }
return obj.GetType() == GetType() && Equals((CurrentUserViewModel)obj);
}
/// <summary>
/// Returns true if CurrentUserViewModel instances are equal
/// </summary>
/// <param name="other">Instance of CurrentUserViewModel to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CurrentUserViewModel other)
{
if (other is null) { return false; }
if (ReferenceEquals(this, other)) { return true; }
return
(
Id == other.Id ||
Id != null &&
Id.Equals(other.Id)
) &&
(
GivenName == other.GivenName ||
GivenName != null &&
GivenName.Equals(other.GivenName)
) &&
(
Surname == other.Surname ||
Surname != null &&
Surname.Equals(other.Surname)
) &&
(
Email == other.Email ||
Email != null &&
Email.Equals(other.Email)
) &&
(
Active == other.Active ||
Active != null &&
Active.Equals(other.Active)
) &&
(
SmUserId == other.SmUserId ||
SmUserId != null &&
SmUserId.Equals(other.SmUserId)
) &&
(
SmAuthorizationDirectory == other.SmAuthorizationDirectory ||
SmAuthorizationDirectory != null &&
SmAuthorizationDirectory.Equals(other.SmAuthorizationDirectory)
) &&
(
UserRoles == other.UserRoles ||
UserRoles != null &&
UserRoles.SequenceEqual(other.UserRoles)
) &&
(
District == other.District ||
District != null &&
District.Equals(other.District)
);
}
/// <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
if (Id != null)
{
hash = hash * 59 + Id.GetHashCode();
}
if (GivenName != null)
{
hash = hash * 59 + GivenName.GetHashCode();
}
if (Surname != null)
{
hash = hash * 59 + Surname.GetHashCode();
}
if (Email != null)
{
hash = hash * 59 + Email.GetHashCode();
}
if (Active != null)
{
hash = hash * 59 + Active.GetHashCode();
}
if (SmUserId != null)
{
hash = hash * 59 + SmUserId.GetHashCode();
}
if (SmAuthorizationDirectory != null)
{
hash = hash * 59 + SmAuthorizationDirectory.GetHashCode();
}
if (UserRoles != null)
{
hash = hash * 59 + UserRoles.GetHashCode();
}
if (District != null)
{
hash = hash * 59 + District.GetHashCode();
}
return hash;
}
}
#region Operators
/// <summary>
/// Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator ==(CurrentUserViewModel left, CurrentUserViewModel right)
{
return Equals(left, right);
}
/// <summary>
/// Not Equals
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static bool operator !=(CurrentUserViewModel left, CurrentUserViewModel right)
{
return !Equals(left, right);
}
#endregion Operators
}
}
| |
using GuiLabs.Editor.Actions;
namespace GuiLabs.Editor.Blocks
{
public static class TokenActions
{
//public static void SetFocusToTheBeginningOfToken(Block token)
//{
// if (token == null)
// {
// return;
// }
// token.SetCursorToTheBeginning();
// token.SetFocus(true);
//}
//public static void SetFocusToTheEndOfToken(Block token)
//{
// if (token == null)
// {
// return;
// }
// token.SetCursorToTheEnd();
// token.SetFocus(true);
//}
public static void SetCursorToTheEndOfPreviousToken(Block block)
{
Block prev = block.FindPrevFocusableBlock();
if (prev != null)
{
prev.SetCursorToTheEnd(true);
}
//else
//{
// ContainerBlock parent = block.Parent;
// if (parent != null)
// {
// Block prevParent = parent.Prev;
// if (prevParent != null)
// {
// prevParent.SetCursorToTheEnd();
// Block toFocus = prevParent.FindLastFocusableBlock();
// }
// }
//}
}
public static void SetCursorToTheBeginningOfNextToken(Block block)
{
Block next = block.FindNextFocusableBlockInChain();
if (next != null)
{
next.SetCursorToTheBeginning(true);
}
}
public static void SetCursorToTheBeginningOfLine(Block currentBlock)
{
if (currentBlock == null)
{
return;
}
ContainerBlock parent = currentBlock.Parent;
if (parent == null)
{
return;
}
Block first = parent.FindFirstFocusableBlock();
if (first == null)
{
return;
}
first.SetCursorToTheBeginning(true);
}
public static void SetCursorToTheEndOfLine(Block currentBlock)
{
if (currentBlock == null)
{
return;
}
ContainerBlock parent = currentBlock.Parent;
if (parent == null)
{
return;
}
Block last = parent.FindLastFocusableBlock();
if (last == null)
{
return;
}
last.SetCursorToTheEnd(true);
}
public static bool SetFocusToPrevious<T>(Block current)
where T : Block
{
while (current != null)
{
current = current.FindPrevFocusableBlock();
if (current != null && current is T)
{
current.SetFocus(true);
return true;
}
}
return false;
}
public static bool SetFocusToNext<T>(Block current)
where T : Block
{
while (current != null)
{
current = current.FindNextFocusableBlock();
if (current != null && current is T)
{
current.SetFocus(true);
return true;
}
}
return false;
}
public static void DeleteSeparatorAndJoinNeighbours(Block separator)
{
TokenBlock prev = separator.Prev as TokenBlock;
TokenBlock next = separator.Next as TokenBlock;
if (separator != null
&& separator.Root != null
&& prev != null
&& next != null
)
{
using (ActionBuilder a = new ActionBuilder(separator.Root))
{
a.RenameItem(prev, prev.Text + next.Text);
a.DeleteBlock(separator).BlockToFocus = prev;
a.DeleteBlock(next);
a.Run();
}
}
}
public static void AppendLineBelowToCurrentLine(Block higherSeparator)
{
if (higherSeparator == null
|| higherSeparator.Parent == null
|| higherSeparator.Parent.Next == null
|| higherSeparator.Next != null)
{
return;
}
ContainerBlock newParent = higherSeparator.Parent;
ContainerBlock oldParent = newParent.Next as ContainerBlock;
Block newFocus = null;
if (oldParent == null)
{
return;
}
else
{
newFocus = oldParent.FindFirstFocusableBlock();
}
ActionBuilder a = new ActionBuilder(higherSeparator.Root);
a.DeleteBlock(higherSeparator);
foreach (Block child in oldParent.Children)
{
a.MoveBlock(newParent, child);
}
a.DeleteBlock(oldParent);
a.RunWithoutRedraw();
if (newFocus != null)
{
newFocus.SetFocus(true);
}
}
public static void AppendSecondLineToFirst(Block lowerSeparator)
{
if (lowerSeparator == null
|| lowerSeparator.Parent == null
|| lowerSeparator.Parent.Prev == null
|| lowerSeparator.Prev != null)
{
return;
}
ContainerBlock oldParent = lowerSeparator.Parent;
ContainerBlock newParent = oldParent.Prev as ContainerBlock;
Block newFocus = null;
if (newParent == null)
{
return;
}
else
{
newFocus = newParent.FindLastFocusableBlock();
}
ActionBuilder a = new ActionBuilder(lowerSeparator.Root);
if (lowerSeparator.Next != null)
{
foreach (Block child in oldParent.Children)
{
if (child != lowerSeparator)
{
a.MoveBlock(newParent, child);
}
}
}
a.DeleteBlock(oldParent);
a.RunWithoutRedraw();
if (newFocus != null)
{
newFocus.SetFocus(true);
}
}
public static void DeleteCurrentLine(Block current)
{
if (current == null)
{
return;
}
ContainerBlock parent = current.Parent;
if (parent == null)
{
return;
}
if (parent.Prev == null && parent.Next == null)
{
return;
}
current.Parent.Delete();
}
public static void InsertNewLineFromCurrent(Block current, Block newLine)
{
if (current == null)
{
return;
}
TokenLineBlock parent = current.Parent as TokenLineBlock;
if (parent == null)
{
return;
}
if (current.Prev == null && current.Next != null)
{
BlockActions.Prepend(parent, newLine);
}
else
{
parent.AppendBlocks(newLine);
}
}
}
}
|