context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsCommands2K = Microsoft.VisualStudio.VSConstants.VSStd2KCmdID;
namespace Microsoft.VisualStudio.Project
{
[CLSCompliant(false)]
[ComVisible(true)]
public class FileNode : HierarchyNode
{
#region static fiels
private static Dictionary<string, int> extensionIcons;
#endregion
#region overriden Properties
/// <summary>
/// overwrites of the generic hierarchyitem.
/// </summary>
[System.ComponentModel.BrowsableAttribute(false)]
public override string Caption
{
get
{
// Use LinkedIntoProjectAt property if available
string caption = this.ItemNode.GetMetadata(ProjectFileConstants.LinkedIntoProjectAt);
if(caption == null || caption.Length == 0)
{
// Otherwise use filename
caption = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
caption = Path.GetFileName(caption);
}
return caption;
}
}
public override int ImageIndex
{
get
{
// Check if the file is there.
if(!this.CanShowDefaultIcon())
{
return (int)ProjectNode.ImageName.MissingFile;
}
//Check for known extensions
int imageIndex;
string extension = System.IO.Path.GetExtension(this.FileName);
if((string.IsNullOrEmpty(extension)) || (!extensionIcons.TryGetValue(extension, out imageIndex)))
{
// Missing or unknown extension; let the base class handle this case.
return base.ImageIndex;
}
// The file type is known and there is an image for it in the image list.
return imageIndex;
}
}
public override Guid ItemTypeGuid
{
get { return VSConstants.GUID_ItemType_PhysicalFile; }
}
public override int MenuCommandId
{
get { return VsMenus.IDM_VS_CTXT_ITEMNODE; }
}
public override string Url
{
get
{
string path = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
if(String.IsNullOrEmpty(path))
{
return String.Empty;
}
Url url;
if(Path.IsPathRooted(path))
{
// Use absolute path
url = new Microsoft.VisualStudio.Shell.Url(path);
}
else
{
// Path is relative, so make it relative to project path
url = new Url(this.ProjectMgr.BaseURI, path);
}
return url.AbsoluteUrl;
}
}
#endregion
#region ctor
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")]
static FileNode()
{
// Build the dictionary with the mapping between some well known extensions
// and the index of the icons inside the standard image list.
extensionIcons = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
extensionIcons.Add(".aspx", (int)ProjectNode.ImageName.WebForm);
extensionIcons.Add(".asax", (int)ProjectNode.ImageName.GlobalApplicationClass);
extensionIcons.Add(".asmx", (int)ProjectNode.ImageName.WebService);
extensionIcons.Add(".ascx", (int)ProjectNode.ImageName.WebUserControl);
extensionIcons.Add(".asp", (int)ProjectNode.ImageName.ASPPage);
extensionIcons.Add(".config", (int)ProjectNode.ImageName.WebConfig);
extensionIcons.Add(".htm", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".html", (int)ProjectNode.ImageName.HTMLPage);
extensionIcons.Add(".css", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".xsl", (int)ProjectNode.ImageName.StyleSheet);
extensionIcons.Add(".vbs", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".js", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".wsf", (int)ProjectNode.ImageName.ScriptFile);
extensionIcons.Add(".txt", (int)ProjectNode.ImageName.TextFile);
extensionIcons.Add(".resx", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".rc", (int)ProjectNode.ImageName.Resources);
extensionIcons.Add(".bmp", (int)ProjectNode.ImageName.Bitmap);
extensionIcons.Add(".ico", (int)ProjectNode.ImageName.Icon);
extensionIcons.Add(".gif", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".jpg", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".png", (int)ProjectNode.ImageName.Image);
extensionIcons.Add(".map", (int)ProjectNode.ImageName.ImageMap);
extensionIcons.Add(".wav", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".mid", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".midi", (int)ProjectNode.ImageName.Audio);
extensionIcons.Add(".avi", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mov", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".mpeg", (int)ProjectNode.ImageName.Video);
extensionIcons.Add(".cab", (int)ProjectNode.ImageName.CAB);
extensionIcons.Add(".jar", (int)ProjectNode.ImageName.JAR);
extensionIcons.Add(".xslt", (int)ProjectNode.ImageName.XSLTFile);
extensionIcons.Add(".xsd", (int)ProjectNode.ImageName.XMLSchema);
extensionIcons.Add(".xml", (int)ProjectNode.ImageName.XMLFile);
extensionIcons.Add(".pfx", (int)ProjectNode.ImageName.PFX);
extensionIcons.Add(".snk", (int)ProjectNode.ImageName.SNK);
}
/// <summary>
/// Constructor for the FileNode
/// </summary>
/// <param name="root">Root of the hierarchy</param>
/// <param name="e">Associated project element</param>
public FileNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
if(this.ProjectMgr.NodeHasDesigner(this.ItemNode.GetMetadata(ProjectFileConstants.Include)))
{
this.HasDesigner = true;
}
}
#endregion
#region overridden methods
protected override NodeProperties CreatePropertiesObject()
{
ISingleFileGenerator generator = this.CreateSingleFileGenerator();
return generator == null ? new FileNodeProperties(this) : new SingleFileGeneratorNodeProperties(this);
}
public override object GetIconHandle(bool open)
{
int index = this.ImageIndex;
if(NoImage == index)
{
// There is no image for this file; let the base class handle this case.
return base.GetIconHandle(open);
}
// Return the handle for the image.
return this.ProjectMgr.ImageHandler.GetIconHandle(index);
}
/// <summary>
/// Get an instance of the automation object for a FileNode
/// </summary>
/// <returns>An instance of the Automation.OAFileNode if succeeded</returns>
public override object GetAutomationObject()
{
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return null;
}
return new Automation.OAFileItem(this.ProjectMgr.GetAutomationObject() as Automation.OAProject, this);
}
/// <summary>
/// Renames a file node.
/// </summary>
/// <param name="label">The new name.</param>
/// <returns>An errorcode for failure or S_OK.</returns>
/// <exception cref="InvalidOperationException" if the file cannot be validated>
/// <devremark>
/// We are going to throw instaed of showing messageboxes, since this method is called from various places where a dialog box does not make sense.
/// For example the FileNodeProperties are also calling this method. That should not show directly a messagebox.
/// Also the automation methods are also calling SetEditLabel
/// </devremark>
public override int SetEditLabel(string label)
{
// IMPORTANT NOTE: This code will be called when a parent folder is renamed. As such, it is
// expected that we can be called with a label which is the same as the current
// label and this should not be considered a NO-OP.
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return VSConstants.E_FAIL;
}
// Validate the filename.
if(String.IsNullOrEmpty(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
else if(label.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
else if(Utilities.IsFileNameInvalid(label))
{
throw new InvalidOperationException(SR.GetString(SR.ErrorInvalidFileName, CultureInfo.CurrentUICulture));
}
for(HierarchyNode n = this.Parent.FirstChild; n != null; n = n.NextSibling)
{
if(n != this && String.Compare(n.Caption, label, StringComparison.OrdinalIgnoreCase) == 0)
{
//A file or folder with the name '{0}' already exists on disk at this location. Please choose another name.
//If this file or folder does not appear in the Solution Explorer, then it is not currently part of your project. To view files which exist on disk, but are not in the project, select Show All Files from the Project menu.
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileOrFolderAlreadyExists, CultureInfo.CurrentUICulture), label));
}
}
string fileName = Path.GetFileNameWithoutExtension(label);
// If there is no filename or it starts with a leading dot issue an error message and quit.
if(String.IsNullOrEmpty(fileName) || fileName[0] == '.')
{
throw new InvalidOperationException(SR.GetString(SR.FileNameCannotContainALeadingPeriod, CultureInfo.CurrentUICulture));
}
// Verify that the file extension is unchanged
string strRelPath = Path.GetFileName(this.ItemNode.GetMetadata(ProjectFileConstants.Include));
if(String.Compare(Path.GetExtension(strRelPath), Path.GetExtension(label), StringComparison.OrdinalIgnoreCase) != 0)
{
// Prompt to confirm that they really want to change the extension of the file
string message = SR.GetString(SR.ConfirmExtensionChange, CultureInfo.CurrentUICulture, new string[] { label });
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if(shell == null)
{
return VSConstants.E_FAIL;
}
if(!VsShellUtilities.PromptYesNo(message, null, OLEMSGICON.OLEMSGICON_INFO, shell))
{
// The user cancelled the confirmation for changing the extension.
// Return S_OK in order not to show any extra dialog box
return VSConstants.S_OK;
}
}
// Build the relative path by looking at folder names above us as one scenarios
// where we get called is when a folder above us gets renamed (in which case our path is invalid)
HierarchyNode parent = this.Parent;
while(parent != null && (parent is FolderNode))
{
strRelPath = Path.Combine(parent.Caption, strRelPath);
parent = parent.Parent;
}
return SetEditLabel(label, strRelPath);
}
public override string GetMkDocument()
{
Debug.Assert(this.Url != null, "No url sepcified for this node");
return this.Url;
}
/// <summary>
/// Delete the item corresponding to the specified path from storage.
/// </summary>
/// <param name="path"></param>
protected internal override void DeleteFromStorage(string path)
{
if(File.Exists(path))
{
File.SetAttributes(path, FileAttributes.Normal); // make sure it's not readonly.
File.Delete(path);
}
}
/// <summary>
/// Rename the underlying document based on the change the user just made to the edit label.
/// </summary>
protected internal override int SetEditLabel(string label, string relativePath)
{
int returnValue = VSConstants.S_OK;
uint oldId = this.ID;
string strSavePath = Path.GetDirectoryName(relativePath);
if(!Path.IsPathRooted(relativePath))
{
strSavePath = Path.Combine(Path.GetDirectoryName(this.ProjectMgr.BaseURI.Uri.LocalPath), strSavePath);
}
string newName = Path.Combine(strSavePath, label);
if(NativeMethods.IsSamePath(newName, this.Url))
{
// If this is really a no-op, then nothing to do
if(String.Compare(newName, this.Url, StringComparison.Ordinal) == 0)
return VSConstants.S_FALSE;
}
else
{
// If the renamed file already exists then quit (unless it is the result of the parent having done the move).
if(IsFileOnDisk(newName)
&& (IsFileOnDisk(this.Url)
|| String.Compare(Path.GetFileName(newName), Path.GetFileName(this.Url), StringComparison.Ordinal) != 0))
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileCannotBeRenamedToAnExistingFile, CultureInfo.CurrentUICulture), label));
}
else if(newName.Length > NativeMethods.MAX_PATH)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.PathTooLong, CultureInfo.CurrentUICulture), label));
}
}
string oldName = this.Url;
// must update the caption prior to calling RenameDocument, since it may
// cause queries of that property (such as from open editors).
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
try
{
if(!RenameDocument(oldName, newName))
{
this.ItemNode.Rename(oldrelPath);
this.ItemNode.RefreshProperties();
}
if(this is DependentFileNode)
{
OnInvalidateItems(this.Parent);
}
}
catch(Exception e)
{
// Just re-throw the exception so we don't get duplicate message boxes.
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newName, oldrelPath);
returnValue = Marshal.GetHRForException(e);
throw;
}
// Return S_FALSE if the hierarchy item id has changed. This forces VS to flush the stale
// hierarchy item id.
if(returnValue == (int)VSConstants.S_OK || returnValue == (int)VSConstants.S_FALSE || returnValue == VSConstants.OLE_E_PROMPTSAVECANCELLED)
{
return (oldId == this.ID) ? VSConstants.S_OK : (int)VSConstants.S_FALSE;
}
return returnValue;
}
/// <summary>
/// Returns a specific Document manager to handle files
/// </summary>
/// <returns>Document manager object</returns>
protected internal override DocumentManager GetDocumentManager()
{
return new FileDocumentManager(this);
}
/// <summary>
/// Called by the drag&drop implementation to ask the node
/// which is being dragged/droped over which nodes should
/// process the operation.
/// This allows for dragging to a node that cannot contain
/// items to let its parent accept the drop, while a reference
/// node delegate to the project and a folder/project node to itself.
/// </summary>
/// <returns></returns>
protected internal override HierarchyNode GetDragTargetHandlerNode()
{
Debug.Assert(this.ProjectMgr != null, " The project manager is null for the filenode");
HierarchyNode handlerNode = this;
while(handlerNode != null && !(handlerNode is ProjectNode || handlerNode is FolderNode))
handlerNode = handlerNode.Parent;
if(handlerNode == null)
handlerNode = this.ProjectMgr;
return handlerNode;
}
protected override int ExecCommandOnNode(Guid cmdGroup, uint cmd, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut)
{
if(this.ProjectMgr == null || this.ProjectMgr.IsClosed)
{
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
// Exec on special filenode commands
if(cmdGroup == VsMenus.guidStandardCommandSet97)
{
IVsWindowFrame windowFrame = null;
switch((VsCommands)cmd)
{
case VsCommands.ViewCode:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Code, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.ViewForm:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, VSConstants.LOGVIEWID_Designer, out windowFrame, WindowFrameShowAction.Show);
case VsCommands.Open:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, false, WindowFrameShowAction.Show);
case VsCommands.OpenWith:
return ((FileDocumentManager)this.GetDocumentManager()).Open(false, true, VSConstants.LOGVIEWID_UserChooseView, out windowFrame, WindowFrameShowAction.Show);
}
}
// Exec on special filenode commands
if(cmdGroup == VsMenus.guidStandardCommandSet2K)
{
switch((VsCommands2K)cmd)
{
case VsCommands2K.RUNCUSTOMTOOL:
{
try
{
this.RunGenerator();
return VSConstants.S_OK;
}
catch(Exception e)
{
Trace.WriteLine("Running Custom Tool failed : " + e.Message);
throw;
}
}
}
}
return base.ExecCommandOnNode(cmdGroup, cmd, nCmdexecopt, pvaIn, pvaOut);
}
protected override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result)
{
if(cmdGroup == VsMenus.guidStandardCommandSet97)
{
switch((VsCommands)cmd)
{
case VsCommands.Copy:
case VsCommands.Paste:
case VsCommands.Cut:
case VsCommands.Rename:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
case VsCommands.ViewCode:
//case VsCommands.Delete: goto case VsCommands.OpenWith;
case VsCommands.Open:
case VsCommands.OpenWith:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
else if(cmdGroup == VsMenus.guidStandardCommandSet2K)
{
if((VsCommands2K)cmd == VsCommands2K.EXCLUDEFROMPROJECT)
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
if((VsCommands2K)cmd == VsCommands2K.RUNCUSTOMTOOL)
{
if(string.IsNullOrEmpty(this.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon)) && (this.NodeProperties is SingleFileGeneratorNodeProperties))
{
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.ENABLED;
return VSConstants.S_OK;
}
}
}
else
{
return (int)OleConstants.OLECMDERR_E_UNKNOWNGROUP;
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
protected override void DoDefaultAction()
{
CCITracing.TraceCall();
FileDocumentManager manager = this.GetDocumentManager() as FileDocumentManager;
Debug.Assert(manager != null, "Could not get the FileDocumentManager");
manager.Open(false, false, WindowFrameShowAction.Show);
}
/// <summary>
/// Performs a SaveAs operation of an open document. Called from SaveItem after the running document table has been updated with the new doc data.
/// </summary>
/// <param name="docData">A pointer to the document in the rdt</param>
/// <param name="newFilePath">The new file path to the document</param>
/// <returns></returns>
protected override int AfterSaveItemAs(IntPtr docData, string newFilePath)
{
if(String.IsNullOrEmpty(newFilePath))
{
throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newFilePath");
}
int returnCode = VSConstants.S_OK;
newFilePath = newFilePath.Trim();
//Identify if Path or FileName are the same for old and new file
string newDirectoryName = Path.GetDirectoryName(newFilePath);
Uri newDirectoryUri = new Uri(newDirectoryName);
string newCanonicalDirectoryName = newDirectoryUri.LocalPath;
newCanonicalDirectoryName = newCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string oldCanonicalDirectoryName = new Uri(Path.GetDirectoryName(this.GetMkDocument())).LocalPath;
oldCanonicalDirectoryName = oldCanonicalDirectoryName.TrimEnd(Path.DirectorySeparatorChar);
string errorMessage = String.Empty;
bool isSamePath = NativeMethods.IsSamePath(newCanonicalDirectoryName, oldCanonicalDirectoryName);
bool isSameFile = NativeMethods.IsSamePath(newFilePath, this.Url);
// Currently we do not support if the new directory is located outside the project cone
string projectCannonicalDirecoryName = new Uri(this.ProjectMgr.ProjectFolder).LocalPath;
projectCannonicalDirecoryName = projectCannonicalDirecoryName.TrimEnd(Path.DirectorySeparatorChar);
if(!isSamePath && newCanonicalDirectoryName.IndexOf(projectCannonicalDirecoryName, StringComparison.OrdinalIgnoreCase) == -1)
{
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.LinkedItemsAreNotSupported, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
//Get target container
HierarchyNode targetContainer = null;
if(isSamePath)
{
targetContainer = this.Parent;
}
else if(NativeMethods.IsSamePath(newCanonicalDirectoryName, projectCannonicalDirecoryName))
{
//the projectnode is the target container
targetContainer = this.ProjectMgr;
}
else
{
//search for the target container among existing child nodes
targetContainer = this.ProjectMgr.FindChild(newDirectoryName);
if(targetContainer != null && (targetContainer is FileNode))
{
// We already have a file node with this name in the hierarchy.
errorMessage = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.FileAlreadyExistsAndCannotBeRenamed, CultureInfo.CurrentUICulture), Path.GetFileNameWithoutExtension(newFilePath));
throw new InvalidOperationException(errorMessage);
}
}
if(targetContainer == null)
{
// Add a chain of subdirectories to the project.
string relativeUri = PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, newDirectoryUri);
Debug.Assert(!String.IsNullOrEmpty(relativeUri) && relativeUri != newDirectoryUri.LocalPath, "Could not make pat distance of " + this.ProjectMgr.BaseURI.Uri.LocalPath + " and " + newDirectoryUri);
targetContainer = this.ProjectMgr.CreateFolderNodes(relativeUri);
}
Debug.Assert(targetContainer != null, "We should have found a target node by now");
//Suspend file changes while we rename the document
string oldrelPath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string oldName = Path.Combine(this.ProjectMgr.ProjectFolder, oldrelPath);
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Rename the node.
DocumentManager.UpdateCaption(this.ProjectMgr.Site, Path.GetFileName(newFilePath), docData);
// Check if the file name was actually changed.
// In same cases (e.g. if the item is a file and the user has changed its encoding) this function
// is called even if there is no real rename.
if(!isSameFile || (this.Parent.ID != targetContainer.ID))
{
// The path of the file is changed or its parent is changed; in both cases we have
// to rename the item.
this.RenameFileNode(oldName, newFilePath, targetContainer.ID);
OnInvalidateItems(this.Parent);
}
}
catch(Exception e)
{
Trace.WriteLine("Exception : " + e.Message);
this.RecoverFromRenameFailure(newFilePath, oldrelPath);
throw;
}
finally
{
sfc.Resume();
}
return returnCode;
}
/// <summary>
/// Determines if this is node a valid node for painting the default file icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
string moniker = this.GetMkDocument();
if(String.IsNullOrEmpty(moniker) || !File.Exists(moniker))
{
return false;
}
return true;
}
#endregion
#region virtual methods
public virtual string FileName
{
get
{
return this.Caption;
}
set
{
this.SetEditLabel(value);
}
}
/// <summary>
/// Determine if this item is represented physical on disk and shows a messagebox in case that the file is not present and a UI is to be presented.
/// </summary>
/// <param name="showMessage">true if user should be presented for UI in case the file is not present</param>
/// <returns>true if file is on disk</returns>
internal protected virtual bool IsFileOnDisk(bool showMessage)
{
bool fileExist = IsFileOnDisk(this.Url);
if(!fileExist && showMessage && !Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ItemDoesNotExistInProjectDirectory, CultureInfo.CurrentUICulture), this.Caption);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
return fileExist;
}
/// <summary>
/// Determine if the file represented by "path" exist in storage.
/// Override this method if your files are not persisted on disk.
/// </summary>
/// <param name="path">Url representing the file</param>
/// <returns>True if the file exist</returns>
internal protected virtual bool IsFileOnDisk(string path)
{
return File.Exists(path);
}
/// <summary>
/// Renames the file in the hierarchy by removing old node and adding a new node in the hierarchy.
/// </summary>
/// <param name="oldFileName">The old file name.</param>
/// <param name="newFileName">The new file name</param>
/// <param name="newParentId">The new parent id of the item.</param>
/// <returns>The newly added FileNode.</returns>
/// <remarks>While a new node will be used to represent the item, the underlying MSBuild item will be the same and as a result file properties saved in the project file will not be lost.</remarks>
protected virtual FileNode RenameFileNode(string oldFileName, string newFileName, uint newParentId)
{
if(string.Compare(oldFileName, newFileName, StringComparison.Ordinal) == 0)
{
// We do not want to rename the same file
return null;
}
this.OnItemDeleted();
this.Parent.RemoveChild(this);
// Since this node has been removed all of its state is zombied at this point
// Do not call virtual methods after this point since the object is in a deleted state.
string[] file = new string[1];
file[0] = newFileName;
VSADDRESULT[] result = new VSADDRESULT[1];
Guid emptyGuid = Guid.Empty;
ErrorHandler.ThrowOnFailure(this.ProjectMgr.AddItemWithSpecific(newParentId, VSADDITEMOPERATION.VSADDITEMOP_OPENFILE, null, 0, file, IntPtr.Zero, 0, ref emptyGuid, null, ref emptyGuid, result));
FileNode childAdded = this.ProjectMgr.FindChild(newFileName) as FileNode;
Debug.Assert(childAdded != null, "Could not find the renamed item in the hierarchy");
// Update the itemid to the newly added.
this.ID = childAdded.ID;
// Remove the item created by the add item. We need to do this otherwise we will have two items.
// Please be aware that we have not removed the ItemNode associated to the removed file node from the hierrachy.
// What we want to achieve here is to reuse the existing build item.
// We want to link to the newly created node to the existing item node and addd the new include.
//temporarily keep properties from new itemnode since we are going to overwrite it
string newInclude = childAdded.ItemNode.Item.EvaluatedInclude;
string dependentOf = childAdded.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
childAdded.ItemNode.RemoveFromProjectFile();
// Assign existing msbuild item to the new childnode
childAdded.ItemNode = this.ItemNode;
childAdded.ItemNode.Item.ItemType = this.ItemNode.ItemName;
childAdded.ItemNode.Item.Xml.Include = newInclude;
if(!string.IsNullOrEmpty(dependentOf))
childAdded.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, dependentOf);
childAdded.ItemNode.RefreshProperties();
//Update the new document in the RDT.
DocumentManager.RenameDocument(this.ProjectMgr.Site, oldFileName, newFileName, childAdded.ID);
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
// This happens in the context of renaming a file.
// Since we are already in solution explorer, it is extremely unlikely that we get a null return.
// If we do, the consequences are minimal: the parent node will be selected instead of the
// renamed node.
if (uiWindow != null)
{
ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem));
}
//Update FirstChild
childAdded.FirstChild = this.FirstChild;
//Update ChildNodes
SetNewParentOnChildNodes(childAdded);
RenameChildNodes(childAdded);
return childAdded;
}
/// <summary>
/// Rename all childnodes
/// </summary>
/// <param name="newFileNode">The newly added Parent node.</param>
protected virtual void RenameChildNodes(FileNode parentNode)
{
foreach(HierarchyNode child in GetChildNodes())
{
FileNode childNode = child as FileNode;
if(null == childNode)
{
continue;
}
string newfilename;
if(childNode.HasParentNodeNameRelation)
{
string relationalName = childNode.Parent.GetRelationalName();
string extension = childNode.GetRelationNameExtension();
newfilename = relationalName + extension;
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), newfilename);
}
else
{
newfilename = Path.Combine(Path.GetDirectoryName(childNode.Parent.GetMkDocument()), childNode.Caption);
}
childNode.RenameDocument(childNode.GetMkDocument(), newfilename);
//We must update the DependsUpon property since the rename operation will not do it if the childNode is not renamed
//which happens if the is no name relation between the parent and the child
string dependentOf = childNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);
if(!string.IsNullOrEmpty(dependentOf))
{
childNode.ItemNode.SetMetadata(ProjectFileConstants.DependentUpon, childNode.Parent.ItemNode.GetMetadata(ProjectFileConstants.Include));
}
}
}
/// <summary>
/// Tries recovering from a rename failure.
/// </summary>
/// <param name="fileThatFailed"> The file that failed to be renamed.</param>
/// <param name="originalFileName">The original filenamee</param>
protected virtual void RecoverFromRenameFailure(string fileThatFailed, string originalFileName)
{
if(this.ItemNode != null && !String.IsNullOrEmpty(originalFileName))
{
this.ItemNode.Rename(originalFileName);
}
}
protected override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation)
{
if(deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage)
{
return this.ProjectMgr.CanProjectDeleteItems;
}
return false;
}
/// <summary>
/// This should be overriden for node that are not saved on disk
/// </summary>
/// <param name="oldName">Previous name in storage</param>
/// <param name="newName">New name in storage</param>
protected virtual void RenameInStorage(string oldName, string newName)
{
File.Move(oldName, newName);
}
/// <summary>
/// factory method for creating single file generators.
/// </summary>
/// <returns></returns>
protected virtual ISingleFileGenerator CreateSingleFileGenerator()
{
return new SingleFileGenerator(this.ProjectMgr);
}
/// <summary>
/// This method should be overridden to provide the list of special files and associated flags for source control.
/// </summary>
/// <param name="sccFile">One of the file associated to the node.</param>
/// <param name="files">The list of files to be placed under source control.</param>
/// <param name="flags">The flags that are associated to the files.</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Scc")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "scc")]
protected internal override void GetSccSpecialFiles(string sccFile, IList<string> files, IList<tagVsSccFilesFlags> flags)
{
if(this.ExcludeNodeFromScc)
{
return;
}
if(files == null)
{
throw new ArgumentNullException("files");
}
if(flags == null)
{
throw new ArgumentNullException("flags");
}
foreach(HierarchyNode node in this.GetChildNodes())
{
files.Add(node.GetMkDocument());
}
}
#endregion
#region Helper methods
/// <summary>
/// Get's called to rename the eventually running document this hierarchyitem points to
/// </summary>
/// returns FALSE if the doc can not be renamed
internal bool RenameDocument(string oldName, string newName)
{
IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
if(pRDT == null) return false;
IntPtr docData = IntPtr.Zero;
IVsHierarchy pIVsHierarchy;
uint itemId;
uint uiVsDocCookie;
SuspendFileChanges sfc = new SuspendFileChanges(this.ProjectMgr.Site, oldName);
sfc.Suspend();
try
{
// Suspend ms build since during a rename operation no msbuild re-evaluation should be performed until we have finished.
// Scenario that could fail if we do not suspend.
// We have a project system relying on MPF that triggers a Compile target build (re-evaluates itself) whenever the project changes. (example: a file is added, property changed.)
// 1. User renames a file in the above project sytem relying on MPF
// 2. Our rename funstionality implemented in this method removes and readds the file and as a post step copies all msbuild entries from the removed file to the added file.
// 3. The project system mentioned will trigger an msbuild re-evaluate with the new item, because it was listening to OnItemAdded.
// The problem is that the item at the "add" time is only partly added to the project, since the msbuild part has not yet been copied over as mentioned in part 2 of the last step of the rename process.
// The result is that the project re-evaluates itself wrongly.
VSRENAMEFILEFLAGS renameflag = VSRENAMEFILEFLAGS.VSRENAMEFILEFLAGS_NoFlags;
try
{
this.ProjectMgr.SuspendMSBuild();
ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));
if(pIVsHierarchy != null && !Utilities.IsSameComObject(pIVsHierarchy, this.ProjectMgr.InteropSafeIVsHierarchy))
{
// Don't rename it if it wasn't opened by us.
return false;
}
// ask other potentially running packages
if(!this.ProjectMgr.Tracker.CanRenameItem(oldName, newName, renameflag))
{
return false;
}
// Allow the user to "fix" the project by renaming the item in the hierarchy
// to the real name of the file on disk.
if(IsFileOnDisk(oldName) || !IsFileOnDisk(newName))
{
RenameInStorage(oldName, newName);
}
string newFileName = Path.GetFileName(newName);
DocumentManager.UpdateCaption(this.ProjectMgr.Site, newFileName, docData);
bool caseOnlyChange = NativeMethods.IsSamePath(oldName, newName);
if(!caseOnlyChange)
{
// Check out the project file if necessary.
if(!this.ProjectMgr.QueryEditProjectFile(false))
{
throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
}
this.RenameFileNode(oldName, newName);
}
else
{
this.RenameCaseOnlyChange(newFileName);
}
}
finally
{
this.ProjectMgr.ResumeMSBuild(this.ProjectMgr.ReEvaluateProjectFileTargetName);
}
this.ProjectMgr.Tracker.OnItemRenamed(oldName, newName, renameflag);
}
finally
{
sfc.Resume();
if(docData != IntPtr.Zero)
{
Marshal.Release(docData);
}
}
return true;
}
private FileNode RenameFileNode(string oldFileName, string newFileName)
{
return this.RenameFileNode(oldFileName, newFileName, this.Parent.ID);
}
/// <summary>
/// Renames the file node for a case only change.
/// </summary>
/// <param name="newFileName">The new file name.</param>
private void RenameCaseOnlyChange(string newFileName)
{
//Update the include for this item.
string include = this.ItemNode.Item.EvaluatedInclude;
if(String.Compare(include, newFileName, StringComparison.OrdinalIgnoreCase) == 0)
{
this.ItemNode.Item.Xml.Include = newFileName;
}
else
{
string includeDir = Path.GetDirectoryName(include);
this.ItemNode.Item.Xml.Include = Path.Combine(includeDir, newFileName);
}
this.ItemNode.RefreshProperties();
this.ReDraw(UIHierarchyElement.Caption);
this.RenameChildNodes(this);
// Refresh the property browser.
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Debug.Assert(shell != null, "Could not get the ui shell from the project");
if(shell == null)
{
throw new InvalidOperationException();
}
ErrorHandler.ThrowOnFailure(shell.RefreshPropertyBrowser(0));
//Select the new node in the hierarchy
IVsUIHierarchyWindow uiWindow = UIHierarchyUtilities.GetUIHierarchyWindow(this.ProjectMgr.Site, SolutionExplorer);
// This happens in the context of renaming a file by case only (Table.sql -> table.sql)
// Since we are already in solution explorer, it is extremely unlikely that we get a null return.
if (uiWindow != null)
{
ErrorHandler.ThrowOnFailure(uiWindow.ExpandItem(this.ProjectMgr.InteropSafeIVsUIHierarchy, this.ID, EXPANDFLAGS.EXPF_SelectItem));
}
}
#endregion
#region SingleFileGenerator Support methods
/// <summary>
/// Event handler for the Custom tool property changes
/// </summary>
/// <param name="sender">FileNode sending it</param>
/// <param name="e">Node event args</param>
internal virtual void OnCustomToolChanged(object sender, HierarchyNodeEventArgs e)
{
this.RunGenerator();
}
/// <summary>
/// Event handler for the Custom tool namespce property changes
/// </summary>
/// <param name="sender">FileNode sending it</param>
/// <param name="e">Node event args</param>
internal virtual void OnCustomToolNameSpaceChanged(object sender, HierarchyNodeEventArgs e)
{
this.RunGenerator();
}
#endregion
#region helpers
/// <summary>
/// Runs a generator.
/// </summary>
internal void RunGenerator()
{
ISingleFileGenerator generator = this.CreateSingleFileGenerator();
if(generator != null)
{
generator.RunGenerator(this.Url);
}
}
/// <summary>
/// Update the ChildNodes after the parent node has been renamed
/// </summary>
/// <param name="newFileNode">The new FileNode created as part of the rename of this node</param>
private void SetNewParentOnChildNodes(FileNode newFileNode)
{
foreach(HierarchyNode childNode in GetChildNodes())
{
childNode.Parent = newFileNode;
}
}
private List<HierarchyNode> GetChildNodes()
{
List<HierarchyNode> childNodes = new List<HierarchyNode>();
HierarchyNode childNode = this.FirstChild;
while(childNode != null)
{
childNodes.Add(childNode);
childNode = childNode.NextSibling;
}
return childNodes;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
using UnityEngine;
public enum DCAccountType
{
DC_Anonymous = 0,
DC_Registered,
DC_SianWeibo,
DC_QQ,
DC_TencentWeibo,
DC_ND91,
DC_Type1,
DC_Type2,
DC_Type3,
DC_Type4,
DC_Type5,
DC_Type6,
DC_Type7,
DC_Type8,
DC_Type9,
DC_Type10
};
public enum DCGender
{
DC_UNKNOWN = 0,
DC_MALE,
DC_FEMALE
};
public class DCAccount
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
private static string JAVA_CLASS = "com.dataeye.DCAccount";
private static AndroidJavaObject account = new AndroidJavaObject(JAVA_CLASS);
#elif UNITY_IPHONE
[DllImport("__Internal")]
private static extern void dcLogin(string accountId);
[DllImport("__Internal")]
private static extern void dcLogin1(string accountId, string gameServer);
[DllImport("__Internal")]
private static extern void dcLogout();
[DllImport("__Internal")]
private static extern string dcGetAccountId();
[DllImport("__Internal")]
private static extern void dcSetAccountType(int type);
[DllImport("__Internal")]
private static extern void dcSetLevel(int level);
[DllImport("__Internal")]
private static extern void dcSetAge(int age);
[DllImport("__Internal")]
private static extern void dcSetGender(int gender);
[DllImport("__Internal")]
private static extern void dcSetGameServer(string gameServer);
[DllImport("__Internal")]
private static extern void dcAddTag(string tag, string subTag);
[DllImport("__Internal")]
private static extern void dcRemoveTag(string tag, string subTag);
#endif
public static void login(string accountId)
{
if(accountId == null)
{
return;
}
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("login", accountId);
#elif UNITY_IPHONE
dcLogin(accountId);
#elif UNITY_WP8
DataEyeWP8.DCAccount.login(accountId);
#endif
}
public static void login(string accountId, string gameServer)
{
if(accountId == null || gameServer == null)
{
return;
}
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("login", accountId, gameServer);
#elif UNITY_IPHONE
dcLogin1(accountId, gameServer);
#elif UNITY_WP8
DataEyeWP8.DCAccount.login(accountId, gameServer);
#endif
}
public static void logout()
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("logout");
#elif UNITY_IPHONE
dcLogout();
#elif UNITY_WP8
DataEyeWP8.DCAccount.logout();
#endif
}
public static string getAccountId()
{
#if UNITY_EDITOR
return null;
#elif UNITY_ANDROID
return account.CallStatic<string>("getAccountId");
#elif UNITY_IPHONE
return dcGetAccountId();
#elif UNITY_WP8
return DataEyeWP8.DCAccount.getAccountId();
#else
return null;
#endif
}
public static void setAccountType(DCAccountType type)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("setAccountType", (int)type);
#elif UNITY_IPHONE
dcSetAccountType((int)type);
#elif UNITY_WP8
DataEyeWP8.DCAccount.setAccountType((DataEyeWP8.DCAccountType)type);
#endif
}
public static void setLevel(int level)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("setLevel", level);
#elif UNITY_IPHONE
dcSetLevel(level);
#elif UNITY_WP8
DataEyeWP8.DCAccount.setLevel(level);
#endif
}
public static void setGender(DCGender gender)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("setGender", (int)gender);
#elif UNITY_IPHONE
dcSetGender((int)gender);
#elif UNITY_WP8
DataEyeWP8.DCAccount.setGender((DataEyeWP8.DCGender)gender);
#endif
}
public static void setAge(int age)
{
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("setAge", age);
#elif UNITY_IPHONE
dcSetAge(age);
#elif UNITY_WP8
DataEyeWP8.DCAccount.setAge(age);
#endif
}
public static void setGameServer(string server)
{
if(server == null)
{
return;
}
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("setGameServer", server);
#elif UNITY_IPHONE
dcSetGameServer(server);
#elif UNITY_WP8
DataEyeWP8.DCAccount.setGameServer(server);
#endif
}
public static void addTag(string tag, string subTag)
{
if(tag == null || subTag == null)
{
return;
}
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("addTag", tag, subTag);
#elif UNITY_IPHONE
dcAddTag(tag, subTag);
#elif UNITY_WP8
DataEyeWP8.DCAccount.addTag(tag, subTag);
#endif
}
public static void removeTag(string tag, string subTag)
{
if(tag == null || subTag == null)
{
return;
}
#if UNITY_EDITOR
#elif UNITY_ANDROID
account.CallStatic("removeTag", tag, subTag);
#elif UNITY_IPHONE
dcRemoveTag(tag, subTag);
#elif UNITY_WP8
DataEyeWP8.DCAccount.removeTag(tag, subTag);
#endif
}
};
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class LayerTest1 : LayerTest
{
const int kTagLayer = 1;
const int kCCMenuTouchPriority = -128;
public override void OnEnter()
{
base.OnEnter();
var listener = new CCEventListenerTouchAllAtOnce();
listener.OnTouchesBegan = onTouchesBegan;
listener.OnTouchesMoved = onTouchesMoved;
listener.OnTouchesEnded = onTouchesEnded;
AddEventListener(listener);
CCSize s = Layer.VisibleBoundsWorldspace.Size;
CCLayerColor layer = new CCLayerColor(new CCColor4B(0xFF, 0x00, 0x00, 0x80));
layer.IgnoreAnchorPointForPosition = false;
layer.Position = s.Center / 2;
layer.ScaleX = (s.Width / 2) / s.Width;
layer.ScaleY = (s.Height / 2) / s.Height;
AddChild(layer, 1, kTagLayer);
}
public override string Title
{
get
{
return "ColorLayer resize (tap & move)";
}
}
public void updateSize(CCPoint touchLocation)
{
var s = Layer.VisibleBoundsWorldspace.Size;
var newSize = new CCSize(Math.Abs(touchLocation.X - s.Width / 2) * 2, Math.Abs(touchLocation.Y - s.Height / 2) * 2);
var l = (CCLayerColor)GetChildByTag(kTagLayer);
l.ScaleX = newSize.Width / s.Width;
l.ScaleY = newSize.Height / s.Height;
l.Position = touchLocation;
}
void onTouchesBegan (List<CCTouch> touches, CCEvent touchEvent)
{
onTouchesMoved (touches, touchEvent);
}
void onTouchesMoved (List<CCTouch> touches, CCEvent touchEvent)
{
var touchLocation = touches[0].Location;
updateSize (touchLocation);
}
void onTouchesEnded (List<CCTouch> touches, CCEvent touchEvent)
{
onTouchesMoved (touches, touchEvent);
}
}
public class LayerTestCascadingOpacityA : LayerTest
{
const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayer();
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
// by default a CCLabelBMFont has IsColorModifiedByOpacity on by default if the
// texture atlas is PreMultipliedAlpha. Label as used by Cocos2d-x by default has
// this set to false. Maybe this is a bug in Cocos2d-x?
label.IsColorModifiedByOpacity = false;
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild( layer1, 0, kTagLayer);
sister1.Position= new CCPoint( s.Width*1/3, s.Height/2);
sister2.Position = new CCPoint( s.Width*2/3, s.Height/2);
label.Position = new CCPoint(s.Width / 2, s.Height / 2);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever(
new CCFadeTo(4, 0),
new CCFadeTo(4, 255),
delay
);
// We only have to define them once.
var fadeTo11 = new CCFadeTo (2, 0);
var fadeTo12 = new CCFadeTo (2, 255);
sister1.RepeatForever(
fadeTo11,
fadeTo12,
fadeTo11,
fadeTo12,
delay
);
// Enable cascading in scene
SetEnableRecursiveCascading(this, true);
}
public override string Subtitle
{
get
{
return "Layer: cascading opacity";
}
}
}
public class LayerTestCascadingOpacityB : LayerTest
{
const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayerColor(new CCColor4B(192, 0, 0, 255));
layer1.IsColorCascaded = false;
layer1.Position = new CCPoint(0, s.Height / 2);
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
// by default a CCLabelBMFont has IsColorModifiedByOpacity on by default if the
// texture atlas is PreMultipliedAlpha. Label as used by Cocos2d-x by default has
// this set to false. Maybe this is a bug in Cocos2d-x?
label.IsColorModifiedByOpacity = false;
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild(layer1, 0, kTagLayer);
sister1.Position = new CCPoint(s.Width * 1 / 3, 0);
sister2.Position = new CCPoint(s.Width * 2 / 3, 0);
label.Position = new CCPoint(s.Width / 2, 0);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever(
new CCFadeTo(4, 0),
new CCFadeTo(4, 255),
delay
);
// We only have to define them once.
var fadeTo11 = new CCFadeTo (2, 0);
var fadeTo12 = new CCFadeTo (2, 255);
sister1.RepeatForever(
fadeTo11,
fadeTo12,
fadeTo11,
fadeTo12,
delay
);
// Enable cascading in scene
SetEnableRecursiveCascading(this, true);
}
public override string Subtitle
{
get
{
return "CCLayerColor: cascading opacity";
}
}
}
public class LayerTestCascadingOpacityC : LayerTest
{
const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayerColor(new CCColor4B(192, 0, 0, 255));
layer1.IsColorCascaded = false;
layer1.Position = new CCPoint(0, s.Height / 2);
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild(layer1, 0, kTagLayer);
sister1.Position = new CCPoint(s.Width * 1 / 3, 0);
sister2.Position = new CCPoint(s.Width * 2 / 3, 0);
label.Position = new CCPoint(s.Width / 2, 0);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever(
new CCFadeTo(4, 0),
new CCFadeTo(4, 255),
delay
);
// We only have to define them once.
var fadeTo11 = new CCFadeTo (2, 0);
var fadeTo12 = new CCFadeTo (2, 255);
sister1.RepeatForever(
fadeTo11,
fadeTo12,
fadeTo11,
fadeTo12,
delay
);
}
public override string Subtitle
{
get
{
return "CCLayerColor: non-cascading opacity";
}
}
}
public class LayerTestCascadingColorA : LayerTest
{
const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayer();
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild(layer1, 0, kTagLayer);
sister1.Position = new CCPoint(s.Width * 1 / 3, s.Height / 2);
sister2.Position = new CCPoint(s.Width * 2 / 3, s.Height / 2);
label.Position = new CCPoint(s.Width / 2, s.Height / 2);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever (
new CCTintTo(6, 255, 0, 255),
new CCTintTo(6, 255, 255, 255),
delay
);
sister1.RepeatForever (
new CCTintTo(2, 255, 255, 0),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 0, 255, 255),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 255, 0, 255),
new CCTintTo(2, 255, 255, 255),
delay
);
// Enable cascading in scene
SetEnableRecursiveCascading(this, true);
}
public override string Subtitle
{
get
{
return "Layer: cascading color";
}
}
}
public class LayerTestCascadingColorB : LayerTest
{
private const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayerColor(new CCColor4B(192, 0, 0, 255));
layer1.IsColorCascaded = false;
layer1.Position = new CCPoint(0, s.Height / 2);
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild(layer1, 0, kTagLayer);
sister1.Position = new CCPoint(s.Width * 1 / 3, 0);
sister2.Position = new CCPoint(s.Width * 2 / 3, 0);
label.Position = new CCPoint(s.Width / 2, 0);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever (
new CCTintTo(6, 255, 0, 255),
new CCTintTo(6, 255, 255, 255),
delay
);
sister1.RepeatForever (
new CCTintTo(2, 255, 255, 0),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 0, 255, 255),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 255, 0, 255),
new CCTintTo(2, 255, 255, 255),
delay
);
// Enable cascading in scene
SetEnableRecursiveCascading(this, true);
}
public override string Subtitle
{
get
{
return "CCLayerColor: cascading color";
}
}
}
public class LayerTestCascadingColorC : LayerTest
{
const int kTagLayer = 1;
public override void OnEnter()
{
base.OnEnter();
var s = Layer.VisibleBoundsWorldspace.Size;
var layer1 = new CCLayerColor(new CCColor4B(192, 0, 0, 255));
layer1.IsColorCascaded = false;
layer1.Position = new CCPoint(0, s.Height / 2);
var sister1 = new CCSprite("Images/grossinis_sister1.png");
var sister2 = new CCSprite("Images/grossinis_sister2.png");
var label = new CCLabel("Test", "fonts/bitmapFontTest.fnt");
layer1.AddChild(sister1);
layer1.AddChild(sister2);
layer1.AddChild(label);
this.AddChild(layer1, 0, kTagLayer);
sister1.Position = new CCPoint(s.Width * 1 / 3, 0);
sister2.Position = new CCPoint(s.Width * 2 / 3, 0);
label.Position = new CCPoint(s.Width / 2, 0);
// Define our delay time
var delay = new CCDelayTime (1);
layer1.RepeatForever (
new CCTintTo(6, 255, 0, 255),
new CCTintTo(6, 255, 255, 255),
delay
);
sister1.RepeatForever (
new CCTintTo(2, 255, 255, 0),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 0, 255, 255),
new CCTintTo(2, 255, 255, 255),
new CCTintTo(2, 255, 0, 255),
new CCTintTo(2, 255, 255, 255),
delay
);
}
public override string Title
{
get
{
return "CCLayerColor: non-cascading color";
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Searches for resources in Assembly manifest, used
** for assembly-based resource lookup.
**
**
===========================================================*/
namespace System.Resources
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Diagnostics;
using Microsoft.Win32;
//
// Note: this type is integral to the construction of exception objects,
// and sometimes this has to be done in low memory situtations (OOM) or
// to create TypeInitializationExceptions due to failure of a static class
// constructor. This type needs to be extremely careful and assume that
// any type it references may have previously failed to construct, so statics
// belonging to that type may not be initialized. FrameworkEventSource.Log
// is one such example.
//
internal partial class ManifestBasedResourceGroveler : IResourceGroveler
{
private ResourceManager.ResourceManagerMediator _mediator;
public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator)
{
// here and below: convert asserts to preconditions where appropriate when we get
// contracts story in place.
Debug.Assert(mediator != null, "mediator shouldn't be null; check caller");
_mediator = mediator;
}
public ResourceSet? GrovelForResourceSet(CultureInfo culture, Dictionary<string, ResourceSet> localResourceSets, bool tryParents, bool createIfNotExists)
{
Debug.Assert(culture != null, "culture shouldn't be null; check caller");
Debug.Assert(localResourceSets != null, "localResourceSets shouldn't be null; check caller");
ResourceSet? rs = null;
Stream? stream = null;
Assembly? satellite = null;
// 1. Fixups for ultimate fallbacks
CultureInfo lookForCulture = UltimateFallbackFixup(culture);
// 2. Look for satellite assembly or main assembly, as appropriate
if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
// don't bother looking in satellites in this case
satellite = _mediator.MainAssembly;
}
else
{
satellite = GetSatelliteAssembly(lookForCulture);
if (satellite == null)
{
bool raiseException = (culture.HasInvariantCultureName && (_mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite));
// didn't find satellite, give error if necessary
if (raiseException)
{
HandleSatelliteMissing();
}
}
}
// get resource file name we'll search for. Note, be careful if you're moving this statement
// around because lookForCulture may be modified from originally requested culture above.
string fileName = _mediator.GetResourceFileName(lookForCulture);
// 3. If we identified an assembly to search; look in manifest resource stream for resource file
if (satellite != null)
{
// Handle case in here where someone added a callback for assembly load events.
// While no other threads have called into GetResourceSet, our own thread can!
// At that point, we could already have an RS in our hash table, and we don't
// want to add it twice.
lock (localResourceSets)
{
localResourceSets.TryGetValue(culture.Name, out rs);
}
stream = GetManifestResourceStream(satellite, fileName);
}
// 4a. Found a stream; create a ResourceSet if possible
if (createIfNotExists && stream != null && rs == null)
{
Debug.Assert(satellite != null, "satellite should not be null when stream is set");
rs = CreateResourceSet(stream, satellite);
}
else if (stream == null && tryParents)
{
// 4b. Didn't find stream; give error if necessary
bool raiseException = culture.HasInvariantCultureName;
if (raiseException)
{
HandleResourceStreamMissing(fileName);
}
}
return rs;
}
private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture)
{
CultureInfo returnCulture = lookForCulture;
// If our neutral resources were written in this culture AND we know the main assembly
// does NOT contain neutral resources, don't probe for this satellite.
Debug.Assert(_mediator.NeutralResourcesCulture != null);
if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name &&
_mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly)
{
returnCulture = CultureInfo.InvariantCulture;
}
else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite)
{
returnCulture = _mediator.NeutralResourcesCulture;
}
return returnCulture;
}
internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, out UltimateResourceFallbackLocation fallbackLocation)
{
Debug.Assert(a != null, "assembly != null");
var attr = a.GetCustomAttribute<NeutralResourcesLanguageAttribute>();
if (attr == null)
{
fallbackLocation = UltimateResourceFallbackLocation.MainAssembly;
return CultureInfo.InvariantCulture;
}
fallbackLocation = attr.Location;
if (fallbackLocation < UltimateResourceFallbackLocation.MainAssembly || fallbackLocation > UltimateResourceFallbackLocation.Satellite)
{
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, fallbackLocation));
}
try
{
return CultureInfo.GetCultureInfo(attr.CultureName);
}
catch (ArgumentException e)
{ // we should catch ArgumentException only.
// Note we could go into infinite loops if mscorlib's
// NeutralResourcesLanguageAttribute is mangled. If this assert
// fires, please fix the build process for the BCL directory.
if (a == typeof(object).Assembly)
{
Debug.Fail(System.CoreLib.Name + "'s NeutralResourcesLanguageAttribute is a malformed culture name! name: \"" + attr.CultureName + "\" Exception: " + e);
return CultureInfo.InvariantCulture;
}
throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_Asm_Culture, a, attr.CultureName), e);
}
}
// Constructs a new ResourceSet for a given file name.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
internal ResourceSet CreateResourceSet(Stream store, Assembly assembly)
{
Debug.Assert(store != null, "I need a Stream!");
// Check to see if this is a Stream the ResourceManager understands,
// and check for the correct resource reader type.
if (store.CanSeek && store.Length > 4)
{
long startPos = store.Position;
// not disposing because we want to leave stream open
BinaryReader br = new BinaryReader(store);
// Look for our magic number as a little endian int.
int bytes = br.ReadInt32();
if (bytes == ResourceManager.MagicNumber)
{
int resMgrHeaderVersion = br.ReadInt32();
string? readerTypeName = null, resSetTypeName = null;
if (resMgrHeaderVersion == ResourceManager.HeaderVersionNumber)
{
br.ReadInt32(); // We don't want the number of bytes to skip.
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
}
else if (resMgrHeaderVersion > ResourceManager.HeaderVersionNumber)
{
// Assume that the future ResourceManager headers will
// have two strings for us - the reader type name and
// resource set type name. Read those, then use the num
// bytes to skip field to correct our position.
int numBytesToSkip = br.ReadInt32();
long endPosition = br.BaseStream.Position + numBytesToSkip;
readerTypeName = br.ReadString();
resSetTypeName = br.ReadString();
br.BaseStream.Seek(endPosition, SeekOrigin.Begin);
}
else
{
// resMgrHeaderVersion is older than this ResMgr version.
// We should add in backwards compatibility support here.
Debug.Assert(_mediator.MainAssembly != null);
throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name));
}
store.Position = startPos;
// Perf optimization - Don't use Reflection for our defaults.
// Note there are two different sets of strings here - the
// assembly qualified strings emitted by ResourceWriter, and
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
return new RuntimeResourceSet(store, permitDeserialization: true);
}
else
{
IResourceReader reader;
// Permit deserialization as long as the default ResourceReader is used
if (ResourceManager.IsDefaultType(readerTypeName, ResourceManager.ResReaderTypeName))
{
reader = new ResourceReader(
store,
new Dictionary<string, ResourceLocator>(FastResourceComparer.Default),
permitDeserialization: true);
}
else
{
Type readerType = Type.GetType(readerTypeName, throwOnError: true)!;
object[] args = new object[1];
args[0] = store;
reader = (IResourceReader)Activator.CreateInstance(readerType, args)!;
}
object[] resourceSetArgs = new object[1];
resourceSetArgs[0] = reader;
Type resSetType;
if (_mediator.UserResourceSet == null)
{
Debug.Assert(resSetTypeName != null, "We should have a ResourceSet type name from the custom resource file here.");
resSetType = Type.GetType(resSetTypeName, true, false)!;
}
else
{
resSetType = _mediator.UserResourceSet;
}
ResourceSet rs = (ResourceSet)Activator.CreateInstance(resSetType,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null,
resourceSetArgs,
null,
null)!;
return rs;
}
}
else
{
store.Position = startPos;
}
}
if (_mediator.UserResourceSet == null)
{
return new RuntimeResourceSet(store, permitDeserialization:true);
}
else
{
object[] args = new object[2];
args[0] = store;
args[1] = assembly;
try
{
ResourceSet? rs = null;
// Add in a check for a constructor taking in an assembly first.
try
{
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!;
return rs;
}
catch (MissingMethodException) { }
args = new object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args)!;
return rs;
}
catch (MissingMethodException e)
{
throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), e);
}
}
}
private Stream? GetManifestResourceStream(Assembly satellite, string fileName)
{
Debug.Assert(satellite != null, "satellite shouldn't be null; check caller");
Debug.Assert(fileName != null, "fileName shouldn't be null; check caller");
Stream? stream = satellite.GetManifestResourceStream(_mediator.LocationInfo!, fileName);
if (stream == null)
{
stream = CaseInsensitiveManifestResourceStreamLookup(satellite, fileName);
}
return stream;
}
// Looks up a .resources file in the assembly manifest using
// case-insensitive lookup rules. Yes, this is slow. The metadata
// dev lead refuses to make all assembly manifest resource lookups case-insensitive,
// even optionally case-insensitive.
private Stream? CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name)
{
Debug.Assert(satellite != null, "satellite shouldn't be null; check caller");
Debug.Assert(name != null, "name shouldn't be null; check caller");
string? nameSpace = _mediator.LocationInfo?.Namespace;
char c = Type.Delimiter;
string resourceName = nameSpace != null && name != null ?
string.Concat(nameSpace, new ReadOnlySpan<char>(ref c, 1), name) :
string.Concat(nameSpace, name);
string? canonicalName = null;
foreach (string existingName in satellite.GetManifestResourceNames())
{
if (string.Equals(existingName, resourceName, StringComparison.InvariantCultureIgnoreCase))
{
if (canonicalName == null)
{
canonicalName = existingName;
}
else
{
throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_MultipleBlobs, resourceName, satellite.ToString()));
}
}
}
if (canonicalName == null)
{
return null;
}
return satellite.GetManifestResourceStream(canonicalName);
}
private Assembly? GetSatelliteAssembly(CultureInfo lookForCulture)
{
Debug.Assert(_mediator.MainAssembly != null);
if (!_mediator.LookedForSatelliteContractVersion)
{
_mediator.SatelliteContractVersion = _mediator.ObtainSatelliteContractVersion(_mediator.MainAssembly);
_mediator.LookedForSatelliteContractVersion = true;
}
Assembly? satellite = null;
// Look up the satellite assembly, but don't let problems
// like a partially signed satellite assembly stop us from
// doing fallback and displaying something to the user.
try
{
satellite = InternalGetSatelliteAssembly(_mediator.MainAssembly, lookForCulture, _mediator.SatelliteContractVersion);
}
catch (FileLoadException)
{
}
catch (BadImageFormatException)
{
// Don't throw for zero-length satellite assemblies, for compat with v1
}
return satellite;
}
// Perf optimization - Don't use Reflection for most cases with
// our .resources files. This makes our code run faster and we can avoid
// creating a ResourceReader via Reflection. This would incur
// a security check (since the link-time check on the constructor that
// takes a String is turned into a full demand with a stack walk)
// and causes partially trusted localized apps to fail.
private bool CanUseDefaultResourceClasses(string readerTypeName, string resSetTypeName)
{
Debug.Assert(readerTypeName != null, "readerTypeName shouldn't be null; check caller");
Debug.Assert(resSetTypeName != null, "resSetTypeName shouldn't be null; check caller");
if (_mediator.UserResourceSet != null)
return false;
// Ignore the actual version of the ResourceReader and
// RuntimeResourceSet classes. Let those classes deal with
// versioning themselves.
if (readerTypeName != null)
{
if (!ResourceManager.IsDefaultType(readerTypeName, ResourceManager.ResReaderTypeName))
return false;
}
if (resSetTypeName != null)
{
if (!ResourceManager.IsDefaultType(resSetTypeName, ResourceManager.ResSetTypeName))
return false;
}
return true;
}
private void HandleSatelliteMissing()
{
Debug.Assert(_mediator.MainAssembly != null);
string satAssemName = _mediator.MainAssembly.GetName().Name + ".resources.dll";
if (_mediator.SatelliteContractVersion != null)
{
satAssemName += ", Version=" + _mediator.SatelliteContractVersion.ToString();
}
byte[]? token = _mediator.MainAssembly.GetName().GetPublicKeyToken();
if (token != null)
{
int iLen = token.Length;
StringBuilder publicKeyTok = new StringBuilder(iLen * 2);
for (int i = 0; i < iLen; i++)
{
publicKeyTok.Append(token[i].ToString("x", CultureInfo.InvariantCulture));
}
satAssemName += ", PublicKeyToken=" + publicKeyTok;
}
Debug.Assert(_mediator.NeutralResourcesCulture != null);
string missingCultureName = _mediator.NeutralResourcesCulture.Name;
if (missingCultureName.Length == 0)
{
missingCultureName = "<invariant>";
}
throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, satAssemName), missingCultureName);
}
private static string GetManifestResourceNamesList(Assembly assembly)
{
try
{
string postfix = "\"";
string [] resourceSetNames = assembly.GetManifestResourceNames();
// If we have more than 10 resource sets, we just print the first 10 for the sake of the exception message readability.
if (resourceSetNames.Length > 10)
{
resourceSetNames = resourceSetNames[..10];
postfix = "\", ...";
}
return "\"" + String.Join("\", \"", resourceSetNames) + postfix;
}
catch
{
return "\"\"";
}
}
private void HandleResourceStreamMissing(string fileName)
{
Debug.Assert(_mediator.BaseName != null);
// Keep people from bothering me about resources problems
if (_mediator.MainAssembly == typeof(object).Assembly && _mediator.BaseName.Equals(System.CoreLib.Name))
{
// This would break CultureInfo & all our exceptions.
Debug.Fail("Couldn't get " + System.CoreLib.Name + ResourceManager.ResFileExtension + " from " + System.CoreLib.Name + "'s assembly" + Environment.NewLine + Environment.NewLine + "Are you building the runtime on your machine? Chances are the BCL directory didn't build correctly. Type 'build -c' in the BCL directory. If you get build errors, look at buildd.log. If you then can't figure out what's wrong (and you aren't changing the assembly-related metadata code), ask a BCL dev.\n\nIf you did NOT build the runtime, you shouldn't be seeing this and you've found a bug.");
// We cannot continue further - simply FailFast.
string mesgFailFast = System.CoreLib.Name + ResourceManager.ResFileExtension + " couldn't be found! Large parts of the BCL won't work!";
System.Environment.FailFast(mesgFailFast);
}
// We really don't think this should happen - we always
// expect the neutral locale's resources to be present.
string resName = string.Empty;
if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null)
resName = _mediator.LocationInfo.Namespace + Type.Delimiter;
resName += fileName;
Debug.Assert(_mediator.MainAssembly != null);
throw new MissingManifestResourceException(
SR.Format(SR.MissingManifestResource_NoNeutralAsm,
resName, _mediator.MainAssembly.GetName().Name, GetManifestResourceNamesList(_mediator.MainAssembly)));
}
}
}
| |
namespace Macabresoft.Macabre2D.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Newtonsoft.Json;
/// <summary>
/// Interface to manage assets.
/// </summary>
public interface IAssetManager : IDisposable {
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="contentManager">The content manager.</param>
/// <param name="serializer">The serializer.</param>
void Initialize(ContentManager contentManager, ISerializer serializer);
/// <summary>
/// Registers the content meta data into the cache.
/// </summary>
/// <param name="metadata">The metadata.</param>
void RegisterMetadata(ContentMetadata metadata);
/// <summary>
/// Resolves an asset reference and loads required content.
/// </summary>
/// <param name="assetReference">The asset reference to resolve.</param>
/// <typeparam name="TAsset">The type of asset.</typeparam>
/// <typeparam name="TContent">The type of content.</typeparam>
/// <returns>A value indicating whether or not the asset was resolved.</returns>
bool ResolveAsset<TAsset, TContent>(AssetReference<TAsset> assetReference) where TAsset : class, IAsset where TContent : class;
/// <summary>
/// Tries sto get metadata.
/// </summary>
/// <param name="contentId">The content identifier.</param>
/// <param name="metadata"></param>
/// <returns></returns>
bool TryGetMetadata(Guid contentId, out ContentMetadata? metadata);
/// <summary>
/// Loads the asset at the specified path.
/// </summary>
/// <typeparam name="T">The type of asset to load.</typeparam>
/// <param name="contentPath">The path.</param>
/// <param name="loaded">The loaded content.</param>
/// <returns>The asset.</returns>
bool TryLoadContent<T>(string contentPath, out T? loaded) where T : class;
/// <summary>
/// Loads the asset with the specified identifier.
/// </summary>
/// <typeparam name="T">The type of asset to load.</typeparam>
/// <param name="id">The identifier.</param>
/// <param name="loaded">The loaded content.</param>
/// <returns>The asset.</returns>
bool TryLoadContent<T>(Guid id, out T? loaded) where T : class;
/// <summary>
/// Unloads the content manager.
/// </summary>
void Unload();
}
/// <summary>
/// Maps content with identifiers. This should be the primary way that content is accessed.
/// </summary>
public sealed class AssetManager : IAssetManager {
private const string MonoGameNamespace = nameof(Microsoft) + "." + nameof(Microsoft.Xna) + "." + nameof(Microsoft.Xna.Framework);
/// <summary>
/// The default empty <see cref="IAssetManager" /> that is present before initialization.
/// </summary>
public static readonly IAssetManager Empty = new EmptyAssetManager();
private readonly HashSet<ContentMetadata> _loadedMetadata = new();
private ContentManager? _contentManager;
private ISerializer? _serializer;
/// <inheritdoc />
public void Dispose() {
this.Unload();
this._loadedMetadata.Clear();
this._serializer = null;
this._contentManager?.Dispose();
this._contentManager = null;
}
/// <inheritdoc />
public void Initialize(ContentManager contentManager, ISerializer serializer) {
this._contentManager = contentManager ?? throw new ArgumentNullException(nameof(contentManager));
this._serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
}
/// <inheritdoc />
public void RegisterMetadata(ContentMetadata metadata) {
this._loadedMetadata.Add(metadata);
}
/// <inheritdoc />
public bool ResolveAsset<TAsset, TContent>(AssetReference<TAsset> assetReference)
where TAsset : class, IAsset
where TContent : class {
var asset = assetReference.Asset ?? this.GetAsset<TAsset>(assetReference.ContentId);
if (asset != null) {
this.LoadContentForAsset<TContent>(asset);
assetReference.Initialize(asset);
}
return asset != null;
}
/// <inheritdoc />
public bool TryGetMetadata(Guid contentId, out ContentMetadata? metadata) {
if (contentId != Guid.Empty) {
if (this._loadedMetadata.FirstOrDefault(x => x.ContentId == contentId) is ContentMetadata cachedMetadata) {
metadata = cachedMetadata;
}
else if (this.TryLoadContent(ContentMetadata.GetMetadataPath(contentId), out ContentMetadata? foundMetadata) && foundMetadata != null) {
metadata = foundMetadata;
this.RegisterMetadata(foundMetadata);
}
else {
metadata = null;
}
}
else {
metadata = null;
}
return metadata != null;
}
/// <inheritdoc />
public bool TryLoadContent<T>(string contentPath, out T? loaded) where T : class {
loaded = null;
if (this._contentManager != null) {
if (typeof(T).Namespace?.StartsWith(MonoGameNamespace) == true) {
try {
loaded = this._contentManager.Load<T?>(contentPath);
}
catch (ContentLoadException) {
// TODO: log this
}
}
else if (this._serializer != null) {
try {
var fileStream = TitleContainer.OpenStream(Path.Combine(this._contentManager.RootDirectory, contentPath));
loaded = this._serializer.Deserialize<T>(fileStream);
}
catch (FileNotFoundException) {
// TODO: log this
}
catch (JsonSerializationException) {
// TODO: log this
}
}
}
return loaded != null;
}
/// <inheritdoc />
public bool TryLoadContent<T>(Guid id, out T? loaded) where T : class {
if (this.TryGetContentPath(id, out var path) && !string.IsNullOrWhiteSpace(path)) {
this.TryLoadContent(path, out loaded);
}
else {
loaded = null;
}
return loaded != null;
}
/// <inheritdoc />
public void Unload() {
this._contentManager?.Unload();
this._loadedMetadata.Clear();
}
private TAsset? GetAsset<TAsset>(Guid contentId) where TAsset : class, IAsset {
TAsset? result = null;
if (contentId != Guid.Empty) {
if (this._loadedMetadata.FirstOrDefault(x => x.ContentId == contentId)?.Asset is TAsset asset) {
result = asset;
}
else if (this.TryGetMetadata(contentId, out var metadata) && metadata != null) {
result = metadata.Asset as TAsset;
}
}
return result;
}
private void LoadContentForAsset<TContent>(IAsset asset) where TContent : class {
if (asset is IAsset<TContent> { Content: null } contentAsset &&
this.TryLoadContent<TContent>(asset.ContentId, out var content) &&
content != null) {
contentAsset.LoadContent(content);
}
}
private bool TryGetContentPath(Guid contentId, out string? contentPath) {
if (this.TryGetMetadata(contentId, out var metadata) && metadata != null) {
contentPath = metadata.GetContentPath();
}
else {
contentPath = null;
}
return !string.IsNullOrEmpty(contentPath);
}
private sealed class EmptyAssetManager : IAssetManager {
/// <inheritdoc />
public void Dispose() {
}
/// <inheritdoc />
public void Initialize(ContentManager contentManager, ISerializer serializer) {
}
/// <inheritdoc />
public void RegisterMetadata(ContentMetadata metadata) {
}
/// <inheritdoc />
public bool ResolveAsset<TAsset, TContent>(AssetReference<TAsset> assetReference) where TAsset : class, IAsset where TContent : class {
return false;
}
/// <inheritdoc />
public bool TryGetMetadata(Guid contentId, out ContentMetadata? metadata) {
metadata = null;
return false;
}
/// <inheritdoc />
public bool TryLoadContent<T>(string contentPath, out T? loaded) where T : class {
loaded = null;
return false;
}
/// <inheritdoc />
public bool TryLoadContent<T>(Guid id, out T? loaded) where T : class {
loaded = null;
return false;
}
/// <inheritdoc />
public void Unload() {
}
}
}
| |
/*
* 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.Core.Impl.Transactions
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Transactions facade.
/// </summary>
internal class TransactionsImpl : PlatformTargetAdapter, ITransactions
{
/** */
private const int OpCacheConfigParameters = 1;
/** */
private const int OpMetrics = 2;
/** */
private const int OpStart = 3;
/** */
private const int OpCommit = 4;
/** */
private const int OpRollback = 5;
/** */
private const int OpClose = 6;
/** */
private const int OpState = 7;
/** */
private const int OpSetRollbackOnly = 8;
/** */
private const int OpCommitAsync = 9;
/** */
private const int OpRollbackAsync = 10;
/** */
private const int OpResetMetrics = 11;
/** */
private const int OpPrepare = 12;
/** */
private readonly TransactionConcurrency _dfltConcurrency;
/** */
private readonly TransactionIsolation _dfltIsolation;
/** */
private readonly TimeSpan _dfltTimeout;
/** */
private readonly Guid _localNodeId;
/// <summary>
/// Initializes a new instance of the <see cref="TransactionsImpl" /> class.
/// </summary>
/// <param name="target">Target.</param>
/// <param name="localNodeId">Local node id.</param>
public TransactionsImpl(IPlatformTargetInternal target, Guid localNodeId) : base(target)
{
_localNodeId = localNodeId;
var res = target.OutStream(OpCacheConfigParameters, reader => Tuple.Create(
(TransactionConcurrency) reader.ReadInt(),
(TransactionIsolation) reader.ReadInt(),
reader.ReadLongAsTimespan()));
_dfltConcurrency = res.Item1;
_dfltIsolation = res.Item2;
_dfltTimeout = res.Item3;
}
/** <inheritDoc /> */
public ITransaction TxStart()
{
return TxStart(_dfltConcurrency, _dfltIsolation);
}
/** <inheritDoc /> */
public ITransaction TxStart(TransactionConcurrency concurrency, TransactionIsolation isolation)
{
return TxStart(concurrency, isolation, _dfltTimeout, 0);
}
/** <inheritDoc /> */
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public ITransaction TxStart(TransactionConcurrency concurrency, TransactionIsolation isolation,
TimeSpan timeout, int txSize)
{
var id = DoOutInOp(OpStart, w =>
{
w.WriteInt((int) concurrency);
w.WriteInt((int) isolation);
w.WriteTimeSpanAsLong(timeout);
w.WriteInt(txSize);
}, s => s.ReadLong());
var innerTx = new TransactionImpl(id, this, concurrency, isolation, timeout, _localNodeId);
return new Transaction(innerTx);
}
/** <inheritDoc /> */
public ITransaction Tx
{
get { return TransactionImpl.Current; }
}
/** <inheritDoc /> */
public ITransactionMetrics GetMetrics()
{
return DoInOp(OpMetrics, stream =>
{
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
return new TransactionMetricsImpl(reader);
});
}
/** <inheritDoc /> */
public void ResetMetrics()
{
DoOutInOp(OpResetMetrics);
}
/** <inheritDoc /> */
public TransactionConcurrency DefaultTransactionConcurrency
{
get { return _dfltConcurrency; }
}
/** <inheritDoc /> */
public TransactionIsolation DefaultTransactionIsolation
{
get { return _dfltIsolation; }
}
/** <inheritDoc /> */
public TimeSpan DefaultTimeout
{
get { return _dfltTimeout; }
}
/// <summary>
/// Executes prepare step of the two phase commit.
/// </summary>
internal void TxPrepare(TransactionImpl tx)
{
DoOutInOp(OpPrepare, tx.Id);
}
/// <summary>
/// Commit transaction.
/// </summary>
/// <param name="tx">Transaction.</param>
/// <returns>Final transaction state.</returns>
internal TransactionState TxCommit(TransactionImpl tx)
{
return (TransactionState) DoOutInOp(OpCommit, tx.Id);
}
/// <summary>
/// Rollback transaction.
/// </summary>
/// <param name="tx">Transaction.</param>
/// <returns>Final transaction state.</returns>
internal TransactionState TxRollback(TransactionImpl tx)
{
return (TransactionState) DoOutInOp(OpRollback, tx.Id);
}
/// <summary>
/// Close transaction.
/// </summary>
/// <param name="tx">Transaction.</param>
/// <returns>Final transaction state.</returns>
internal int TxClose(TransactionImpl tx)
{
return (int) DoOutInOp(OpClose, tx.Id);
}
/// <summary>
/// Get transaction current state.
/// </summary>
/// <param name="tx">Transaction.</param>
/// <returns>Transaction current state.</returns>
internal TransactionState TxState(TransactionImpl tx)
{
return (TransactionState) DoOutInOp(OpState, tx.Id);
}
/// <summary>
/// Set transaction rollback-only flag.
/// </summary>
/// <param name="tx">Transaction.</param>
/// <returns><c>true</c> if the flag was set.</returns>
internal bool TxSetRollbackOnly(TransactionImpl tx)
{
return DoOutInOp(OpSetRollbackOnly, tx.Id) == True;
}
/// <summary>
/// Commits tx in async mode.
/// </summary>
internal Task CommitAsync(TransactionImpl tx)
{
return DoOutOpAsync(OpCommitAsync, w => w.WriteLong(tx.Id));
}
/// <summary>
/// Rolls tx back in async mode.
/// </summary>
internal Task RollbackAsync(TransactionImpl tx)
{
return DoOutOpAsync(OpRollbackAsync, w => w.WriteLong(tx.Id));
}
}
}
| |
// 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 Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.DeriveBytesTests
{
public class PasswordDeriveBytesTests
{
// Note some tests were copied from Rfc2898DeriveBytes (and modified accordingly).
private static readonly byte[] s_testSalt = new byte[] { 9, 5, 5, 5, 1, 2, 1, 2 };
private static readonly byte[] s_testSaltB = new byte[] { 0, 4, 0, 4, 1, 9, 7, 5 };
private const string TestPassword = "PasswordGoesHere";
private const string TestPasswordB = "FakePasswordsAreHard";
private const int DefaultIterationCount = 100;
[Fact]
public static void Ctor_NullPasswordBytes()
{
using (var pdb = new PasswordDeriveBytes((byte[])null, s_testSalt))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(s_testSalt, pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_NullPasswordString()
{
Assert.Throws<ArgumentNullException>(() => new PasswordDeriveBytes((string)null, s_testSalt));
}
[Fact]
public static void Ctor_NullSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, null))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Null(pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_EmptySalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, Array.Empty<byte>()))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(Array.Empty<byte>(), pdb.Salt);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_DiminishedSalt()
{
using (var pdb = new PasswordDeriveBytes(TestPassword, new byte[7]))
{
Assert.Equal(DefaultIterationCount, pdb.IterationCount);
Assert.Equal(7, pdb.Salt.Length);
Assert.Equal("SHA1", pdb.HashName);
}
}
[Fact]
public static void Ctor_TooFewIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 0));
}
[Fact]
public static void Ctor_NegativeIterations()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue));
Assert.Throws<ArgumentOutOfRangeException>(() => new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", int.MinValue / 2));
}
[Fact]
public static void Ctor_DefaultIterations()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal(DefaultIterationCount, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_IterationsRespected()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 1))
{
Assert.Equal(1, deriveBytes.IterationCount);
}
}
[Fact]
public static void Ctor_CspParameters()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, new CspParameters())) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, new CspParameters())) { }
}
[Fact]
public static void Ctor_CspParameters_Null()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", 100, null)) { }
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, s_testSalt, "SHA1", 100, null)) { }
}
[Fact]
public static void Ctor_SaltCopied()
{
byte[] saltIn = (byte[])s_testSalt.Clone();
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, saltIn, "SHA1", DefaultIterationCount))
{
byte[] saltOut = deriveBytes.Salt;
Assert.NotSame(saltIn, saltOut);
Assert.Equal(saltIn, saltOut);
// Right now we know that at least one of the constructor and get_Salt made a copy, if it was
// only get_Salt then this next part would fail.
saltIn[0] = unchecked((byte)~saltIn[0]);
// Have to read the property again to prove it's detached.
Assert.NotEqual(saltIn, deriveBytes.Salt);
}
}
[Fact]
public static void GetSaltCopies()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt, "SHA1", DefaultIterationCount))
{
first = deriveBytes.Salt;
second = deriveBytes.Salt;
}
Assert.NotSame(first, second);
Assert.Equal(first, second);
}
[Fact]
public static void SetSaltAfterGetBytes_Throws()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
Assert.Throws<CryptographicException>(() => deriveBytes.Salt = s_testSalt);
}
}
[Fact]
public static void SetSaltAfterGetBytes_Reset()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
deriveBytes.GetBytes(1);
deriveBytes.Reset();
deriveBytes.Salt = s_testSaltB;
Assert.Equal(s_testSaltB, deriveBytes.Salt);
}
}
[Fact]
public static void MinimumAcceptableInputs()
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(string.Empty, new byte[8], "SHA1", 1))
{
output = deriveBytes.GetBytes(1);
}
Assert.Equal(1, output.Length);
Assert.Equal(0xF8, output[0]);
}
[Fact]
public static void GetBytes_ZeroLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
AssertExtensions.Throws<ArgumentException>(null, () => deriveBytes.GetBytes(0));
}
}
[Fact]
public static void GetBytes_NegativeLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(-1));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue));
Assert.Throws<OverflowException>(() => deriveBytes.GetBytes(int.MinValue / 2));
}
}
[Fact]
public static void GetBytes_NotIdempotent()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
second = deriveBytes.GetBytes(32);
}
Assert.NotEqual(first, second);
}
[Fact]
public static void GetBytes_StableIfReset()
{
byte[] first;
byte[] second;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
first = deriveBytes.GetBytes(32);
deriveBytes.Reset();
second = deriveBytes.GetBytes(32);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_ExtraBytes()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// SHA1 default
Assert.Equal("SHA1", deriveBytes.HashName);
// Request double of SHA1 hash size
first = deriveBytes.GetBytes(40);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Make two passes over the hash
byte[] secondFirstHalf = deriveBytes.GetBytes(first.Length / 2);
// Since we requested 20 bytes there are no 'extra' bytes left over to cause the "_extraCount" bug
// in GetBytes(); that issue is tested in GetBytes_StreamLike_Bug_Compat.
// Request 20 'extra' bytes in one call
byte[] secondSecondHalf = deriveBytes.GetBytes(first.Length - secondFirstHalf.Length);
Buffer.BlockCopy(secondFirstHalf, 0, second, 0, secondFirstHalf.Length);
Buffer.BlockCopy(secondSecondHalf, 0, second, secondFirstHalf.Length, secondSecondHalf.Length);
}
Assert.Equal(first, second);
}
[Fact]
public static void GetBytes_StreamLike_Bug_Compat()
{
byte[] first;
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Equal("SHA1", deriveBytes.HashName);
// Request 20 bytes (SHA1 hash size) plus 12 extra bytes
first = deriveBytes.GetBytes(32);
}
byte[] second = new byte[first.Length];
// Reset
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Ask for half now (16 bytes)
byte[] firstHalf = deriveBytes.GetBytes(first.Length / 2);
// Ask for the other half now (16 bytes)
byte[] lastHalf = deriveBytes.GetBytes(first.Length - firstHalf.Length);
// lastHalf should contain the last 4 bytes from the SHA1 hash plus 12 extra bytes
// but due to the _extraCount bug it doesn't.
// Merge the two buffers into the second array
Buffer.BlockCopy(firstHalf, 0, second, 0, firstHalf.Length);
Buffer.BlockCopy(lastHalf, 0, second, firstHalf.Length, lastHalf.Length);
}
// Fails due to _extraCount bug (the bug is fixed in Rfc2898DeriveBytes)
Assert.NotEqual(first, second);
// However, the first 16 bytes will be equal because the _extraCount bug does
// not affect the first call, only the subsequent GetBytes() call.
byte[] first_firstHalf = new byte[first.Length / 2];
byte[] second_firstHalf = new byte[first.Length / 2];
Buffer.BlockCopy(first, 0, first_firstHalf, 0, first_firstHalf.Length);
Buffer.BlockCopy(second, 0, second_firstHalf, 0, second_firstHalf.Length);
Assert.Equal(first_firstHalf, second_firstHalf);
}
[Fact]
public static void GetBytes_Boundary()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
// Boundary case success
deriveBytes.GetBytes(1000 * 20);
// Boundary case failure
Assert.Throws<CryptographicException>(() => deriveBytes.GetBytes(1));
}
}
[Fact]
public static void GetBytes_KnownValues_MD5_32()
{
TestKnownValue_GetBytes(
HashAlgorithmName.MD5,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("F8D88E9DAFC828DA2400F5144271C2F630A1C061C654FC9DE2E7900E121461B9"));
}
[Fact]
public static void GetBytes_KnownValues_SHA256_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA256,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("3774A17468276057717A90C25B72915921D8F8C046F7868868DBB99BB4C4031CADE9E26BE77BEA39"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("12F2497EC3EB78B0EA32AABFD8B9515FBC800BEEB6316A4DDF4EA62518341488A116DA3BBC26C685"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_2()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSalt,
DefaultIterationCount + 1,
ByteUtils.HexToByteArray("FB6199E4D9BB017D2F3AF6964F3299971607C6B984934A9E43140631957429160C33A6630EF12E31"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_3()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPassword,
s_testSaltB,
DefaultIterationCount,
ByteUtils.HexToByteArray("DCA4851AB3C9960CF387E64DE7A1B2E09616BEA6A4666AAFAC31F1670F23530E38BD4BF4D9248A08"));
}
[Fact]
public static void GetBytes_KnownValues_SHA1_40_4()
{
TestKnownValue_GetBytes(
HashAlgorithmName.SHA1,
TestPasswordB,
s_testSalt,
DefaultIterationCount,
ByteUtils.HexToByteArray("1DCA2A3405E93D9E3F7CD10653444F2FD93F5BE32C4B1BEDDF94D0D67461CBE86B5BDFEB32071E96"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_TripleDes()
{
byte[] key = TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"TripleDES",
192,
s_testSalt,
ByteUtils.HexToByteArray("97628A641949D99DCED35DB0ABCE20F21FF4DA9B46E00BCE"));
// Verify key is valid
using (var alg = new TripleDESCryptoServiceProvider())
{
alg.Key = key;
alg.IV = new byte[8];
alg.Padding = PaddingMode.None;
alg.Mode = CipherMode.CBC;
byte[] plainText = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
byte[] cipher = alg.Encrypt(plainText);
byte[] expectedCipher = "9DC863445642B88AC46B3B107CB5A0ACC1596A176962EE8F".HexToByteArray();
Assert.Equal<byte>(expectedCipher, cipher);
byte[] decrypted = alg.Decrypt(cipher);
byte[] expectedDecrypted = "79a86903608e133e020e1dc68c9835250c2f17b0ebeed91b".HexToByteArray();
Assert.Equal<byte>(expectedDecrypted, decrypted);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_RC2()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA256,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("CF4A1CA60093E71D6B740DBB962B3C66"));
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.MD5,
TestPassword,
"RC2",
128,
s_testSalt,
ByteUtils.HexToByteArray("84F4B6854CDF896A86FB493B852B6E1F"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_RC2_NoSalt()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"RC2",
128,
null, // Salt is not used here so we should get same key value
ByteUtils.HexToByteArray("B0695D8D98F5844B9650A9F68EFF105B"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_KnownValues_DES()
{
TestKnownValue_CryptDeriveKey(
HashAlgorithmName.SHA1,
TestPassword,
"DES",
64,
s_testSalt,
ByteUtils.HexToByteArray("B0685D8C98F4854A"));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_KeyLength()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 127, s_testSalt));
Assert.ThrowsAny<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 129, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_Algorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("BADALG", "SHA1", 128, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_HashAlgorithm()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "BADALG", 128, s_testSalt));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // No support for CryptDeriveKey on Unix
public static void CryptDeriveKey_Invalid_IV()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null));
Assert.Throws<CryptographicException>(() => deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, new byte[1]));
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public static void CryptDeriveKey_Throws_Unix()
{
using (var deriveBytes = new PasswordDeriveBytes(TestPassword, s_testSalt))
{
Assert.Throws<PlatformNotSupportedException>(() => (deriveBytes.CryptDeriveKey("RC2", "SHA1", 128, null)));
}
}
private static byte[] TestKnownValue_CryptDeriveKey(HashAlgorithmName hashName, string password, string alg, int keySize, byte[] salt, byte[] expected)
{
byte[] output;
byte[] iv = new byte[8];
using (var deriveBytes = new PasswordDeriveBytes(password, salt))
{
output = deriveBytes.CryptDeriveKey(alg, hashName.Name, keySize, iv);
}
Assert.Equal(expected, output);
// For these tests, the returned IV is always zero
Assert.Equal(new byte[8], iv);
return output;
}
private static void TestKnownValue_GetBytes(HashAlgorithmName hashName, string password, byte[] salt, int iterationCount, byte[] expected)
{
byte[] output;
using (var deriveBytes = new PasswordDeriveBytes(password, salt, hashName.Name, iterationCount))
{
output = deriveBytes.GetBytes(expected.Length);
}
Assert.Equal(expected, output);
}
}
}
| |
using UnityEngine;
using System.Collections;
using PixelCrushers.DialogueSystem.UnityGUI;
namespace PixelCrushers.DialogueSystem {
/// <summary>
/// This component implements a selector that allows the player to target and use a usable
/// object.
///
/// To mark an object usable, add the Usable component and a collider to it. The object's
/// layer should be in the layer mask specified on the Selector component.
///
/// The selector can be configured to target items under the mouse cursor or the middle of
/// the screen. When a usable object is targeted, the selector displays a targeting reticle
/// and information about the object. If the target is in range, the inRange reticle
/// texture is displayed; otherwise the outOfRange texture is displayed.
///
/// If the player presses the use button (which defaults to spacebar and Fire2), the targeted
/// object will receive an "OnUse" message.
///
/// You can hook into SelectedUsableObject and DeselectedUsableObject to get notifications
/// when the current target has changed.
/// </summary>
[AddComponentMenu("Dialogue System/Actor/Player/Selector")]
public class Selector : MonoBehaviour {
/// <summary>
/// This class defines the textures and size of the targeting reticle.
/// </summary>
[System.Serializable]
public class Reticle {
public Texture2D inRange;
public Texture2D outOfRange;
public float width = 64f;
public float height = 64f;
}
/// <summary>
/// Specifies how to target: center of screen or under the mouse cursor.
/// </summary>
public enum SelectAt { CenterOfScreen, MousePosition, CustomPosition };
/// <summary>
/// Specifies whether to compute range from the targeted object (distance to the camera
/// or distance to the selector's game object).
/// </summary>
public enum DistanceFrom { Camera, GameObject };
/// <summary>
/// Specifies whether to do 2D or 3D raycasts.
/// </summary>
public enum Dimension { In2D, In3D };
/// <summary>
/// The default layermask is just the Default layer.
/// </summary>
private static LayerMask DefaultLayer = 1;
/// <summary>
/// The layer mask to use when targeting objects. Objects on others layers are ignored.
/// </summary>
[Tooltip("Layer mask to use when targeting objects; objects on others layers are ignored")]
public LayerMask layerMask = DefaultLayer;
/// <summary>
/// How to target (center of screen or under mouse cursor). Default is center of screen.
/// </summary>
[Tooltip("How to target")]
public SelectAt selectAt = SelectAt.CenterOfScreen;
/// <summary>
/// How to compute range to targeted object. Default is from the camera.
/// </summary>
[Tooltip("How to compute range to targeted object")]
public DistanceFrom distanceFrom = DistanceFrom.Camera;
/// <summary>
/// The max selection distance. The selector won't target objects farther than this.
/// </summary>
[Tooltip("Don't target objects farther than this; targets may still be unusable if beyond their usable range")]
public float maxSelectionDistance = 30f;
/// <summary>
/// Specifies whether to run 2D or 3D raycasts.
/// </summary>
public Dimension runRaycasts = Dimension.In3D;
/// <summary>
/// Set <c>true</c> to check all objects within the raycast range for usables.
/// If <c>false</c>, the check stops on the first hit, even if it's not a usable.
/// This prevents selection through walls.
/// </summary>
[Tooltip("Tick to check all objects within raycast range for usables, even passing through obstacles")]
public bool raycastAll = false;
/// <summary>
/// If <c>true</c>, uses a default OnGUI to display a selection message and
/// targeting reticle.
/// </summary>
[Tooltip("")]
public bool useDefaultGUI = true;
/// <summary>
/// The GUI skin to use for the target's information (name and use message).
/// </summary>
[Tooltip("The GUI skin to use for the target's information (name and use message)")]
public GUISkin guiSkin;
/// <summary>
/// The name of the GUI style in the skin.
/// </summary>
[Tooltip("The name of the GUI style in the skin")]
public string guiStyleName = "label";
/// <summary>
/// The text alignment.
/// </summary>
public TextAnchor alignment = TextAnchor.UpperCenter;
/// <summary>
/// The text style for the text.
/// </summary>
public TextStyle textStyle = TextStyle.Shadow;
/// <summary>
/// The color of the text style's outline or shadow.
/// </summary>
public Color textStyleColor = Color.black;
/// <summary>
/// The color of the information labels when the target is in range.
/// </summary>
[Tooltip("The color of the information labels when the target is in range")]
public Color inRangeColor = Color.yellow;
/// <summary>
/// The color of the information labels when the target is out of range.
/// </summary>
[Tooltip("The color of the information labels when the target is out of range")]
public Color outOfRangeColor = Color.gray;
/// <summary>
/// The reticle images.
/// </summary>
public Reticle reticle;
/// <summary>
/// The key that sends an OnUse message.
/// </summary>
public KeyCode useKey = KeyCode.Space;
/// <summary>
/// The button that sends an OnUse message.
/// </summary>
public string useButton = "Fire2";
/// <summary>
/// The default use message. This can be overridden in the target's Usable component.
/// </summary>
[Tooltip("Default use message; can be overridden in the target's Usable component")]
public string defaultUseMessage = "(spacebar to interact)";
/// <summary>
/// If ticked, the OnUse message is broadcast to the usable object's children.
/// </summary>
[Tooltip("Tick to also broadcast to the usable object's children")]
public bool broadcastToChildren = true;
/// <summary>
/// The actor transform to send with OnUse. Defaults to this transform.
/// </summary>
[Tooltip("Actor transform to send with OnUse; defaults to this transform")]
public Transform actorTransform = null;
/// <summary>
/// If set, show this alert message if attempt to use something beyond its usable range.
/// </summary>
[Tooltip("If set, show this alert message if attempt to use something beyond its usable range")]
public string tooFarMessage = string.Empty;
/// <summary>
/// The too far event handler.
/// </summary>
public UnityEngine.Events.UnityEvent tooFarEvent = new UnityEngine.Events.UnityEvent();
/// <summary>
/// If <c>true</c>, draws gizmos.
/// </summary>
[Tooltip("Tick to draw gizmos in Scene view")]
public bool debug = false;
/// <summary>
/// Gets or sets the custom position used when the selectAt is set to SelectAt.CustomPosition.
/// You can use, for example, to slide around a targeting icon onscreen using a gamepad.
/// </summary>
/// <value>
/// The custom position.
/// </value>
public Vector3 CustomPosition { get; set; }
/// <summary>
/// Gets the current selection.
/// </summary>
/// <value>The selection.</value>
public Usable CurrentUsable { get { return usable; } }
/// <summary>
/// Gets the distance from the current usable.
/// </summary>
/// <value>The current distance.</value>
public float CurrentDistance { get { return distance; } }
/// <summary>
/// Gets the GUI style.
/// </summary>
/// <value>The GUI style.</value>
public GUIStyle GuiStyle { get { SetGuiStyle(); return guiStyle; } }
/// <summary>
/// Occurs when the selector has targeted a usable object.
/// </summary>
public event SelectedUsableObjectDelegate SelectedUsableObject = null;
/// <summary>
/// Occurs when the selector has untargeted a usable object.
/// </summary>
public event DeselectedUsableObjectDelegate DeselectedUsableObject = null;
protected GameObject selection = null; // Currently under the selection point.
protected Usable usable = null; // Usable component of the current selection.
protected GameObject clickedDownOn = null; // Selection when the mouse button was pressed down.
protected string heading = string.Empty;
protected string useMessage = string.Empty;
protected float distance = 0;
protected GUIStyle guiStyle = null;
protected Ray lastRay = new Ray();
protected RaycastHit lastHit = new RaycastHit();
protected RaycastHit[] lastHits = new RaycastHit[0];
public virtual void Start()
{
if (Camera.main == null) Debug.LogError("Dialogue System: The scene is missing a camera tagged 'MainCamera'. The Selector may not behave the way you expect.", this);
}
/// <summary>
/// Runs a raycast to see what's under the selection point. Updates the selection and
/// calls the selection delegates if the selection has changed. If the player hits the
/// use button, sends an OnUse message to the selection.
/// </summary>
protected void Update() {
// Exit if disabled or paused:
if (!enabled || (Time.timeScale <= 0)) return;
// Exit if there's no camera:
if (UnityEngine.Camera.main == null) return;
// Exit if using mouse selection and is over a UI element:
if ((selectAt == SelectAt.MousePosition) && (UnityEngine.EventSystems.EventSystem.current != null) && UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject()) return;
// Raycast 2D or 3D:
switch (runRaycasts) {
case Dimension.In2D:
Run2DRaycast();
break;
default:
case Dimension.In3D:
Run3DRaycast();
break;
}
// If the player presses the use key/button on a target:
if (IsUseButtonDown() && (usable != null)) {
if (distance <= usable.maxUseDistance) {
// If within range, send the OnUse message:
var fromTransform = (actorTransform != null) ? actorTransform : this.transform;
if (broadcastToChildren) {
usable.gameObject.BroadcastMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
} else {
usable.gameObject.SendMessage("OnUse", fromTransform, SendMessageOptions.DontRequireReceiver);
}
} else {
// Otherwise report too far if configured to do so:
if (!string.IsNullOrEmpty(tooFarMessage)) {
DialogueManager.ShowAlert(tooFarMessage);
}
tooFarEvent.Invoke();
}
}
}
protected void Run2DRaycast() {
if (raycastAll) {
// Run Physics2D.RaycastAll:
RaycastHit2D[] hits;
hits = Physics2D.RaycastAll(UnityEngine.Camera.main.ScreenToWorldPoint(GetSelectionPoint()), Vector2.zero, maxSelectionDistance, layerMask);
bool foundUsable = false;
foreach (var hit in hits) {
float hitDistance = (distanceFrom == DistanceFrom.Camera) ? 0 : Vector3.Distance(gameObject.transform.position, hit.collider.transform.position);
if (selection == hit.collider.gameObject) {
foundUsable = true;
distance = hitDistance;
break;
} else {
Usable hitUsable = hit.collider.gameObject.GetComponent<Usable>();
if (hitUsable != null) {
foundUsable = true;
distance = hitDistance;
usable = hitUsable;
selection = hit.collider.gameObject;
if (SelectedUsableObject != null) SelectedUsableObject(usable);
break;
}
}
}
if (!foundUsable) {
DeselectTarget();
}
} else {
// Cast a ray and see what we hit:
RaycastHit2D hit;
hit = Physics2D.Raycast(UnityEngine.Camera.main.ScreenToWorldPoint(GetSelectionPoint()), Vector2.zero, maxSelectionDistance, layerMask);
if (hit.collider != null) {
distance = (distanceFrom == DistanceFrom.Camera) ? 0 : Vector3.Distance(gameObject.transform.position, hit.collider.transform.position);
if (selection != hit.collider.gameObject) {
Usable hitUsable = hit.collider.gameObject.GetComponent<Usable>();
if (hitUsable != null) {
usable = hitUsable;
selection = hit.collider.gameObject;
heading = string.Empty;
useMessage = string.Empty;
if (SelectedUsableObject != null) SelectedUsableObject(usable);
} else {
DeselectTarget();
}
}
} else {
DeselectTarget();
}
}
}
protected void Run3DRaycast() {
Ray ray = UnityEngine.Camera.main.ScreenPointToRay(GetSelectionPoint());
lastRay = ray;
if (raycastAll) {
// Run RaycastAll:
RaycastHit[] hits;
hits = Physics.RaycastAll(ray, maxSelectionDistance, layerMask);
lastRay = ray;
lastHits = hits;
bool foundUsable = false;
foreach (var hit in hits) {
float hitDistance = (distanceFrom == DistanceFrom.Camera) ? hit.distance : Vector3.Distance(gameObject.transform.position, hit.collider.transform.position);
if (selection == hit.collider.gameObject) {
foundUsable = true;
distance = hitDistance;
break;
} else {
Usable hitUsable = hit.collider.gameObject.GetComponent<Usable>();
if (hitUsable != null) {
foundUsable = true;
distance = hitDistance;
usable = hitUsable;
selection = hit.collider.gameObject;
if (SelectedUsableObject != null) SelectedUsableObject(usable);
break;
}
}
}
if (!foundUsable) {
DeselectTarget();
}
} else {
// Cast a ray and see what we hit:
RaycastHit hit;
if (Physics.Raycast(ray, out hit, maxSelectionDistance, layerMask)) {
distance = (distanceFrom == DistanceFrom.Camera) ? hit.distance : Vector3.Distance(gameObject.transform.position, hit.collider.transform.position);
if (selection != hit.collider.gameObject) {
Usable hitUsable = hit.collider.gameObject.GetComponent<Usable>();
if (hitUsable != null) {
usable = hitUsable;
selection = hit.collider.gameObject;
heading = string.Empty;
useMessage = string.Empty;
if (SelectedUsableObject != null) SelectedUsableObject(usable);
} else {
DeselectTarget();
}
}
} else {
DeselectTarget();
}
lastHit = hit;
}
}
protected virtual void DeselectTarget() {
if ((usable != null) && (DeselectedUsableObject != null)) DeselectedUsableObject(usable);
usable = null;
selection = null;
heading = string.Empty;
useMessage = string.Empty;
}
protected bool IsUseButtonDown() {
// First check for button down to remember what was selected at the time:
if (!string.IsNullOrEmpty(useButton) && Input.GetButtonDown(useButton)) {
clickedDownOn = selection;
}
// Check for use key or button (only if releasing button on same selection:
return ((useKey != KeyCode.None) && Input.GetKeyDown(useKey))
|| (!string.IsNullOrEmpty(useButton) && Input.GetButtonUp(useButton) && (selection == clickedDownOn));
}
protected Vector3 GetSelectionPoint() {
switch (selectAt) {
case SelectAt.MousePosition:
return Input.mousePosition;
case SelectAt.CustomPosition:
return CustomPosition;
default:
case SelectAt.CenterOfScreen:
return new Vector3(Screen.width / 2, Screen.height / 2);
}
}
/// <summary>
/// If useDefaultGUI is <c>true</c> and a usable object has been targeted, this method
/// draws a selection message and targeting reticle.
/// </summary>
public virtual void OnGUI() {
if (useDefaultGUI) {
SetGuiStyle();
Rect screenRect = new Rect(0, 0, Screen.width, Screen.height);
if (usable != null) {
bool inUseRange = (distance <= usable.maxUseDistance);
guiStyle.normal.textColor = inUseRange ? inRangeColor : outOfRangeColor;
if (string.IsNullOrEmpty(heading)) {
heading = usable.GetName();
useMessage = string.IsNullOrEmpty(usable.overrideUseMessage) ? defaultUseMessage : usable.overrideUseMessage;
}
UnityGUITools.DrawText(screenRect, heading, guiStyle, textStyle, textStyleColor);
UnityGUITools.DrawText(new Rect(0, guiStyle.CalcSize(new GUIContent("Ay")).y, Screen.width, Screen.height), useMessage, guiStyle, textStyle, textStyleColor);
Texture2D reticleTexture = inUseRange ? reticle.inRange : reticle.outOfRange;
if (reticleTexture != null) GUI.Label(new Rect(0.5f * (Screen.width - reticle.width), 0.5f * (Screen.height - reticle.height), reticle.width, reticle.height), reticleTexture);
}
}
}
protected void SetGuiStyle() {
GUI.skin = UnityGUITools.GetValidGUISkin(guiSkin);
if (guiStyle == null) {
guiStyle = new GUIStyle(GUI.skin.FindStyle(guiStyleName) ?? GUI.skin.label);
guiStyle.alignment = alignment;
}
}
/// <summary>
/// Draws raycast result gizmos.
/// </summary>
public virtual void OnDrawGizmos() {
if (!debug) return;
Gizmos.color = Color.yellow;
Gizmos.DrawLine(lastRay.origin, lastRay.origin + lastRay.direction * maxSelectionDistance);
if (raycastAll) {
foreach (var hit in lastHits) {
bool isUsable = (hit.collider.GetComponent<Usable>() != null);
Gizmos.color = isUsable ? Color.green : Color.red;
Gizmos.DrawWireSphere(hit.point, 0.2f);
}
} else {
if (lastHit.collider != null) {
bool isUsable = (lastHit.collider.GetComponent<Usable>() != null);
Gizmos.color = isUsable ? Color.green : Color.red;
Gizmos.DrawWireSphere(lastHit.point, 0.2f);
}
}
}
}
}
| |
//
// Lazy.cs
//
// Authors:
// Zoltan Varga (vargaz@gmail.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright (C) 2009 Novell
//
// 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.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
namespace OpenSim.Framework
{
public enum LazyThreadSafetyMode
{
None,
PublicationOnly,
ExecutionAndPublication
}
[SerializableAttribute]
[ComVisibleAttribute(false)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, ExternalThreading = true)]
public class Lazy<T>
{
private Exception exception;
private Func<T> factory;
private bool inited;
private LazyThreadSafetyMode mode;
private object monitor;
private T value;
public Lazy()
: this(LazyThreadSafetyMode.ExecutionAndPublication)
{
}
public Lazy(Func<T> valueFactory)
: this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication)
{
}
public Lazy(bool isThreadSafe)
: this(() => Activator.CreateInstance<T>(), isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
public Lazy(Func<T> valueFactory, bool isThreadSafe)
: this(valueFactory, isThreadSafe ? LazyThreadSafetyMode.ExecutionAndPublication : LazyThreadSafetyMode.None)
{
}
public Lazy(LazyThreadSafetyMode mode)
: this(() => Activator.CreateInstance<T>(), mode)
{
}
public Lazy(Func<T> valueFactory, LazyThreadSafetyMode mode)
{
if (valueFactory == null)
throw new ArgumentNullException("valueFactory");
this.factory = valueFactory;
if (mode != LazyThreadSafetyMode.None)
monitor = new object();
this.mode = mode;
}
public bool IsValueCreated
{
get
{
return inited;
}
}
// Don't trigger expensive initialization
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public T Value
{
get
{
if (inited)
return value;
if (exception != null)
throw exception;
return InitValue();
}
}
public override string ToString()
{
if (inited)
return value.ToString();
else
return "Value is not created";
}
private T InitValue()
{
switch (mode)
{
case LazyThreadSafetyMode.None:
{
var init_factory = factory;
if (init_factory == null)
throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance");
try
{
factory = null;
T v = init_factory();
value = v;
Thread.MemoryBarrier();
inited = true;
}
catch (Exception ex)
{
exception = ex;
throw;
}
break;
}
case LazyThreadSafetyMode.PublicationOnly:
{
var init_factory = factory;
T v;
//exceptions are ignored
if (init_factory != null)
v = init_factory();
else
v = default(T);
lock (monitor)
{
if (inited)
return value;
value = v;
Thread.MemoryBarrier();
inited = true;
factory = null;
}
break;
}
case LazyThreadSafetyMode.ExecutionAndPublication:
{
lock (monitor)
{
if (inited)
return value;
if (factory == null)
throw exception = new InvalidOperationException("The initialization function tries to access Value on this instance");
var init_factory = factory;
try
{
factory = null;
T v = init_factory();
value = v;
Thread.MemoryBarrier();
inited = true;
}
catch (Exception ex)
{
exception = ex;
throw;
}
}
break;
}
default:
throw new InvalidOperationException("Invalid LazyThreadSafetyMode " + mode);
}
if (monitor == null)
{
value = factory();
inited = true;
}
else
{
lock (monitor)
{
if (inited)
return value;
if (factory == null)
throw new InvalidOperationException("The initialization function tries to access Value on this instance");
var init_factory = factory;
try
{
factory = null;
T v = init_factory();
value = v;
Thread.MemoryBarrier();
inited = true;
}
catch
{
factory = init_factory;
throw;
}
}
}
return value;
}
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Drawing;
using Gallio.Common;
using Gallio.Common.Collections;
using Gallio.Common.Messaging;
using Gallio.Common.Messaging.MessageSinks;
using Gallio.Framework.Pattern;
using Gallio.Loader;
using Gallio.Model;
using Gallio.Common.Reflection;
using Gallio.Model.Messages.Exploration;
using Gallio.Model.Schema;
using Gallio.Model.Tree;
using Gallio.ReSharperRunner.Properties;
using Gallio.ReSharperRunner.Provider;
using Gallio.ReSharperRunner.Provider.Facade;
using Gallio.ReSharperRunner.Reflection;
using Gallio.ReSharperRunner.Provider.Tasks;
using Gallio.Runtime;
using Gallio.Runtime.Logging;
using Gallio.Runtime.ProgressMonitoring;
using JetBrains.CommonControls;
using JetBrains.Metadata.Reader.API;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.TaskRunnerFramework;
using JetBrains.UI.TreeView;
using Gallio.Runtime.Loader;
using JetBrains.ReSharper.UnitTestExplorer;
#if RESHARPER_50_OR_NEWER
using JetBrains.ReSharper.UnitTestFramework;
using JetBrains.ReSharper.UnitTestFramework.UI;
#endif
#if RESHARPER_31
using JetBrains.Shell;
using JetBrains.Shell.Progress;
using JetBrains.Util.DataStructures.TreeModel;
#else
using JetBrains.Application;
using JetBrains.Application.Progress;
using JetBrains.TreeModels;
#endif
namespace Gallio.ReSharperRunner.Provider
{
/// <summary>
/// This is the main entry point into the Gallio test runner for ReSharper.
/// </summary>
[UnitTestProvider]
public class GallioTestProvider : IUnitTestProvider
{
public const string ProviderId = "Gallio";
private readonly Shim shim;
static GallioTestProvider()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
public GallioTestProvider()
{
shim = new Shim(this);
}
public void ExploreExternal(UnitTestElementConsumer consumer)
{
shim.ExploreExternal(consumer);
}
public void ExploreSolution(ISolution solution, UnitTestElementConsumer consumer)
{
shim.ExploreSolution(solution, consumer);
}
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
shim.ExploreAssembly(assembly, project, consumer);
}
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
shim.ExploreFile(psiFile, consumer, interrupted);
}
#if ! RESHARPER_50_OR_NEWER
public bool IsUnitTestElement(IDeclaredElement element)
{
return shim.IsUnitTestElement(element);
}
#endif
#if RESHARPER_45
public bool IsUnitTestStuff(IDeclaredElement element)
{
return shim.IsUnitTestStuff(element);
}
#endif
#if RESHARPER_50_OR_NEWER
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
public bool IsElementOfKind(UnitTestElement element, UnitTestElementKind kind)
{
return shim.IsElementOfKind(element, kind);
}
#endif
public void Present(UnitTestElement element, IPresentableItem item, TreeModelNode node, PresentationState state)
{
shim.Present(element, item, node, state);
}
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return shim.GetTaskRunnerInfo();
}
public string Serialize(UnitTestElement element)
{
return shim.Serialize(element);
}
public UnitTestElement Deserialize(ISolution solution, string elementString)
{
return shim.Deserialize(solution, elementString);
}
public IList<UnitTestTask> GetTaskSequence(UnitTestElement element, IList<UnitTestElement> explicitElements)
{
return shim.GetTaskSequence(element, explicitElements);
}
public int CompareUnitTestElements(UnitTestElement x, UnitTestElement y)
{
return shim.CompareUnitTestElements(x, y);
}
public void ProfferConfiguration(TaskExecutorConfiguration configuration, UnitTestSession session)
{
shim.ProfferConfiguration(configuration, session);
}
public string ID
{
get { return shim.ID; }
}
#if RESHARPER_45_OR_NEWER
public Image Icon
{
get { return shim.Icon; }
}
public string Name
{
get { return shim.Name; }
}
public ProviderCustomOptionsControl GetCustomOptionsControl(ISolution solution)
{
return shim.GetCustomOptionsControl(solution);
}
#endif
internal sealed class Shim
{
private static readonly MultiMap<string, string> IncompatibleProviders = new MultiMap<string, string>()
{
{ "nUnit", new[] { "NUnitAdapter248.TestFramework", "NUnitAdapter25.TestFramework" } },
{ "MSTest", new[] { "MSTestAdapter.TestFramework" } }
};
private readonly IUnitTestProvider provider;
private readonly GallioTestPresenter presenter;
private readonly ITestFrameworkManager testFrameworkManager;
private readonly ILogger logger;
/// <summary>
/// Initializes the provider.
/// </summary>
public Shim(IUnitTestProvider provider)
{
this.provider = provider;
testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve<ITestFrameworkManager>();
presenter = new GallioTestPresenter();
logger = new FacadeLoggerWrapper(new AdapterFacadeLogger());
RuntimeAccessor.Instance.AddLogListener(logger);
}
/// <summary>
/// Explores the "world", i.e. retrieves tests not associated with current solution.
/// </summary>
public void ExploreExternal(UnitTestElementConsumer consumer)
{
if (consumer == null)
throw new ArgumentNullException("consumer");
// Nothing to do currently.
}
/// <summary>
/// Explores given solution, but not containing projects.
/// </summary>
public void ExploreSolution(ISolution solution, UnitTestElementConsumer consumer)
{
if (solution == null)
throw new ArgumentNullException("solution");
if (consumer == null)
throw new ArgumentNullException("consumer");
#if ! RESHARPER_31 && ! RESHARPER_40 && ! RESHARPER_41
using (ReadLockCookie.Create())
#endif
{
if (!solution.IsValid)
return;
// Nothing to do currently.
// TODO: Should consider test files supported by other frameworks like RSpec.
}
}
/// <summary>
/// Explores given compiled project.
/// </summary>
public void ExploreAssembly(IMetadataAssembly assembly, IProject project, UnitTestElementConsumer consumer)
{
if (assembly == null)
throw new ArgumentNullException("assembly");
if (project == null)
throw new ArgumentNullException("project");
if (consumer == null)
throw new ArgumentNullException("consumer");
#if ! RESHARPER_31 && ! RESHARPER_40 && ! RESHARPER_41
using (ReadLockCookie.Create())
#endif
{
if (!project.IsValid)
return;
try
{
MetadataReflectionPolicy reflectionPolicy = new MetadataReflectionPolicy(assembly, project);
IAssemblyInfo assemblyInfo = reflectionPolicy.Wrap(assembly);
if (assemblyInfo != null)
{
ConsumerAdapter consumerAdapter = new ConsumerAdapter(provider, consumer);
Describe(reflectionPolicy, new ICodeElementInfo[] { assemblyInfo }, consumerAdapter);
}
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
}
/// <summary>
/// Explores given PSI file.
/// </summary>
public void ExploreFile(IFile psiFile, UnitTestElementLocationConsumer consumer, CheckForInterrupt interrupted)
{
if (psiFile == null)
throw new ArgumentNullException("psiFile");
if (consumer == null)
throw new ArgumentNullException("consumer");
#if ! RESHARPER_31 && ! RESHARPER_40 && ! RESHARPER_41
using (ReadLockCookie.Create())
#endif
{
if (!psiFile.IsValid())
return;
try
{
PsiReflectionPolicy reflectionPolicy = new PsiReflectionPolicy(psiFile.GetManager());
ConsumerAdapter consumerAdapter = new ConsumerAdapter(provider, consumer, psiFile);
var codeElements = new List<ICodeElementInfo>();
psiFile.ProcessDescendants(new OneActionProcessorWithoutVisit(delegate(IElement element)
{
ITypeDeclaration declaration = element as ITypeDeclaration;
if (declaration != null)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, declaration);
}, delegate(IElement element)
{
if (interrupted())
throw new ProcessCancelledException();
// Stop recursing at the first type declaration found.
return element is ITypeDeclaration;
}));
Describe(reflectionPolicy, codeElements, consumerAdapter);
ProjectFileState.SetFileState(psiFile.GetProjectFile(), consumerAdapter.CreateProjectFileState());
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
}
private static void PopulateCodeElementsFromTypeDeclaration(List<ICodeElementInfo> codeElements, PsiReflectionPolicy reflectionPolicy, ITypeDeclaration declaration)
{
if (! declaration.IsValid())
return;
ITypeInfo typeInfo = reflectionPolicy.Wrap(declaration.DeclaredElement);
if (typeInfo != null)
codeElements.Add(typeInfo);
foreach (ITypeDeclaration nestedDeclaration in declaration.NestedTypeDeclarations)
PopulateCodeElementsFromTypeDeclaration(codeElements, reflectionPolicy, nestedDeclaration);
}
private ITestDriver CreateTestDriver()
{
var excludedTestFrameworkIds = new List<string>();
foreach (IUnitTestProvider provider in UnitTestManager.GetInstance(SolutionManager.Instance.CurrentSolution).GetEnabledProviders())
{
IList<string> frameworkIds;
if (IncompatibleProviders.TryGetValue(provider.ID, out frameworkIds))
excludedTestFrameworkIds.AddRange(frameworkIds);
}
var testFrameworkSelector = new TestFrameworkSelector()
{
Filter = testFrameworkHandle => !excludedTestFrameworkIds.Contains(testFrameworkHandle.Id),
FallbackMode = TestFrameworkFallbackMode.Approximate
};
return testFrameworkManager.GetTestDriver(testFrameworkSelector, logger);
}
private void Describe(IReflectionPolicy reflectionPolicy, IList<ICodeElementInfo> codeElements, ConsumerAdapter consumerAdapter)
{
var testDriver = CreateTestDriver();
var testExplorationOptions = new TestExplorationOptions();
testDriver.Describe(reflectionPolicy, codeElements, testExplorationOptions, consumerAdapter,
NullProgressMonitor.CreateInstance());
}
#if ! RESHARPER_50_OR_NEWER
/// <summary>
/// Checks if given declared element is UnitTestElement.
/// </summary>
public bool IsUnitTestElement(IDeclaredElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return EvalTestPartPredicate(element, x => x.IsTest);
}
#endif
#if RESHARPER_45
/// <summary>
/// Checks if given declared element is part of a unit test.
/// </summary>
/// <remarks>
/// <para>
/// Could be a set up or tear down method, or something else that belongs to a test.
/// </para>
/// </remarks>
public bool IsUnitTestStuff(IDeclaredElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return EvalTestPartPredicate(element, x => x.IsTest || x.IsTestContribution);
}
#endif
#if RESHARPER_50_OR_NEWER
public bool IsElementOfKind(IDeclaredElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
return EvalTestPartPredicate(element, testPart =>
{
switch (kind)
{
case UnitTestElementKind.Unknown:
return false;
case UnitTestElementKind.Test:
return testPart.IsTest;
case UnitTestElementKind.TestContainer:
return testPart.IsTestContainer;
case UnitTestElementKind.TestStuff:
return testPart.IsTestContribution;
default:
throw new ArgumentOutOfRangeException("kind");
}
});
}
public bool IsElementOfKind(UnitTestElement element, UnitTestElementKind kind)
{
if (element == null)
throw new ArgumentNullException("element");
GallioTestElement gallioTestElement = element as GallioTestElement;
if (gallioTestElement == null)
return false;
switch (kind)
{
case UnitTestElementKind.Unknown:
case UnitTestElementKind.TestStuff:
return false;
case UnitTestElementKind.Test:
return gallioTestElement.IsTestCase;
case UnitTestElementKind.TestContainer:
return ! gallioTestElement.IsTestCase;
default:
throw new ArgumentOutOfRangeException("kind");
}
}
#endif
private bool EvalTestPartPredicate(IDeclaredElement element, Predicate<TestPart> predicate)
{
#if RESHARPER_45_OR_NEWER
using (ReadLockCookie.Create())
#endif
{
if (!element.IsValid())
return false;
try
{
PsiReflectionPolicy reflectionPolicy = new PsiReflectionPolicy(element.GetManager());
ICodeElementInfo elementInfo = reflectionPolicy.Wrap(element);
if (elementInfo == null)
return false;
ITestDriver driver = CreateTestDriver();
IList<TestPart> testParts = driver.GetTestParts(reflectionPolicy, elementInfo);
return GenericCollectionUtils.Exists(testParts, predicate);
}
catch (Exception ex)
{
HandleEmbeddedProcessCancelledException(ex);
throw;
}
}
}
/// <summary>
/// Presents unit test.
///</summary>
public void Present(UnitTestElement element, IPresentableItem item, TreeModelNode node, PresentationState state)
{
if (element == null)
throw new ArgumentNullException("element");
if (item == null)
throw new ArgumentNullException("item");
if (node == null)
throw new ArgumentNullException("node");
if (state == null)
throw new ArgumentNullException("state");
presenter.UpdateItem(element, node, item, state);
}
/// <summary>
/// Gets instance of <see cref="T:JetBrains.ReSharper.TaskRunnerFramework.RemoteTaskRunnerInfo" />.
/// </summary>
public RemoteTaskRunnerInfo GetTaskRunnerInfo()
{
return new RemoteTaskRunnerInfo(typeof(FacadeTaskRunner));
}
/// <summary>
/// Serializes element for persistence.
/// </summary>
public string Serialize(UnitTestElement element)
{
if (element == null)
throw new ArgumentNullException("element");
return null;
}
/// <summary>
/// Deserializes element from persisted string.
/// </summary>
public UnitTestElement Deserialize(ISolution solution, string elementString)
{
if (solution == null)
throw new ArgumentNullException("solution");
if (elementString == null)
throw new ArgumentNullException("elementString");
return null;
}
/// <summary>
/// Gets task information for <see cref="T:JetBrains.ReSharper.TaskRunnerFramework.RemoteTaskRunner" /> from element.
/// </summary>
public IList<UnitTestTask> GetTaskSequence(UnitTestElement element, IList<UnitTestElement> explicitElements)
{
if (element == null)
throw new ArgumentNullException("element");
if (explicitElements == null)
throw new ArgumentNullException("explicitElements");
GallioTestElement topElement = (GallioTestElement)element;
List<UnitTestTask> tasks = new List<UnitTestTask>();
// Add the run task. Must always be first.
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateRootTask()));
// Add the test case branch.
AddTestTasksFromRootToLeaf(tasks, topElement);
// Now that we're done with the critical parts of the task tree, we can add other
// arbitrary elements. We don't care about the structure of the task tree beyond this depth.
// Add the assembly location.
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateAssemblyTaskFrom(topElement)));
if (explicitElements.Count != 0)
{
// Add explicit element markers.
foreach (GallioTestElement explicitElement in explicitElements)
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(explicitElement)));
}
else
{
// No explicit elements but we must have at least one to filter by, so we consider
// the top test explicitly selected.
tasks.Add(new UnitTestTask(null, FacadeTaskFactory.CreateExplicitTestTaskFrom(topElement)));
}
return tasks;
}
private void AddTestTasksFromRootToLeaf(List<UnitTestTask> tasks, GallioTestElement element)
{
GallioTestElement parentElement = element.Parent as GallioTestElement;
if (parentElement != null)
AddTestTasksFromRootToLeaf(tasks, parentElement);
tasks.Add(new UnitTestTask(element, FacadeTaskFactory.CreateTestTaskFrom(element)));
}
/// <summary>
/// Compares unit tests elements to determine relative sort order.
/// </summary>
public int CompareUnitTestElements(UnitTestElement x, UnitTestElement y)
{
if (x == null)
throw new ArgumentNullException("x");
if (y == null)
throw new ArgumentNullException("y");
GallioTestElement xe = (GallioTestElement)x;
GallioTestElement ye = (GallioTestElement)y;
return xe.CompareTo(ye);
}
/// <summary>
/// Obtains configuration data.
/// </summary>
public void ProfferConfiguration(TaskExecutorConfiguration configuration, UnitTestSession session)
{
}
/// <summary>
/// Gets the ID of the provider.
/// </summary>
public string ID
{
get { return ProviderId; }
}
#if RESHARPER_45_OR_NEWER
/// <summary>
/// Gets the icon to display in the Options panel or null to use the default.
/// </summary>
public Image Icon
{
get { return Resources.ProviderIcon; }
}
/// <summary>
/// Gets the name to display in the Options panel.
/// </summary>
public string Name
{
get { return Resources.ProviderName; }
}
/// <summary>
/// Gets a custom options panel control or null if none.
/// </summary>
/// <param name="solution">The solution.</param>
/// <returns>The control, or null if none.</returns>
public ProviderCustomOptionsControl GetCustomOptionsControl(ISolution solution)
{
return null;
}
#endif
/// <summary>
/// ReSharper can throw ProcessCancelledException while we are performing reflection
/// over code elements. Gallio will then often wrap the exception as a ModelException
/// which ReSharper does not expect. So we check to see whether a ProcessCancelledException
/// was wrapped up and throw it again if needed.
/// </summary>
private static void HandleEmbeddedProcessCancelledException(Exception exception)
{
do
{
if (exception is ProcessCancelledException)
throw exception;
exception = exception.InnerException;
}
while (exception != null);
}
private sealed class ConsumerAdapter : IMessageSink
{
private readonly IUnitTestProvider provider;
private readonly UnitTestElementConsumer consumer;
private readonly MessageConsumer messageConsumer;
private readonly Dictionary<string, GallioTestElement> tests = new Dictionary<string, GallioTestElement>();
private readonly List<AnnotationData> annotations = new List<AnnotationData>();
public ConsumerAdapter(IUnitTestProvider provider, UnitTestElementConsumer consumer)
{
this.provider = provider;
this.consumer = consumer;
messageConsumer = new MessageConsumer()
.Handle<TestDiscoveredMessage>(HandleTestDiscoveredMessage)
.Handle<AnnotationDiscoveredMessage>(HandleAnnotationDiscoveredMessage);
}
public ConsumerAdapter(IUnitTestProvider provider, UnitTestElementLocationConsumer consumer, IFile psiFile)
: this(provider, delegate(UnitTestElement element)
{
#if RESHARPER_31
IProjectFile projectFile = psiFile.ProjectItem;
#else
IProjectFile projectFile = psiFile.ProjectFile;
#endif
if (projectFile.IsValid)
{
UnitTestElementDisposition disposition = element.GetDisposition();
if (disposition.Locations.Count != 0 && disposition.Locations[0].ProjectFile == projectFile)
{
consumer(disposition);
}
}
})
{
}
public void Publish(Message message)
{
messageConsumer.Consume(message);
}
private void HandleTestDiscoveredMessage(TestDiscoveredMessage message)
{
GallioTestElement element;
if (!tests.TryGetValue(message.Test.Id, out element))
{
if (ShouldTestBePresented(message.Test.CodeElement))
{
GallioTestElement parentElement;
tests.TryGetValue(message.ParentTestId, out parentElement);
element = GallioTestElement.CreateFromTest(message.Test, message.Test.CodeElement, provider, parentElement);
consumer(element);
}
tests.Add(message.Test.Id, element);
}
}
private void HandleAnnotationDiscoveredMessage(AnnotationDiscoveredMessage message)
{
annotations.Add(message.Annotation);
}
public ProjectFileState CreateProjectFileState()
{
return annotations.Count != 0
? ProjectFileState.CreateFromAnnotations(annotations)
: null;
}
/// <summary>
/// ReSharper does not know how to present tests with a granularity any
/// larger than a type.
/// </summary>
/// <remarks>
/// <para>
/// The tree it shows to users in such cases is
/// not very helpful because it appears that the root test is a child of the
/// project that resides in the root namespace. So we filter out
/// certain kinds of tests from view.
/// </para>
/// </remarks>
private static bool ShouldTestBePresented(ICodeElementInfo codeElement)
{
if (codeElement == null)
return false;
switch (codeElement.Kind)
{
case CodeElementKind.Assembly:
case CodeElementKind.Namespace:
return false;
default:
return true;
}
}
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.World.Estate
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "XEstate")]
public class XEstateModule : ISharedRegionModule
{
protected EstateConnector m_EstateConnector;
protected bool m_InInfoUpdate = false;
protected List<Scene> m_Scenes = new List<Scene>();
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public bool InInfoUpdate
{
get { return m_InInfoUpdate; }
set { m_InInfoUpdate = value; }
}
public string Name
{
get { return "EstateModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public List<Scene> Scenes
{
get { return m_Scenes; }
}
public void AddRegion(Scene scene)
{
lock (m_Scenes)
m_Scenes.Add(scene);
scene.EventManager.OnNewClient += OnNewClient;
}
public void Close()
{
}
public void Initialise(IConfigSource config)
{
int port = 0;
IConfig estateConfig = config.Configs["Estate"];
if (estateConfig != null)
{
port = estateConfig.GetInt("Port", 0);
}
m_EstateConnector = new EstateConnector(this);
// Instantiate the request handler
IHttpServer server = MainServer.GetHttpServer((uint)port);
server.AddStreamHandler(new EstateRequestHandler(this));
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
IEstateModule em = scene.RequestModuleInterface<IEstateModule>();
em.OnRegionInfoChange += OnRegionInfoChange;
em.OnEstateInfoChange += OnEstateInfoChange;
em.OnEstateMessage += OnEstateMessage;
}
public void RemoveRegion(Scene scene)
{
scene.EventManager.OnNewClient -= OnNewClient;
lock (m_Scenes)
m_Scenes.Remove(scene);
}
private Scene FindScene(UUID RegionID)
{
foreach (Scene s in Scenes)
{
if (s.RegionInfo.RegionID == RegionID)
return s;
}
return null;
}
private void OnEstateInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateEstate(s.RegionInfo.EstateSettings.EstateID);
}
private void OnEstateMessage(UUID RegionID, UUID FromID, string FromName, string Message)
{
Scene senderScenes = FindScene(RegionID);
if (senderScenes == null)
return;
uint estateID = senderScenes.RegionInfo.EstateSettings.EstateID;
foreach (Scene s in Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == estateID)
{
IDialogModule dm = s.RequestModuleInterface<IDialogModule>();
if (dm != null)
{
dm.SendNotificationToUsersInRegion(FromID, FromName,
Message);
}
}
}
if (!m_InInfoUpdate)
m_EstateConnector.SendEstateMessage(estateID, FromID, FromName, Message);
}
private void OnEstateTeleportAllUsersHomeRequest(IClientAPI client, UUID invoice, UUID senderID)
{
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s == scene)
continue; // Already handles by estate module
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
scene.ForEachScenePresence(delegate(ScenePresence p)
{
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient);
}
});
}
m_EstateConnector.SendTeleportHomeAllUsers(estateID);
}
private void OnEstateTeleportOneUserHomeRequest(IClientAPI client, UUID invoice, UUID senderID, UUID prey)
{
if (prey == UUID.Zero)
return;
if (!(client.Scene is Scene))
return;
Scene scene = (Scene)client.Scene;
uint estateID = scene.RegionInfo.EstateSettings.EstateID;
if (!scene.Permissions.CanIssueEstateCommand(client.AgentId, false))
return;
foreach (Scene s in Scenes)
{
if (s == scene)
continue; // Already handles by estate module
if (s.RegionInfo.EstateSettings.EstateID != estateID)
continue;
ScenePresence p = scene.GetScenePresence(prey);
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
scene.TeleportClientHome(prey, p.ControllingClient);
}
}
m_EstateConnector.SendTeleportHomeOneUser(estateID, prey);
}
private void OnNewClient(IClientAPI client)
{
client.OnEstateTeleportOneUserHomeRequest += OnEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += OnEstateTeleportAllUsersHomeRequest;
}
private void OnRegionInfoChange(UUID RegionID)
{
Scene s = FindScene(RegionID);
if (s == null)
return;
if (!m_InInfoUpdate)
m_EstateConnector.SendUpdateCovenant(s.RegionInfo.EstateSettings.EstateID, s.RegionInfo.RegionSettings.Covenant);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="ImageBrush.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.KnownBoxes;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.ComponentModel.Design.Serialization;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Media3D;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Windows.Media.Imaging;
using System.Windows.Markup;
using System.Windows.Media.Converters;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media
{
sealed partial class ImageBrush : TileBrush
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new ImageBrush Clone()
{
return (ImageBrush)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new ImageBrush CloneCurrentValue()
{
return (ImageBrush)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void ImageSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// The first change to the default value of a mutable collection property (e.g. GeometryGroup.Children)
// will promote the property value from a default value to a local value. This is technically a sub-property
// change because the collection was changed and not a new collection set (GeometryGroup.Children.
// Add versus GeometryGroup.Children = myNewChildrenCollection). However, we never marshalled
// the default value to the compositor. If the property changes from a default value, the new local value
// needs to be marshalled to the compositor. We detect this scenario with the second condition
// e.OldValueSource != e.NewValueSource. Specifically in this scenario the OldValueSource will be
// Default and the NewValueSource will be Local.
if (e.IsASubPropertyChange &&
(e.OldValueSource == e.NewValueSource))
{
return;
}
ImageBrush target = ((ImageBrush) d);
ImageSource oldV = (ImageSource) e.OldValue;
ImageSource newV = (ImageSource) e.NewValue;
System.Windows.Threading.Dispatcher dispatcher = target.Dispatcher;
if (dispatcher != null)
{
DUCE.IResource targetResource = (DUCE.IResource)target;
using (CompositionEngineLock.Acquire())
{
int channelCount = targetResource.GetChannelCount();
for (int channelIndex = 0; channelIndex < channelCount; channelIndex++)
{
DUCE.Channel channel = targetResource.GetChannel(channelIndex);
Debug.Assert(!channel.IsOutOfBandChannel);
Debug.Assert(!targetResource.GetHandle(channel).IsNull);
target.ReleaseResource(oldV,channel);
target.AddRefResource(newV,channel);
}
}
}
target.PropertyChanged(ImageSourceProperty);
}
#region Public Properties
/// <summary>
/// ImageSource - ImageSource. Default value is null.
/// </summary>
public ImageSource ImageSource
{
get
{
return (ImageSource) GetValue(ImageSourceProperty);
}
set
{
SetValueInternal(ImageSourceProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new ImageBrush();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Transform vTransform = Transform;
Transform vRelativeTransform = RelativeTransform;
ImageSource vImageSource = ImageSource;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hTransform;
if (vTransform == null ||
Object.ReferenceEquals(vTransform, Transform.Identity)
)
{
hTransform = DUCE.ResourceHandle.Null;
}
else
{
hTransform = ((DUCE.IResource)vTransform).GetHandle(channel);
}
DUCE.ResourceHandle hRelativeTransform;
if (vRelativeTransform == null ||
Object.ReferenceEquals(vRelativeTransform, Transform.Identity)
)
{
hRelativeTransform = DUCE.ResourceHandle.Null;
}
else
{
hRelativeTransform = ((DUCE.IResource)vRelativeTransform).GetHandle(channel);
}
DUCE.ResourceHandle hImageSource = vImageSource != null ? ((DUCE.IResource)vImageSource).GetHandle(channel) : DUCE.ResourceHandle.Null;
// Obtain handles for animated properties
DUCE.ResourceHandle hOpacityAnimations = GetAnimationResourceHandle(OpacityProperty, channel);
DUCE.ResourceHandle hViewportAnimations = GetAnimationResourceHandle(ViewportProperty, channel);
DUCE.ResourceHandle hViewboxAnimations = GetAnimationResourceHandle(ViewboxProperty, channel);
// Pack & send command packet
DUCE.MILCMD_IMAGEBRUSH data;
unsafe
{
data.Type = MILCMD.MilCmdImageBrush;
data.Handle = _duceResource.GetHandle(channel);
if (hOpacityAnimations.IsNull)
{
data.Opacity = Opacity;
}
data.hOpacityAnimations = hOpacityAnimations;
data.hTransform = hTransform;
data.hRelativeTransform = hRelativeTransform;
data.ViewportUnits = ViewportUnits;
data.ViewboxUnits = ViewboxUnits;
if (hViewportAnimations.IsNull)
{
data.Viewport = Viewport;
}
data.hViewportAnimations = hViewportAnimations;
if (hViewboxAnimations.IsNull)
{
data.Viewbox = Viewbox;
}
data.hViewboxAnimations = hViewboxAnimations;
data.Stretch = Stretch;
data.TileMode = TileMode;
data.AlignmentX = AlignmentX;
data.AlignmentY = AlignmentY;
data.CachingHint = (CachingHint)GetValue(RenderOptions.CachingHintProperty);
data.CacheInvalidationThresholdMinimum = (double)GetValue(RenderOptions.CacheInvalidationThresholdMinimumProperty);
data.CacheInvalidationThresholdMaximum = (double)GetValue(RenderOptions.CacheInvalidationThresholdMaximumProperty);
data.hImageSource = hImageSource;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_IMAGEBRUSH));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_IMAGEBRUSH))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel);
Transform vRelativeTransform = RelativeTransform;
if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).AddRefOnChannel(channel);
ImageSource vImageSource = ImageSource;
if (vImageSource != null) ((DUCE.IResource)vImageSource).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel);
Transform vRelativeTransform = RelativeTransform;
if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).ReleaseOnChannel(channel);
ImageSource vImageSource = ImageSource;
if (vImageSource != null) ((DUCE.IResource)vImageSource).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
//
// This property finds the correct initial size for the _effectiveValues store on the
// current DependencyObject as a performance optimization
//
// This includes:
// ImageSource
//
internal override int EffectiveValuesInitialSize
{
get
{
return 1;
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the ImageBrush.ImageSource property.
/// </summary>
public static readonly DependencyProperty ImageSourceProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static ImageBrush()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
// Initializations
Type typeofThis = typeof(ImageBrush);
ImageSourceProperty =
RegisterProperty("ImageSource",
typeof(ImageSource),
typeofThis,
null,
new PropertyChangedCallback(ImageSourcePropertyChanged),
null,
/* isIndependentlyAnimated = */ false,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Xml;
using System.Text.RegularExpressions;
namespace Microsoft.Build.BuildEngine.Shared
{
/// <summary>
/// This class contains utility methods for XML manipulation.
/// </summary>
/// <owner>SumedhK</owner>
static internal class XmlUtilities
{
/// <summary>
/// This method renames an XML element. Well, actually you can't directly
/// rename an XML element using the DOM, so what you have to do is create
/// a brand new XML element with the new name, and copy over all the attributes
/// and children. This method returns the new XML element object.
/// </summary>
/// <param name="oldElement"></param>
/// <param name="newElementName"></param>
/// <param name="xmlNamespace">Can be null if global namespace.</param>
/// <returns>new/renamed element</returns>
/// <owner>RGoel</owner>
internal static XmlElement RenameXmlElement(XmlElement oldElement, string newElementName, string xmlNamespace)
{
XmlElement newElement = (xmlNamespace == null)
? oldElement.OwnerDocument.CreateElement(newElementName)
: oldElement.OwnerDocument.CreateElement(newElementName, xmlNamespace);
// Copy over all the attributes.
foreach (XmlAttribute oldAttribute in oldElement.Attributes)
{
XmlAttribute newAttribute = (XmlAttribute)oldAttribute.CloneNode(true);
newElement.SetAttributeNode(newAttribute);
}
// Copy over all the child nodes.
foreach (XmlNode oldChildNode in oldElement.ChildNodes)
{
XmlNode newChildNode = oldChildNode.CloneNode(true);
newElement.AppendChild(newChildNode);
}
if (oldElement.ParentNode != null)
{
// Add the new element in the same place the old element was.
oldElement.ParentNode.ReplaceChild(newElement, oldElement);
}
return newElement;
}
/// <summary>
/// Retrieves the file that the given XML node was defined in. If the XML node is purely in-memory, it may not have a file
/// associated with it, in which case the default file is returned.
/// </summary>
/// <owner>SumedhK</owner>
/// <param name="node"></param>
/// <param name="defaultFile">Can be empty string.</param>
/// <returns>The path to the XML node's file, or the default file.</returns>
internal static string GetXmlNodeFile(XmlNode node, string defaultFile)
{
ErrorUtilities.VerifyThrow(node != null, "Need XML node.");
ErrorUtilities.VerifyThrow(defaultFile != null, "Must specify the default file to use.");
string file = defaultFile;
// NOTE: the XML node may not have a filename if it's purely an in-memory node
if ((node.OwnerDocument.BaseURI != null) && (node.OwnerDocument.BaseURI.Length > 0))
{
file = new Uri(node.OwnerDocument.BaseURI).LocalPath;
}
return file;
}
/// <summary>
/// An XML document can have many root nodes, but usually we want the single root
/// element. Callers can test each root node in turn with this method, until it returns
/// true.
/// </summary>
/// <param name="node">Candidate root node</param>
/// <returns>true if node is the root element</returns>
/// <owner>danmose</owner>
internal static bool IsXmlRootElement(XmlNode node)
{
// "A Document node can have the following child node types: XmlDeclaration,
// Element (maximum of one), ProcessingInstruction, Comment, and DocumentType."
return (
(node.NodeType != XmlNodeType.Comment) &&
(node.NodeType != XmlNodeType.Whitespace) &&
(node.NodeType != XmlNodeType.XmlDeclaration) &&
(node.NodeType != XmlNodeType.ProcessingInstruction) &&
(node.NodeType != XmlNodeType.DocumentType)
);
}
/// <summary>
/// Verifies that a name is valid for the name of an item, property, or piece of metadata.
/// If it isn't, throws an ArgumentException indicating the invalid character.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// </remarks>
/// <throws>ArgumentException</throws>
/// <param name="name">name to validate</param>
/// <owner>danmose</owner>
internal static void VerifyThrowValidElementName(string name)
{
int firstInvalidCharLocation = LocateFirstInvalidElementNameCharacter(name);
if (-1 != firstInvalidCharLocation)
{
ErrorUtilities.VerifyThrowArgument(false, "NameInvalid", name, name[firstInvalidCharLocation]);
}
}
/// <summary>
/// Verifies that a name is valid for the name of an item, property, or piece of metadata.
/// If it isn't, throws an InvalidProjectException indicating the invalid character.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// </remarks>
internal static void VerifyThrowProjectValidElementName(XmlElement element)
{
string name = element.Name;
int firstInvalidCharLocation = LocateFirstInvalidElementNameCharacter(name);
if (-1 != firstInvalidCharLocation)
{
ProjectErrorUtilities.ThrowInvalidProject(element, "NameInvalid", name, name[firstInvalidCharLocation]);
}
}
/// <summary>
/// Indicates if the given name is valid as the name of an item, property or metadatum.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than those of the XML Standard.
/// </remarks>
/// <owner>SumedhK</owner>
/// <param name="name"></param>
/// <returns>true, if name is valid</returns>
internal static bool IsValidElementName(string name)
{
return (LocateFirstInvalidElementNameCharacter(name) == -1);
}
/// <summary>
/// Finds the location of the first invalid character, if any, in the name of an
/// item, property, or piece of metadata. Returns the location of the first invalid character, or -1 if there are none.
/// Valid names must match this pattern: [A-Za-z_][A-Za-z_0-9\-.]*
/// Note, this is a subset of all possible valid XmlElement names: we use a subset because we also
/// have to match this same set in our regular expressions, and allowing all valid XmlElement name
/// characters in a regular expression would be impractical.
/// </summary>
/// <remarks>
/// Note that our restrictions are more stringent than the XML Standard's restrictions.
/// PERF: This method has to be as fast as possible, as it's called when any item, property, or piece
/// of metadata is constructed.
/// </remarks>
internal static int LocateFirstInvalidElementNameCharacter(string name)
{
// Check the first character.
// Try capital letters first.
// Optimize slightly for success.
if (!IsValidInitialElementNameCharacter(name[0]))
{
return 0;
}
// Check subsequent characters.
// Try lower case letters first.
// Optimize slightly for success.
for (int i = 1; i < name.Length; i++)
{
if (!IsValidSubsequentElementNameCharacter(name[i]))
{
return i;
}
}
// If we got here, the name was valid.
return -1;
}
/// <summary>
/// Load the xml file using XMLTextReader and locate the element and attribute specified and then
/// return the value. This is a quick way to peek at the xml file whithout having the go through
/// the XMLDocument (MSDN article (Chapter 9 - Improving XML Performance)).
/// </summary>
internal static string GetAttributeValueForElementFromFile
(
string projectFileName,
string elementName,
string attributeName
)
{
string attributeValue = null;
try
{
using (XmlTextReader xmlReader = new XmlTextReader(projectFileName))
{
xmlReader.DtdProcessing = DtdProcessing.Ignore;
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (String.Compare(xmlReader.Name, elementName, StringComparison.OrdinalIgnoreCase) == 0)
{
if (xmlReader.HasAttributes)
{
for (int i = 0; i < xmlReader.AttributeCount; i++)
{
xmlReader.MoveToAttribute(i);
if (String.Compare(xmlReader.Name, attributeName, StringComparison.OrdinalIgnoreCase) == 0)
{
attributeValue = xmlReader.Value;
break;
}
}
}
// if we have already located the element then we are done
break;
}
}
}
}
}
catch(XmlException)
{
// Ignore any XML exceptions as it will be caught later on
}
catch (System.IO.IOException)
{
// Ignore any IO exceptions as it will be caught later on
}
return attributeValue;
}
internal static bool IsValidInitialElementNameCharacter(char c)
{
return (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c == '_');
}
internal static bool IsValidSubsequentElementNameCharacter(char c)
{
return (c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c == '_') ||
(c == '-');
}
}
}
| |
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Orleans.Runtime
{
/// <summary>
/// SafeTimerBase - an internal base class for implementing sync and async timers in Orleans.
///
/// </summary>
internal class SafeTimerBase : IDisposable
{
private const string asyncTimerName ="Orleans.Runtime.asynTask.SafeTimerBase";
private const string syncTimerName = "Orleans.Runtime.sync.SafeTimerBase";
private Timer timer;
private Func<object, Task> asynTaskCallback;
private TimerCallback syncCallbackFunc;
private TimeSpan dueTime;
private TimeSpan timerFrequency;
private bool timerStarted;
private DateTime previousTickTime;
private int totalNumTicks;
private ILogger logger;
internal SafeTimerBase(ILogger logger, Func<object, Task> asynTaskCallback, object state)
{
Init(logger, asynTaskCallback, null, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(ILogger logger, Func<object, Task> asynTaskCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(logger, asynTaskCallback, null, state, dueTime, period);
Start(dueTime, period);
}
internal SafeTimerBase(ILogger logger, TimerCallback syncCallback, object state)
{
Init(logger, null, syncCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
internal SafeTimerBase(ILogger logger, TimerCallback syncCallback, object state, TimeSpan dueTime, TimeSpan period)
{
Init(logger, null, syncCallback, state, dueTime, period);
Start(dueTime, period);
}
public void Start(TimeSpan due, TimeSpan period)
{
if (timerStarted) throw new InvalidOperationException(String.Format("Calling start on timer {0} is not allowed, since it was already created in a started mode with specified due.", GetFullName()));
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
timerFrequency = period;
dueTime = due;
timerStarted = true;
previousTickTime = DateTime.UtcNow;
timer.Change(due, Constants.INFINITE_TIMESPAN);
}
private void Init(ILogger logger, Func<object, Task> asynCallback, TimerCallback synCallback, object state, TimeSpan due, TimeSpan period)
{
if (synCallback == null && asynCallback == null) throw new ArgumentNullException("synCallback", "Cannot use null for both sync and asyncTask timer callbacks.");
int numNonNulls = (asynCallback != null ? 1 : 0) + (synCallback != null ? 1 : 0);
if (numNonNulls > 1) throw new ArgumentNullException("synCallback", "Cannot define more than one timer callbacks. Pick one.");
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, "Cannot use TimeSpan.Zero for timer period");
this.asynTaskCallback = asynCallback;
syncCallbackFunc = synCallback;
timerFrequency = period;
this.dueTime = due;
totalNumTicks = 0;
this.logger = logger;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerChanging, "Creating timer {0} with dueTime={1} period={2}", GetFullName(), due, period);
timer = new Timer(HandleTimerCallback, state, Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
}
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Maybe called by finalizer thread with disposing=false. As per guidelines, in such a case do not touch other objects.
// Dispose() may be called multiple times
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
DisposeTimer();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
internal void DisposeTimer()
{
if (timer != null)
{
try
{
var t = timer;
timer = null;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerDisposing, "Disposing timer {0}", GetFullName());
t.Dispose();
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Ignored error disposing timer {0}", GetFullName()), exc);
}
}
}
#endregion
private string GetFullName()
{
// the type information is really useless and just too long.
if (syncCallbackFunc != null)
return syncTimerName;
if (asynTaskCallback != null)
return asyncTimerName;
throw new InvalidOperationException("invalid SafeTimerBase state");
}
public bool CheckTimerFreeze(DateTime lastCheckTime, Func<string> callerName)
{
return CheckTimerDelay(previousTickTime, totalNumTicks,
dueTime, timerFrequency, logger, () => String.Format("{0}.{1}", GetFullName(), callerName()), ErrorCode.Timer_SafeTimerIsNotTicking, true);
}
public static bool CheckTimerDelay(DateTime previousTickTime, int totalNumTicks,
TimeSpan dueTime, TimeSpan timerFrequency, ILogger logger, Func<string> getName, ErrorCode errorCode, bool freezeCheck)
{
TimeSpan timeSinceLastTick = DateTime.UtcNow - previousTickTime;
TimeSpan exceptedTimeToNexTick = totalNumTicks == 0 ? dueTime : timerFrequency;
TimeSpan exceptedTimeWithSlack;
if (exceptedTimeToNexTick >= TimeSpan.FromSeconds(6))
{
exceptedTimeWithSlack = exceptedTimeToNexTick + TimeSpan.FromSeconds(3);
}
else
{
exceptedTimeWithSlack = exceptedTimeToNexTick.Multiply(1.5);
}
if (timeSinceLastTick <= exceptedTimeWithSlack) return true;
// did not tick in the last period.
var errMsg = String.Format("{0}{1} did not fire on time. Last fired at {2}, {3} since previous fire, should have fired after {4}.",
freezeCheck ? "Watchdog Freeze Alert: " : "-", // 0
getName == null ? "" : getName(), // 1
LogFormatter.PrintDate(previousTickTime), // 2
timeSinceLastTick, // 3
exceptedTimeToNexTick); // 4
if(freezeCheck)
{
logger.Error(errorCode, errMsg);
}else
{
logger.Warn(errorCode, errMsg);
}
return false;
}
/// <summary>
/// Changes the start time and the interval between method invocations for a timer, using TimeSpan values to measure time intervals.
/// </summary>
/// <param name="newDueTime">A TimeSpan representing the amount of time to delay before invoking the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to prevent the timer from restarting. Specify zero (0) to restart the timer immediately.</param>
/// <param name="period">The time interval between invocations of the callback method specified when the Timer was constructed. Specify negative one (-1) milliseconds to disable periodic signaling.</param>
/// <returns><c>true</c> if the timer was successfully updated; otherwise, <c>false</c>.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private bool Change(TimeSpan newDueTime, TimeSpan period)
{
if (period == TimeSpan.Zero) throw new ArgumentOutOfRangeException("period", period, string.Format("Cannot use TimeSpan.Zero for timer {0} period", GetFullName()));
if (timer == null) return false;
timerFrequency = period;
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.TimerChanging, "Changing timer {0} to dueTime={1} period={2}", GetFullName(), newDueTime, period);
try
{
// Queue first new timer tick
return timer.Change(newDueTime, Constants.INFINITE_TIMESPAN);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerChangeError,
string.Format("Error changing timer period - timer {0} not changed", GetFullName()), exc);
return false;
}
}
private void HandleTimerCallback(object state)
{
if (timer == null) return;
if (asynTaskCallback != null)
{
HandleAsyncTaskTimerCallback(state);
}
else
{
HandleSyncTimerCallback(state);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void HandleSyncTimerCallback(object state)
{
try
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerBeforeCallback, "About to make sync timer callback for timer {0}", GetFullName());
syncCallbackFunc(state);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed sync timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during sync timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
private async void HandleAsyncTaskTimerCallback(object state)
{
if (timer == null) return;
// There is a subtle race/issue here w.r.t unobserved promises.
// It may happen than the asyncCallbackFunc will resolve some promises on which the higher level application code is depends upon
// and this promise's await or CW will fire before the below code (after await or Finally) even runs.
// In the unit test case this may lead to the situation where unit test has finished, but p1 or p2 or p3 have not been observed yet.
// To properly fix this we may use a mutex/monitor to delay execution of asyncCallbackFunc until all CWs and Finally in the code below were scheduled
// (not until CW lambda was run, but just until CW function itself executed).
// This however will relay on scheduler executing these in separate threads to prevent deadlock, so needs to be done carefully.
// In particular, need to make sure we execute asyncCallbackFunc in another thread (so use StartNew instead of ExecuteWithSafeTryCatch).
try
{
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerBeforeCallback, "About to make async task timer callback for timer {0}", GetFullName());
await asynTaskCallback(state);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerAfterCallback, "Completed async task timer callback for timer {0}", GetFullName());
}
catch (Exception exc)
{
logger.Warn(ErrorCode.TimerCallbackError, string.Format("Ignored exception {0} during async task timer callback {1}", exc.Message, GetFullName()), exc);
}
finally
{
previousTickTime = DateTime.UtcNow;
// Queue next timer callback
QueueNextTimerTick();
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private void QueueNextTimerTick()
{
try
{
if (timer == null) return;
totalNumTicks++;
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerChanging, "About to QueueNextTimerTick for timer {0}", GetFullName());
if (timerFrequency == Constants.INFINITE_TIMESPAN)
{
//timer.Change(Constants.INFINITE_TIMESPAN, Constants.INFINITE_TIMESPAN);
DisposeTimer();
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerStopped, "Timer {0} is now stopped and disposed", GetFullName());
}
else
{
timer.Change(timerFrequency, Constants.INFINITE_TIMESPAN);
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.TimerNextTick, "Queued next tick for timer {0} in {1}", GetFullName(), timerFrequency);
}
}
catch (ObjectDisposedException ode)
{
logger.Warn(ErrorCode.TimerDisposeError,
string.Format("Timer {0} already disposed - will not queue next timer tick", GetFullName()), ode);
}
catch (Exception exc)
{
logger.Error(ErrorCode.TimerQueueTickError,
string.Format("Error queueing next timer tick - WARNING: timer {0} is now stopped", GetFullName()), exc);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Torque
// Copyright GarageGames, LLC 2011
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Placeholder projectile and explosion with required sounds, debris, and
// particle datablocks. These datablocks existed in now removed scripts, but
// were used within some that remain: see Lurker.cs, Ryder.cs, ProxMine.cs
//
// These effects should be made more generic or new fx created for unique usage.
//
// I've removed all effects that are not required for the current weapons. On
// reflection I really went overboard when originally making these effects!
// ----------------------------------------------------------------------------
$GrenadeUpVectorOffset = "0 0 1";
// ---------------------------------------------------------------------------
// Sounds
// ---------------------------------------------------------------------------
datablock SFXProfile(GrenadeExplosionSound)
{
filename = "art/sound/weapons/GRENADELAND.wav";
description = AudioDefault3d;
preload = true;
};
datablock SFXProfile(GrenadeLauncherExplosionSound)
{
filename = "art/sound/weapons/Crossbow_explosion";
description = AudioDefault3d;
preload = true;
};
// ----------------------------------------------------------------------------
// Lights for the projectile(s)
// ----------------------------------------------------------------------------
datablock LightDescription(GrenadeLauncherLightDesc)
{
range = 1.0;
color = "1 1 1";
brightness = 2.0;
animationType = PulseLightAnim;
animationPeriod = 0.25;
//flareType = SimpleLightFlare0;
};
// ---------------------------------------------------------------------------
// Debris
// ---------------------------------------------------------------------------
datablock ParticleData(GrenadeDebrisFireParticle)
{
textureName = "art/particles/impact";
dragCoeffiecient = 0;
gravityCoefficient = -1.00366;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 300;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -280.0;
spinRandomMax = 280.0;
colors[0] = "1 0.590551 0.188976 0.0944882";
colors[1] = "0.677165 0.590551 0.511811 0.496063";
colors[2] = "0.645669 0.645669 0.645669 0";
sizes[0] = 0.2;
sizes[1] = 0.5;
sizes[2] = 0.2;
times[0] = 0.0;
times[1] = 0.494118;
times[2] = 1.0;
animTexName = "art/particles/impact";
colors[3] = "1 1 1 0.407";
sizes[3] = "0.5";
};
datablock ParticleEmitterData(GrenadeDebrisFireEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 0;
ejectionVelocity = 0;
velocityVariance = 0;
thetaMin = 0.0;
thetaMax = 25;
phiReferenceVel = 0;
phiVariance = 360;
ejectionoffset = 0.3;
particles = "GrenadeDebrisFireParticle";
orientParticles = "1";
blendStyle = "NORMAL";
};
datablock DebrisData(GrenadeDebris)
{
shapeFile = "art/shapes/weapons/Grenade/grenadeDebris.dae";
emitters[0] = GrenadeDebrisFireEmitter;
elasticity = 0.4;
friction = 0.25;
numBounces = 3;
bounceVariance = 1;
explodeOnMaxBounce = false;
staticOnMaxBounce = false;
snapOnMaxBounce = false;
minSpinSpeed = 200;
maxSpinSpeed = 600;
render2D = false;
lifetime = 4;
lifetimeVariance = 1.5;
velocity = 15;
velocityVariance = 5;
fade = true;
useRadiusMass = true;
baseRadius = 0.3;
gravModifier = 1.0;
terminalVelocity = 20;
ignoreWater = false;
};
// ----------------------------------------------------------------------------
// Splash effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeSplashMist)
{
dragCoefficient = 1.0;
windCoefficient = 2.0;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 600;
lifetimeVarianceMS = 100;
useInvAlpha = false;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
spinSpeed = 1;
textureName = "art/particles/smoke";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashMistEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 3.0;
velocityVariance = 2.0;
ejectionOffset = 0.15;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvance = false;
lifetimeMS = 250;
particles = "GrenadeSplashMist";
};
datablock ParticleData(GrenadeSplashParticle)
{
dragCoefficient = 1;
windCoefficient = 0.9;
gravityCoefficient = 0.3;
inheritedVelFactor = 0.2;
constantAcceleration = -1.4;
lifetimeMS = 600;
lifetimeVarianceMS = 200;
textureName = "art/particles/droplet";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.25;
sizes[2] = 0.25;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashEmitter)
{
ejectionPeriodMS = 4;
periodVarianceMS = 0;
ejectionVelocity = 7.3;
velocityVariance = 2.0;
ejectionOffset = 0.0;
thetaMin = 30;
thetaMax = 80;
phiReferenceVel = 00;
phiVariance = 360;
overrideAdvance = false;
orientParticles = true;
orientOnVelocity = true;
lifetimeMS = 100;
particles = "GrenadeSplashParticle";
};
datablock ParticleData(GrenadeSplashRingParticle)
{
textureName = "art/particles/wake";
dragCoefficient = 0.0;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 200;
windCoefficient = 0.0;
useInvAlpha = 1;
spinRandomMin = 30.0;
spinRandomMax = 30.0;
spinSpeed = 1;
animateTexture = true;
framesPerSec = 1;
animTexTiling = "2 1";
animTexFrames = "0 1";
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.5";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 4.0;
sizes[2] = 8.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeSplashRingEmitter)
{
lifetimeMS = "100";
ejectionPeriodMS = 200;
periodVarianceMS = 10;
ejectionVelocity = 0;
velocityVariance = 0;
ejectionOffset = 0;
thetaMin = 89;
thetaMax = 90;
phiReferenceVel = 0;
phiVariance = 1;
alignParticles = 1;
alignDirection = "0 0 1";
particles = "GrenadeSplashRingParticle";
};
datablock SplashData(GrenadeSplash)
{
// SplashData doesn't have a render function in the source,
// so everything but the emitter array is useless here.
emitter[0] = GrenadeSplashEmitter;
emitter[1] = GrenadeSplashMistEmitter;
emitter[2] = GrenadeSplashRingEmitter;
//numSegments = 15;
//ejectionFreq = 15;
//ejectionAngle = 40;
//ringLifetime = 0.5;
//lifetimeMS = 300;
//velocity = 4.0;
//startRadius = 0.0;
//acceleration = -3.0;
//texWrap = 5.0;
//texture = "art/images/particles//splash";
//colors[0] = "0.7 0.8 1.0 0.0";
//colors[1] = "0.7 0.8 1.0 0.3";
//colors[2] = "0.7 0.8 1.0 0.7";
//colors[3] = "0.7 0.8 1.0 0.0";
//times[0] = 0.0;
//times[1] = 0.4;
//times[2] = 0.8;
//times[3] = 1.0;
};
// ----------------------------------------------------------------------------
// Explosion Particle effects
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeExpFire)
{
textureName = "art/particles/fireball.png";
dragCoeffiecient = 0;
windCoeffiecient = 0.5;
gravityCoefficient = -1;
inheritedVelFactor = 0;
constantAcceleration = 0;
lifetimeMS = 1200;//3000;
lifetimeVarianceMS = 100;//200;
useInvAlpha = false;
spinRandomMin = 0;
spinRandomMax = 1;
spinSpeed = 1;
colors[0] = "0.886275 0.854902 0.733333 0.795276";
colors[1] = "0.356863 0.34902 0.321569 0.266";
colors[2] = "0.0235294 0.0235294 0.0235294 0.207";
sizes[0] = 1;//2;
sizes[1] = 5;
sizes[2] = 7;//0.5;
times[0] = 0.0;
times[1] = 0.25;
times[2] = 0.5;
animTexName = "art/particles/fireball.png";
times[3] = "1";
dragCoefficient = "1.99902";
sizes[3] = "10";
colors[3] = "0 0 0 0";
};
datablock ParticleEmitterData(GrenadeExpFireEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 5;//0;
ejectionVelocity = 1;//1.0;
velocityVariance = 0;//0.5;
thetaMin = 0.0;
thetaMax = 45;
lifetimeMS = 250;
particles = "GrenadeExpFire";
blendStyle = "ADDITIVE";
};
datablock ParticleData(GrenadeExpDust)
{
textureName = "art/particles/smoke.png";
dragCoefficient = 0.498534;
gravityCoefficient = 0;
inheritedVelFactor = 1;
constantAcceleration = 0.0;
lifetimeMS = 2000;
lifetimeVarianceMS = 250;
useInvAlpha = 0;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 90.0;
colors[0] = "0.992126 0.992126 0.992126 0.96063";
colors[1] = "0.11811 0.11811 0.11811 0.929134";
colors[2] = "0.00392157 0.00392157 0.00392157 0.362205";
sizes[0] = 1.59922;
sizes[1] = 4.99603;
sizes[2] = 9.99817;
times[0] = 0.0;
times[1] = 0.494118;
times[2] = 1.0;
animTexName = "art/particles/smoke.png";
colors[3] = "0.996078 0.996078 0.996078 0";
sizes[3] = "15";
};
datablock ParticleEmitterData(GrenadeExpDustEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 8;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = 0;
lifetimeMS = 2000;
particles = "GrenadeExpDust";
blendStyle = "NORMAL";
};
datablock ParticleData(GrenadeExpSpark)
{
textureName = "art/particles/Sparkparticle";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.4 0.3 1";
colors[1] = "0.6 0.4 0.3 1";
colors[2] = "1.0 0.4 0.3 0";
sizes[0] = 0.5;
sizes[1] = 0.75;
sizes[2] = 1;
times[0] = 0;
times[1] = 0.5;
times[2] = 1;
};
datablock ParticleEmitterData(GrenadeExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 20;
velocityVariance = 10;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 120;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSpark";
};
datablock ParticleData(GrenadeExpSparks)
{
textureName = "art/particles/droplet";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 350;
colors[0] = "0.6 0.4 0.3 1.0";
colors[1] = "0.6 0.4 0.3 0.6";
colors[2] = "1.0 0.4 0.3 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeExpSparksEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GrenadeExpSparks";
};
datablock ParticleData(GrenadeExpSmoke)
{
textureName = "art/particles/smoke";
dragCoeffiecient = 0;
gravityCoefficient = -0.40293;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 800;
lifetimeVarianceMS = 299;
useInvAlpha = true;
spinSpeed = 1;
spinRandomMin = -80.0;
spinRandomMax = 0;
colors[0] = "0.8 0.8 0.8 0.4";
colors[1] = "0.5 0.5 0.5 0.5";
colors[2] = "0.75 0.75 0.75 0";
sizes[0] = 4.49857;
sizes[1] = 7.49863;
sizes[2] = 11.2495;
times[0] = 0;
times[1] = 0.498039;
times[2] = 1;
animTexName = "art/particles/smoke";
times[3] = "1";
};
datablock ParticleEmitterData(GrenadeExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 5;
ejectionVelocity = 2.4;
velocityVariance = 1.2;
thetaMin = 0.0;
thetaMax = 180.0;
ejectionOffset = 1;
particles = "GrenadeExpSmoke";
blendStyle = "NORMAL";
};
// ----------------------------------------------------------------------------
// Dry/Air Explosion Objects
// ----------------------------------------------------------------------------
datablock ExplosionData(GrenadeExplosion)
{
soundProfile = GrenadeExplosionSound;
lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal
// Volume particles
particleEmitter = GrenadeExpFireEmitter;
particleDensity = 75;
particleRadius = 2.25;
// Point emission
emitter[0] = GrenadeExpDustEmitter;
emitter[1] = GrenadeExpSparksEmitter;
emitter[2] = GrenadeExpSmokeEmitter;
// Camera Shaking
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "15.0 15.0 15.0";
camShakeDuration = 1.5;
camShakeRadius = 20;
// Exploding debris
debris = GrenadeDebris;
debrisThetaMin = 10;
debrisThetaMax = 60;
debrisNum = 4;
debrisNumVariance = 2;
debrisVelocity = 25;
debrisVelocityVariance = 5;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "1.0 1.0 1.0";
lightEndColor = "1.0 1.0 1.0";
lightStartBrightness = 4.0;
lightEndBrightness = 0.0;
lightNormalOffset = 2.0;
};
// ----------------------------------------------------------------------------
// Water Explosion
// ----------------------------------------------------------------------------
datablock ParticleData(GLWaterExpDust)
{
textureName = "art/particles/steam";
dragCoefficient = 1.0;
gravityCoefficient = -0.01;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 2500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -90.0;
spinRandomMax = 500.0;
colors[0] = "0.6 0.6 1.0 0.5";
colors[1] = "0.6 0.6 1.0 0.3";
sizes[0] = 0.25;
sizes[1] = 1.5;
times[0] = 0.0;
times[1] = 1.0;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpDustEmitter)
{
ejectionPeriodMS = 1;
periodVarianceMS = 0;
ejectionVelocity = 10;
velocityVariance = 0.0;
ejectionOffset = 0.0;
thetaMin = 85;
thetaMax = 85;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
lifetimeMS = 75;
particles = "GLWaterExpDust";
};
datablock ParticleData(GLWaterExpSparks)
{
textureName = "art/particles/spark_wet";
dragCoefficient = 1;
gravityCoefficient = 0.0;
inheritedVelFactor = 0.2;
constantAcceleration = 0.0;
lifetimeMS = 500;
lifetimeVarianceMS = 250;
colors[0] = "0.6 0.6 1.0 1.0";
colors[1] = "0.6 0.6 1.0 1.0";
colors[2] = "0.6 0.6 1.0 0.0";
sizes[0] = 0.5;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSparkEmitter)
{
ejectionPeriodMS = 2;
periodVarianceMS = 0;
ejectionVelocity = 12;
velocityVariance = 6.75;
ejectionOffset = 0.0;
thetaMin = 0;
thetaMax = 60;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
orientParticles = true;
lifetimeMS = 100;
particles = "GLWaterExpSparks";
};
datablock ParticleData(GLWaterExpSmoke)
{
textureName = "art/particles/smoke";
dragCoeffiecient = 0.4;
gravityCoefficient = -0.25;
inheritedVelFactor = 0.025;
constantAcceleration = -1.1;
lifetimeMS = 1250;
lifetimeVarianceMS = 0;
useInvAlpha = false;
spinSpeed = 1;
spinRandomMin = -200.0;
spinRandomMax = 200.0;
colors[0] = "0.1 0.1 1.0 1.0";
colors[1] = "0.4 0.4 1.0 1.0";
colors[2] = "0.4 0.4 1.0 0.0";
sizes[0] = 2.0;
sizes[1] = 6.0;
sizes[2] = 2.0;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpSmokeEmitter)
{
ejectionPeriodMS = 15;
periodVarianceMS = 0;
ejectionVelocity = 6.25;
velocityVariance = 0.25;
thetaMin = 0.0;
thetaMax = 90.0;
lifetimeMS = 250;
particles = "GLWaterExpSmoke";
};
datablock ParticleData(GLWaterExpBubbles)
{
textureName = "art/particles/millsplash01";
dragCoefficient = 0.0;
gravityCoefficient = -0.05;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 250;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 0.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.2;
sizes[1] = 0.4;
sizes[2] = 0.8;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GLWaterExpBubbleEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 3.0;
velocityVariance = 0.5;
thetaMin = 0;
thetaMax = 80;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = "GLWaterExpBubbles";
};
datablock ExplosionData(GrenadeLauncherWaterExplosion)
{
//soundProfile = GLWaterExplosionSound;
emitter[0] = GLWaterExpDustEmitter;
emitter[1] = GLWaterExpSparkEmitter;
emitter[2] = GLWaterExpSmokeEmitter;
emitter[3] = GLWaterExpBubbleEmitter;
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "20.0 20.0 20.0";
camShakeDuration = 1.5;
camShakeRadius = 20.0;
lightStartRadius = 20.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.9 0.8";
lightEndColor = "0.6 0.6 1.0";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
// ----------------------------------------------------------------------------
// Dry/Air Explosion Objects
// ----------------------------------------------------------------------------
datablock ExplosionData(GrenadeSubExplosion)
{
offset = 0.25;
emitter[0] = GrenadeExpSparkEmitter;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "0.9 0.7 0.7";
lightEndColor = "0.9 0.7 0.7";
lightStartBrightness = 2.0;
lightEndBrightness = 0.0;
};
datablock ExplosionData(GrenadeLauncherExplosion)
{
soundProfile = GrenadeLauncherExplosionSound;
lifeTimeMS = 400; // Quick flash, short burn, and moderate dispersal
// Volume particles
particleEmitter = GrenadeExpFireEmitter;
particleDensity = 75;
particleRadius = 2.25;
// Point emission
emitter[0] = GrenadeExpDustEmitter;
emitter[1] = GrenadeExpSparksEmitter;
emitter[2] = GrenadeExpSmokeEmitter;
// Sub explosion objects
subExplosion[0] = GrenadeSubExplosion;
// Camera Shaking
shakeCamera = true;
camShakeFreq = "10.0 11.0 9.0";
camShakeAmp = "15.0 15.0 15.0";
camShakeDuration = 1.5;
camShakeRadius = 20;
// Exploding debris
debris = GrenadeDebris;
debrisThetaMin = 10;
debrisThetaMax = 60;
debrisNum = 4;
debrisNumVariance = 2;
debrisVelocity = 25;
debrisVelocityVariance = 5;
lightStartRadius = 4.0;
lightEndRadius = 0.0;
lightStartColor = "1.0 1.0 1.0";
lightEndColor = "1.0 1.0 1.0";
lightStartBrightness = 4.0;
lightEndBrightness = 0.0;
lightNormalOffset = 2.0;
};
// ----------------------------------------------------------------------------
// Underwater Grenade projectile trail
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeTrailWaterParticle)
{
textureName = "art/particles/bubble";
dragCoefficient = 0.0;
gravityCoefficient = 0.1;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 1500;
lifetimeVarianceMS = 600;
useInvAlpha = false;
spinRandomMin = -100.0;
spinRandomMax = 100.0;
spinSpeed = 1;
colors[0] = "0.7 0.8 1.0 1.0";
colors[1] = "0.7 0.8 1.0 0.4";
colors[2] = "0.7 0.8 1.0 0.0";
sizes[0] = 0.05;
sizes[1] = 0.05;
sizes[2] = 0.05;
times[0] = 0.0;
times[1] = 0.5;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeTrailWaterEmitter)
{
ejectionPeriodMS = 5;
periodVarianceMS = 0;
ejectionVelocity = 1.0;
ejectionOffset = 0.1;
velocityVariance = 0.5;
thetaMin = 0.0;
thetaMax = 80.0;
phiReferenceVel = 0;
phiVariance = 360;
overrideAdvances = false;
particles = GrenadeTrailWaterParticle;
};
// ----------------------------------------------------------------------------
// Normal-fire Projectile Object
// ----------------------------------------------------------------------------
datablock ParticleData(GrenadeProjSmokeTrail)
{
textureName = "art/particles/smoke";
dragCoeffiecient = 0.0;
gravityCoefficient = -0.2;
inheritedVelFactor = 0.0;
constantAcceleration = 0.0;
lifetimeMS = 750;
lifetimeVarianceMS = 250;
useInvAlpha = true;
spinRandomMin = -60;
spinRandomMax = 60;
spinSpeed = 1;
colors[0] = "0.9 0.8 0.8 0.6";
colors[1] = "0.6 0.6 0.6 0.9";
colors[2] = "0.3 0.3 0.3 0";
sizes[0] = 0.25;
sizes[1] = 0.5;
sizes[2] = 0.75;
times[0] = 0.0;
times[1] = 0.4;
times[2] = 1.0;
};
datablock ParticleEmitterData(GrenadeProjSmokeTrailEmitter)
{
ejectionPeriodMS = 10;
periodVarianceMS = 0;
ejectionVelocity = 0.75;
velocityVariance = 0;
thetaMin = 0.0;
thetaMax = 0.0;
phiReferenceVel = 90;
phiVariance = 0;
particles = "GrenadeProjSmokeTrail";
};
datablock ProjectileData(GrenadeLauncherProjectile)
{
projectileShapeName = "art/shapes/weapons/shared/rocket.dts";
directDamage = 30;
radiusDamage = 30;
damageRadius = 5;
areaImpulse = 2000;
explosion = GrenadeLauncherExplosion;
waterExplosion = GrenadeLauncherWaterExplosion;
decal = ScorchRXDecal;
splash = GrenadeSplash;
particleEmitter = GrenadeProjSmokeTrailEmitter;
particleWaterEmitter = GrenadeTrailWaterEmitter;
muzzleVelocity = 30;
velInheritFactor = 0.3;
armingDelay = 2000;
lifetime = 10000;
fadeDelay = 4500;
bounceElasticity = 0.4;
bounceFriction = 0.3;
isBallistic = true;
gravityMod = 0.9;
lightDesc = GrenadeLauncherLightDesc;
damageType = "GrenadeDamage";
};
| |
//-----------------------------------------------------------------------
// <copyright file="TangoSupport.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;
/// <summary>
/// Contains the Project Tango Support Unity API. The Project Tango Support
/// Unity API provides helper methods useful to external developers for
/// manipulating Project Tango data. The Project Tango Support Unity API is
/// experimental and subject to change.
/// </summary>
public static class TangoSupport
{
/// <summary>
/// Matrix that transforms from Start of Service to the Unity World.
/// </summary>
public static readonly Matrix4x4 UNITY_WORLD_T_START_SERVICE = new Matrix4x4
{
m00 = 1.0f, m01 = 0.0f, m02 = 0.0f, m03 = 0.0f,
m10 = 0.0f, m11 = 0.0f, m12 = 1.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 1.0f, m22 = 0.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
/// <summary>
/// Matrix that transforms from the Unity Camera to Device.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*",
Justification = "Matrix visibility is more important.")]
public static readonly Matrix4x4 DEVICE_T_UNITY_CAMERA = new Matrix4x4
{
m00 = 1.0f, m01 = 0.0f, m02 = 0.0f, m03 = 0.0f,
m10 = 0.0f, m11 = 1.0f, m12 = 0.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 0.0f, m22 = -1.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
public static readonly Matrix4x4 COLOR_CAMERA_T_UNITY_CAMERA = new Matrix4x4
{
m00 = 1.0f, m01 = 0.0f, m02 = 0.0f, m03 = 0.0f,
m10 = 0.0f, m11 = -1.0f, m12 = 0.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 0.0f, m22 = 1.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
/// <summary>
/// The rotation matrix need to be applied when using color camera's pose.
/// </summary>
public static Matrix4x4 m_colorCameraPoseRotation = Matrix4x4.identity;
/// <summary>
/// The rotation matrix need to be applied when using device pose.
/// </summary>
public static Matrix4x4 m_devicePoseRotation = Matrix4x4.identity;
/// <summary>
/// Name of the Tango Support C API shared library.
/// </summary>
internal const string TANGO_SUPPORT_UNITY_DLL = "tango_support_api";
/// <summary>
/// Class name for debug logging.
/// </summary>
private const string CLASS_NAME = "TangoSupport";
/// <summary>
/// Matrix that transforms for device screen rotation of 270 degrees.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*",
Justification = "Matrix visibility is more important.")]
private static readonly Matrix4x4 ROTATION270_T_DEFAULT = new Matrix4x4
{
m00 = 0.0f, m01 = -1.0f, m02 = 0.0f, m03 = 0.0f,
m10 = 1.0f, m11 = 0.0f, m12 = 0.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 0.0f, m22 = 1.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
/// <summary>
/// Matrix that transforms for device screen rotation of 180 degrees.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*",
Justification = "Matrix visibility is more important.")]
private static readonly Matrix4x4 ROTATION180_T_DEFAULT = new Matrix4x4
{
m00 = -1.0f, m01 = 0.0f, m02 = 0.0f, m03 = 0.0f,
m10 = 0.0f, m11 = -1.0f, m12 = 0.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 0.0f, m22 = 1.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
/// <summary>
/// Matrix that transforms for device screen rotation of 90 degrees.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.SpacingRules", "*",
Justification = "Matrix visibility is more important.")]
private static readonly Matrix4x4 ROTATION90_T_DEFAULT = new Matrix4x4
{
m00 = 0.0f, m01 = 1.0f, m02 = 0.0f, m03 = 0.0f,
m10 = -1.0f, m11 = 0.0f, m12 = 0.0f, m13 = 0.0f,
m20 = 0.0f, m21 = 0.0f, m22 = 1.0f, m23 = 0.0f,
m30 = 0.0f, m31 = 0.0f, m32 = 0.0f, m33 = 1.0f
};
/// <summary>
/// Compute a rotation from rotation a to rotation b, in form of the OrientationManager.Rotation enum.
/// </summary>
/// <param name="b">Target rotation frame.</param>
/// <param name="a">Start rotation frame.</param>
/// <returns>The orientation index that follows Android screen rotation standard.</returns>
public static Tango.OrientationManager.Rotation RotateFromAToB(Tango.OrientationManager.Rotation b,
Tango.OrientationManager.Rotation a)
{
int ret = (int)b - (int)a;
if (ret < 0)
{
ret += 4;
}
return (Tango.OrientationManager.Rotation)(ret % 4);
}
/// <summary>
/// Update current additional rotation matrix based on the display orientation and color camera orientation.
///
/// Not that m_colorCameraPoseRotation will need to compensate the rotation with physical color camera.
/// </summary>
/// <param name="displayRotation">Orientation of current activity. Index enum is same same as Android screen
/// orientation standard.</param>
/// <param name="colorCameraRotation">Orientation of current color camera sensor. Index enum is same as Android
/// camera orientation standard.</param>
public static void UpdatePoseMatrixFromDeviceRotation(OrientationManager.Rotation displayRotation,
OrientationManager.Rotation colorCameraRotation)
{
Tango.OrientationManager.Rotation r = RotateFromAToB(displayRotation, colorCameraRotation);
switch (r)
{
case Tango.OrientationManager.Rotation.ROTATION_90:
m_colorCameraPoseRotation = ROTATION90_T_DEFAULT;
break;
case Tango.OrientationManager.Rotation.ROTATION_180:
m_colorCameraPoseRotation = ROTATION180_T_DEFAULT;
break;
case Tango.OrientationManager.Rotation.ROTATION_270:
m_colorCameraPoseRotation = ROTATION270_T_DEFAULT;
break;
default:
m_colorCameraPoseRotation = Matrix4x4.identity;
break;
}
switch (displayRotation)
{
case Tango.OrientationManager.Rotation.ROTATION_90:
m_devicePoseRotation = ROTATION90_T_DEFAULT;
break;
case Tango.OrientationManager.Rotation.ROTATION_180:
m_devicePoseRotation = ROTATION180_T_DEFAULT;
break;
case Tango.OrientationManager.Rotation.ROTATION_270:
m_devicePoseRotation = ROTATION270_T_DEFAULT;
break;
default:
m_devicePoseRotation = Matrix4x4.identity;
break;
}
}
/// <summary>
/// Fits a plane to a point cloud near a user-specified location. This
/// occurs in two passes. First, all points in cloud within
/// <c>maxPixelDistance</c> to <c>uvCoordinates</c> after projection are kept. Then a
/// plane is fit to the subset cloud using RANSAC. After the initial fit
/// all inliers from the original cloud are used to refine the plane
/// model.
/// </summary>
/// <returns>
/// Common.ErrorType.TANGO_SUCCESS on success,
/// Common.ErrorType.TANGO_INVALID on invalid input, and
/// Common.ErrorType.TANGO_ERROR on failure.
/// </returns>
/// <param name="pointCloud">
/// The point cloud. Cannot be null and must have at least three points.
/// </param>
/// <param name="pointCount">
/// The number of points to read from the point cloud.
/// </param>
/// <param name="timestamp">The timestamp of the point cloud.</param>
/// <param name="cameraIntrinsics">
/// The camera intrinsics for the color camera. Cannot be null.
/// </param>
/// <param name="matrix">
/// Transformation matrix of the color camera with respect to the Unity
/// World frame.
/// </param>
/// <param name="uvCoordinates">
/// The UV coordinates for the user selection. This is expected to be
/// between (0.0, 0.0) and (1.0, 1.0).
/// </param>
/// <param name="intersectionPoint">
/// The output point in depth camera coordinates that the user selected.
/// </param>
/// <param name="plane">The plane fit.</param>
public static int FitPlaneModelNearClick(
Vector3[] pointCloud, int pointCount, double timestamp,
TangoCameraIntrinsics cameraIntrinsics, ref Matrix4x4 matrix,
Vector2 uvCoordinates, out Vector3 intersectionPoint,
out Plane plane)
{
GCHandle pointCloudHandle = GCHandle.Alloc(pointCloud,
GCHandleType.Pinned);
TangoXYZij pointCloudXyzIj = new TangoXYZij();
pointCloudXyzIj.timestamp = timestamp;
pointCloudXyzIj.xyz_count = pointCount;
pointCloudXyzIj.xyz = pointCloudHandle.AddrOfPinnedObject();
DMatrix4x4 doubleMatrix = new DMatrix4x4(matrix);
// Unity has Y pointing screen up; Tango camera has Y pointing
// screen down.
Vector2 uvCoordinatesTango = new Vector2(uvCoordinates.x,
1.0f - uvCoordinates.y);
DVector3 doubleIntersectionPoint = new DVector3();
double[] planeArray = new double[4];
int returnValue = TangoSupportAPI.TangoSupport_fitPlaneModelNearPointMatrixTransform(
pointCloudXyzIj, cameraIntrinsics, ref doubleMatrix,
ref uvCoordinatesTango,
out doubleIntersectionPoint, planeArray);
if (returnValue != Common.ErrorType.TANGO_SUCCESS)
{
intersectionPoint = new Vector3(0.0f, 0.0f, 0.0f);
plane = new Plane(new Vector3(0.0f, 0.0f, 0.0f), 0.0f);
}
else
{
intersectionPoint = doubleIntersectionPoint.ToVector3();
Vector3 normal = new Vector3((float)planeArray[0],
(float)planeArray[1],
(float)planeArray[2]);
float distance = (float)planeArray[3] / normal.magnitude;
plane = new Plane(normal, distance);
}
pointCloudHandle.Free();
return returnValue;
}
/// <summary>
/// DEPRECATED. Use ScreenCoordinateToWorldNearestNeighbor instead.
///
/// Calculates the depth in the color camera space at a user-specified
/// location using nearest-neighbor interpolation.
/// </summary>
/// <returns>
/// Common.ErrorType.TANGO_SUCCESS on success and
/// Common.ErrorType.TANGO_INVALID on invalid input.
/// </returns>
/// <param name="pointCloud">
/// The point cloud. Cannot be null and must have at least one point.
/// </param>
/// <param name="pointCount">
/// The number of points to read from the point cloud.
/// </param>
/// <param name="timestamp">The timestamp of the depth points.</param>
/// <param name="cameraIntrinsics">
/// The camera intrinsics for the color camera. Cannot be null.
/// </param>
/// <param name="matrix">
/// Transformation matrix of the color camera with respect to the Unity
/// World frame.
/// </param>
/// <param name="uvCoordinates">
/// The UV coordinates for the user selection. This is expected to be
/// between (0.0, 0.0) and (1.0, 1.0).
/// </param>
/// <param name="colorCameraPoint">
/// The point (x, y, z), where (x, y) is the back-projection of the UV
/// coordinates to the color camera space and z is the z coordinate of
/// the point in the point cloud nearest to the user selection after
/// projection onto the image plane. If there is not a point cloud point
/// close to the user selection after projection onto the image plane,
/// then the point will be set to (0.0, 0.0, 0.0) and isValidPoint will
/// be set to false.
/// </param>
/// <param name="isValidPoint">
/// A flag valued true if there is a point cloud point close to the user
/// selection after projection onto the image plane and valued false
/// otherwise.
/// </param>
[Obsolete("Use ScreenCoordinateToWorldNearestNeighbor instead.")]
public static int GetDepthAtPointNearestNeighbor(
Vector3[] pointCloud, int pointCount, double timestamp,
TangoCameraIntrinsics cameraIntrinsics, ref Matrix4x4 matrix,
Vector2 uvCoordinates, out Vector3 colorCameraPoint,
out bool isValidPoint)
{
return ScreenCoordinateToWorldNearestNeighbor(pointCloud,
pointCount, timestamp, cameraIntrinsics, ref matrix,
uvCoordinates, out colorCameraPoint, out isValidPoint);
}
/// <summary>
/// Calculates the depth in the color camera space at a user-specified
/// location using nearest-neighbor interpolation.
/// </summary>
/// <returns>
/// Common.ErrorType.TANGO_SUCCESS on success and
/// Common.ErrorType.TANGO_INVALID on invalid input.
/// </returns>
/// <param name="pointCloud">
/// The point cloud. Cannot be null and must have at least one point.
/// </param>
/// <param name="pointCount">
/// The number of points to read from the point cloud.
/// </param>
/// <param name="timestamp">The timestamp of the depth points.</param>
/// <param name="cameraIntrinsics">
/// The camera intrinsics for the color camera. Cannot be null.
/// </param>
/// <param name="matrix">
/// Transformation matrix of the color camera with respect to the Unity
/// World frame.
/// </param>
/// <param name="uvCoordinates">
/// The UV coordinates for the user selection. This is expected to be
/// between (0.0, 0.0) and (1.0, 1.0).
/// </param>
/// <param name="colorCameraPoint">
/// The point (x, y, z), where (x, y) is the back-projection of the UV
/// coordinates to the color camera space and z is the z coordinate of
/// the point in the point cloud nearest to the user selection after
/// projection onto the image plane. If there is not a point cloud point
/// close to the user selection after projection onto the image plane,
/// then the point will be set to (0.0, 0.0, 0.0) and isValidPoint will
/// be set to false.
/// </param>
/// <param name="isValidPoint">
/// A flag valued true if there is a point cloud point close to the user
/// selection after projection onto the image plane and valued false
/// otherwise.
/// </param>
public static int ScreenCoordinateToWorldNearestNeighbor(
Vector3[] pointCloud, int pointCount, double timestamp,
TangoCameraIntrinsics cameraIntrinsics, ref Matrix4x4 matrix,
Vector2 uvCoordinates, out Vector3 colorCameraPoint,
out bool isValidPoint)
{
GCHandle pointCloudHandle = GCHandle.Alloc(pointCloud,
GCHandleType.Pinned);
TangoXYZij pointCloudXyzIj = new TangoXYZij();
pointCloudXyzIj.timestamp = timestamp;
pointCloudXyzIj.xyz_count = pointCount;
pointCloudXyzIj.xyz = pointCloudHandle.AddrOfPinnedObject();
DMatrix4x4 doubleMatrix = new DMatrix4x4(matrix);
// Unity has Y pointing screen up; Tango camera has Y pointing
// screen down.
Vector2 uvCoordinatesTango = new Vector2(uvCoordinates.x,
1.0f - uvCoordinates.y);
int isValidPointInteger;
int returnValue = TangoSupportAPI.TangoSupport_getDepthAtPointNearestNeighborMatrixTransform(
pointCloudXyzIj, cameraIntrinsics, ref doubleMatrix,
ref uvCoordinatesTango, out colorCameraPoint,
out isValidPointInteger);
isValidPoint = isValidPointInteger != 0;
pointCloudHandle.Free();
return returnValue;
}
/// <summary>
/// Calculates the depth in the color camera space at a user-specified
/// location using bilateral filtering weighted by both spatial distance
/// from the user coordinate and by intensity similarity.
/// </summary>
/// <returns>
/// Common.ErrorType.TANGO_SUCCESS on success,
/// Common.ErrorType.TANGO_INVALID on invalid input, and
/// Common.ErrorType.TANGO_ERROR on failure.
/// </returns>
/// <param name="pointCloud">
/// The point cloud. Cannot be null and must have at least one point.
/// </param>
/// <param name="pointCount">
/// The number of points to read from the point cloud.
/// </param>
/// <param name="timestamp">The timestamp of the depth points.</param>
/// <param name="cameraIntrinsics">
/// The camera intrinsics for the color camera. Cannot be null.
/// </param>
/// <param name="colorImage">
/// The color image buffer. Cannot be null.
/// </param>
/// <param name="matrix">
/// Transformation matrix of the color camera with respect to the Unity
/// World frame.
/// </param>
/// <param name="uvCoordinates">
/// The UV coordinates for the user selection. This is expected to be
/// between (0.0, 0.0) and (1.0, 1.0).
/// </param>
/// <param name="colorCameraPoint">
/// The point (x, y, z), where (x, y) is the back-projection of the UV
/// coordinates to the color camera space and z is the z coordinate of
/// the point in the point cloud nearest to the user selection after
/// projection onto the image plane. If there is not a point cloud point
/// close to the user selection after projection onto the image plane,
/// then the point will be set to (0.0, 0.0, 0.0) and isValidPoint will
/// be set to false.
/// </param>
/// <param name="isValidPoint">
/// A flag valued true if there is a point cloud point close to the user
/// selection after projection onto the image plane and valued false
/// otherwise.
/// </param>
public static int ScreenCoordinateToWorldBilateral(
Vector3[] pointCloud, int pointCount, double timestamp,
TangoCameraIntrinsics cameraIntrinsics, TangoImageBuffer colorImage,
ref Matrix4x4 matrix, Vector2 uvCoordinates,
out Vector3 colorCameraPoint, out bool isValidPoint)
{
GCHandle pointCloudHandle = GCHandle.Alloc(pointCloud,
GCHandleType.Pinned);
TangoXYZij pointCloudXyzIj = new TangoXYZij();
pointCloudXyzIj.timestamp = timestamp;
pointCloudXyzIj.xyz_count = pointCount;
pointCloudXyzIj.xyz = pointCloudHandle.AddrOfPinnedObject();
DMatrix4x4 doubleMatrix = new DMatrix4x4(matrix);
// Unity has Y pointing screen up; Tango camera has Y pointing
// screen down.
Vector2 uvCoordinatesTango = new Vector2(uvCoordinates.x,
1.0f - uvCoordinates.y);
int isValidPointInteger;
int returnValue = TangoSupportAPI.TangoSupport_getDepthAtPointBilateralCameraIntrinsicsMatrixTransform(
pointCloudXyzIj, cameraIntrinsics, colorImage, ref doubleMatrix,
ref uvCoordinatesTango, out colorCameraPoint,
out isValidPointInteger);
isValidPoint = isValidPointInteger != 0;
pointCloudHandle.Free();
return returnValue;
}
/// <summary>
/// Convert a TangoPoseData into the Unity coordinate system. This only
/// works on TangoPoseData that describes the device with respect to the
/// start of service or area description. The result position and
/// rotation can be used to set Unity's Transform.position and
/// Transform.rotation.
/// </summary>
/// <param name="poseData">
/// The input pose data that is going to be converted, please note that
/// the pose data has to be in the start of service with respect to
/// device frame.
/// </param>
/// <param name="position">The result position data.</param>
/// <param name="rotation">The result rotation data.</param>
public static void TangoPoseToWorldTransform(TangoPoseData poseData,
out Vector3 position,
out Quaternion rotation)
{
if (poseData == null)
{
Debug.Log("Invalid poseData.\n" + Environment.StackTrace);
position = Vector3.zero;
rotation = Quaternion.identity;
return;
}
if (poseData.framePair.targetFrame != TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE)
{
Debug.Log("Invalid target frame of the poseData.\n" + Environment.StackTrace);
position = Vector3.zero;
rotation = Quaternion.identity;
return;
}
if (poseData.framePair.baseFrame !=
TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE &&
poseData.framePair.baseFrame !=
TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION)
{
Debug.Log("Invalid base frame of the poseData.\n" + Environment.StackTrace);
position = Vector3.zero;
rotation = Quaternion.identity;
return;
}
Matrix4x4 startServiceTDevice = poseData.ToMatrix4x4();
Matrix4x4 unityWorldTUnityCamera = UNITY_WORLD_T_START_SERVICE *
startServiceTDevice *
DEVICE_T_UNITY_CAMERA *
m_devicePoseRotation;
// Extract final position, rotation.
position = unityWorldTUnityCamera.GetColumn(3);
rotation = Quaternion.LookRotation(unityWorldTUnityCamera.GetColumn(2),
unityWorldTUnityCamera.GetColumn(1));
}
/// <summary>
/// A double-precision 4x4 transformation matrix.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct DMatrix4x4
{
/// <summary>
/// 0,0-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_00;
/// <summary>
/// 1,0-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_10;
/// <summary>
/// 2,0-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_20;
/// <summary>
/// 3,0-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_30;
/// <summary>
/// 0,1-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_01;
/// <summary>
/// 1,1-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_11;
/// <summary>
/// 2,1-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_21;
/// <summary>
/// 3,1-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_31;
/// <summary>
/// 0,2-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_02;
/// <summary>
/// 1,2-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_12;
/// <summary>
/// 2,2-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_22;
/// <summary>
/// 3,2-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_32;
/// <summary>
/// 0,3-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_03;
/// <summary>
/// 1,3-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_13;
/// <summary>
/// 2,3-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_23;
/// <summary>
/// 3,3-th element of this matrix.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_33;
/// <summary>
/// Creates a new double-precision matrix from the given
/// single-precision matrix.
/// </summary>
/// <param name="matrix">A single-precision matrix.</param>
public DMatrix4x4(Matrix4x4 matrix)
{
m_00 = matrix.m00;
m_10 = matrix.m10;
m_20 = matrix.m20;
m_30 = matrix.m30;
m_01 = matrix.m01;
m_11 = matrix.m11;
m_21 = matrix.m21;
m_31 = matrix.m31;
m_02 = matrix.m02;
m_12 = matrix.m12;
m_22 = matrix.m22;
m_32 = matrix.m32;
m_03 = matrix.m03;
m_13 = matrix.m13;
m_23 = matrix.m23;
m_33 = matrix.m33;
}
/// <summary>
/// Returns a single-precision matrix representation of this
/// double-precision matrix.
/// </summary>
/// <returns>A single-precision matrix.</returns>
public Matrix4x4 ToMatrix4x4()
{
return new Matrix4x4
{
m00 = (float)m_00, m01 = (float)m_01, m02 = (float)m_02, m03 = (float)m_03,
m10 = (float)m_10, m11 = (float)m_11, m12 = (float)m_12, m13 = (float)m_13,
m20 = (float)m_20, m21 = (float)m_21, m22 = (float)m_22, m23 = (float)m_23,
m30 = (float)m_30, m31 = (float)m_31, m32 = (float)m_32, m33 = (float)m_33
};
}
/// <summary>
/// Returns a string representation of this matrix.
/// </summary>
/// <returns>A string.</returns>
public override string ToString()
{
return string.Format("{0}\t{1}\t{2}\t{3}\n{4}\t{5}\t{6}\t{7}\n{8}\t{9}\t{10}\t{11}\n{12}\t{13}\t{14}\t{15}\n",
m_00, m_01, m_02, m_03,
m_10, m_11, m_12, m_13,
m_20, m_21, m_22, m_23,
m_30, m_31, m_32, m_33);
}
}
/// <summary>
/// A double-precision 3D vector.
/// </summary>
private struct DVector3
{
/// <summary>
/// X component of this vector.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_x;
/// <summary>
/// Y component of this vector.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_y;
/// <summary>
/// Z component of this vector.
/// </summary>
[MarshalAs(UnmanagedType.R8)]
public double m_z;
/// <summary>
/// Creates a new double-precision vector from the given
/// single-precision vector.
/// </summary>
/// <param name="vector">A single-precision vector.</param>
public DVector3(Vector3 vector)
{
m_x = vector.x;
m_y = vector.y;
m_z = vector.z;
}
/// <summary>
/// Returns a single-precision vector representation of this
/// double-precision vector.
/// </summary>
/// <returns>A single-precision vector.</returns>
public Vector3 ToVector3()
{
return new Vector3((float)m_x, (float)m_y, (float)m_z);
}
/// <summary>
/// Returns a string representation of this vector.
/// </summary>
/// <returns>A string.</returns>
public override string ToString()
{
return string.Format("({0}, {1}, {2})", m_x, m_y, m_z);
}
}
#region API_Functions
/// <summary>
/// Wraps the Tango Support C API.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "C API Wrapper")]
private struct TangoSupportAPI
{
#if UNITY_ANDROID && !UNITY_EDITOR
[DllImport(TANGO_SUPPORT_UNITY_DLL)]
public static extern int TangoSupport_fitPlaneModelNearPointMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
ref DMatrix4x4 matrix, ref Vector2 uvCoordinates,
out DVector3 intersectionPoint,
[Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 4)] double[] planeModel);
[DllImport(TANGO_SUPPORT_UNITY_DLL)]
public static extern int TangoSupport_getDepthAtPointBilateralCameraIntrinsicsMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
TangoImageBuffer colorImage, ref DMatrix4x4 matrix,
ref Vector2 uvCoordinates, out Vector3 colorCameraPoint,
[Out, MarshalAs(UnmanagedType.I4)] out int isValidPoint);
[DllImport(TANGO_SUPPORT_UNITY_DLL)]
public static extern int TangoSupport_getDepthAtPointNearestNeighborMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
ref DMatrix4x4 matrix, ref Vector2 uvCoordinates,
out Vector3 colorCameraPoint,
[Out, MarshalAs(UnmanagedType.I4)] out int isValidPoint);
#else
public static int TangoSupport_fitPlaneModelNearPointMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
ref DMatrix4x4 matrix, ref Vector2 uvCoordinates,
out DVector3 intersectionPoint, double[] planeModel)
{
intersectionPoint = new DVector3();
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoSupport_getDepthAtPointBilateralCameraIntrinsicsMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
TangoImageBuffer colorImage, ref DMatrix4x4 matrix,
ref Vector2 uvCoordinates, out Vector3 colorCameraPoint,
out int isValidPoint)
{
colorCameraPoint = Vector3.zero;
isValidPoint = 1;
return Common.ErrorType.TANGO_SUCCESS;
}
public static int TangoSupport_getDepthAtPointNearestNeighborMatrixTransform(
TangoXYZij pointCloud, TangoCameraIntrinsics cameraIntrinsics,
ref DMatrix4x4 matrix, ref Vector2 uvCoordinates,
out Vector3 colorCameraPoint, out int isValidPoint)
{
colorCameraPoint = Vector3.zero;
isValidPoint = 1;
return Common.ErrorType.TANGO_SUCCESS;
}
#endif
}
#endregion
}
}
| |
// GenCilAsText.cs: HDO, 1998-2005, 2006-08-28
// ---------------
// Generate CIL in form of text to be assembled later on.
//=====================================|========================================
#define GENCILASTEXT
#if GENCILASTEXT
#undef TEST_GENCILASTEXT
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.Text;
public static class GenCilAsText
{
private static String MODULE;
private static Stack loopEndLabels;
// --- provide lables ---
private static int nextLabNr;
private static String NewLabel()
{
String label = "L" + nextLabNr;
nextLabNr++;
return label;
} // NewLabel
// === generate CIL for declarations ===
private static void GenGlobConsts(StringBuilder sb)
{
Symbol sy = SymTab.CurSymbols();
while (sy != null)
{
if (sy.kind == Symbol.Kind.constKind)
{
sb.Append(" .field public static literal ");
GenType(sb, sy.type);
sb.Append(NameList.NameOf(sy.spix) + " = ");
if (sy.type == Type.boolType)
{
sb.Append("bool(");
if (sy.val == 0)
sb.Append("false)\n");
else // sy.val != 0
sb.Append("true)\n");
}
else
{ // sy.type == intType
sb.Append("int32(" + sy.val + ")\n");
} // else
} // if
sy = sy.next;
} // while
} // GenGlobConsts
private static void GenGlobVars(StringBuilder sb)
{
Symbol sy = SymTab.CurSymbols();
while (sy != null)
{
if (sy.kind == Symbol.Kind.varKind)
{
sb.Append(" .field public static ");
GenType(sb, sy.type);
sb.Append(NameList.NameOf(sy.spix) + "\n");
} // if
sy = sy.next;
} // while
} // GenGlobVars
private static void GenLocVars(StringBuilder sb, Symbol symbols)
{
Symbol sy = symbols;
// skip parameters
while (sy != null && sy.kind == Symbol.Kind.parKind)
{
sy = sy.next;
} // while
// generate local declarations for constants and variables
Symbol firstConstOrVarSy = sy;
int i = 0;
while (sy != null)
{
if (sy.kind == Symbol.Kind.constKind ||
sy.kind == Symbol.Kind.varKind)
{
if (i == 0)
sb.Append(" .locals init (\n ");
else
sb.Append(",\n ");
sb.Append("[" + i + "] ");
GenType(sb, sy.type);
sb.Append(NameList.NameOf(sy.spix));
if (sy.next == null)
sb.Append(")\n");
i++;
} // if
sy = sy.next;
} // while
// generate initializations for constants
sy = firstConstOrVarSy;
while (sy != null)
{
if (sy.kind == Symbol.Kind.constKind ||
sy.kind == Symbol.Kind.varKind && sy.init)
{
if (sy.type.IsPtrType() && sy.val == 0)
sb.Append(" ldnull\n");
else if(sy.type.kind == Type.Kind.doubleKind)
sb.Append(" ldc.r8 " + Convert.ToString(sy.dblVal, System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "\n");
else
sb.Append(" ldc.i4 " + sy.val + "\n");
sb.Append(" stloc " + sy.addr + "\n");
} // if
sy = sy.next;
} // while
} // GenLocVars
private static void GenType(StringBuilder sb, Type t)
{
switch (t.kind)
{
case Type.Kind.voidKind:
sb.Append("void ");
break;
case Type.Kind.boolKind:
sb.Append("bool ");
break;
case Type.Kind.boolPtrKind:
sb.Append("bool[] ");
break;
case Type.Kind.intKind:
sb.Append("int32 ");
break;
case Type.Kind.intPtrKind:
sb.Append("int32[] ");
break;
case Type.Kind.doubleKind:
sb.Append("float64 ");
break;
case Type.Kind.doublePtrKind:
sb.Append("float64[] ");
break;
default:
throw new Exception("invalid type kind");
} // switch
} // GenType
private static void GenGlobFuncs(StringBuilder sb)
{
Symbol sy = SymTab.CurSymbols();
while (sy != null)
{
if (sy.kind == Symbol.Kind.funcKind && NameList.NameOf(sy.spix) != "main")
{
sb.Append(" .method public hidebysig static ");
GenType(sb, sy.type);
sb.Append(NameList.NameOf(sy.spix) + "(");
Symbol parSy = sy.symbols;
bool first = true;
while (parSy != null && parSy.kind == Symbol.Kind.parKind)
{
if (first)
sb.Append("\n ");
else
sb.Append(",\n ");
first = false;
GenType(sb, parSy.type);
sb.Append(NameList.NameOf(parSy.spix));
parSy = parSy.next;
} // while
sb.Append(") cil managed {\n");
sb.Append(" .maxstack 100\n");
GenLocVars(sb, sy.symbols);
GenFuncBody(sb, sy);
sb.Append(" } // .method\n\n");
} // if
sy = sy.next;
} // while
} // GenGlobFuncs
// === generate CIL for expresssions ===
private static void GenLoadConstOperand(StringBuilder sb, LitOperand lo)
{
if (lo.type.kind == Type.Kind.boolKind ||
lo.type.kind == Type.Kind.intKind)
sb.Append(" ldc.i4 " + lo.val + "\n");
else if (lo.type.kind == Type.Kind.doubleKind)
sb.Append(" ldc.r8 " + Convert.ToString(lo.dblVal, System.Globalization.CultureInfo.InvariantCulture.NumberFormat) + "\n");
else if (lo.type.kind == Type.Kind.voidPtrKind &&
lo.val == 0)
sb.Append(" ldnull\n");
else
throw new Exception("invalid const operand type");
} // GenLoadConstOperand
private static void GenLoadVarOperand(StringBuilder sb, VarOperand vo)
{
switch (vo.sy.kind)
{
case Symbol.Kind.constKind:
if(vo.type.kind == Type.Kind.doubleKind)
sb.Append(" ldc.r8 " + vo.sy.val + "\n");
else
sb.Append(" ldc.i4 " + vo.sy.val + "\n");
break;
case Symbol.Kind.varKind:
if (vo.sy.level == 0)
{ // global scope
sb.Append(" ldsfld ");
GenType(sb, vo.sy.type);
sb.Append(MODULE + "::" + NameList.NameOf(vo.sy.spix) + "\n");
}
else if (vo.sy.level == 1) // function scope
sb.Append(" ldloc " + vo.sy.addr + "\n");
else
throw new Exception("invalid operand scope level");
break;
case Symbol.Kind.parKind:
sb.Append(" ldarg " + vo.sy.addr + "\n");
break;
default:
throw new Exception("invalid operand kind");
} // switch
} // GenLoadVarOperand
private static void GenStoreVarOperand(StringBuilder sb, VarOperand vo)
{
switch (vo.sy.kind)
{
case Symbol.Kind.varKind:
if (vo.sy.level == 0)
{ // global scope
sb.Append(" stsfld ");
GenType(sb, vo.sy.type);
sb.Append(MODULE + "::" + NameList.NameOf(vo.sy.spix) + "\n");
}
else if (vo.sy.level == 1) // function scope
sb.Append(" stloc " + vo.sy.addr + "\n");
else
throw new Exception("invalid operand scope level");
break;
case Symbol.Kind.parKind:
sb.Append(" starg " + vo.sy.addr + "\n");
break;
default:
throw new Exception("invalid operand kind");
} // switch
} // GenStoreVarOperand
private static void GenUnaryOperator(StringBuilder sb, UnaryOperator uo)
{
GenExpr(sb, uo.e);
switch (uo.op)
{
case UnaryOperator.Operation.notOp:
sb.Append(" ldc.i4 1\n");
sb.Append(" xor\n");
break;
case UnaryOperator.Operation.posOp:
sb.Append(" nop // posOp\n");
break;
case UnaryOperator.Operation.negOp:
sb.Append(" neg\n");
break;
default:
throw new Exception("invalid unary operator");
} // switch
} // GenUnaryOperator
private static void GenBinaryOperator(StringBuilder sb, BinaryOperator bo)
{
GenExpr(sb, bo.left);
if (bo.op == BinaryOperator.Operation.orOp ||
bo.op == BinaryOperator.Operation.andOp)
{
String label1 = NewLabel();
if (bo.op == BinaryOperator.Operation.orOp)
sb.Append(" brtrue " + label1 + "\n");
else // bo.op == BinaryOperator.Operation.andOp
sb.Append(" brfalse " + label1 + "\n");
GenExpr(sb, bo.right);
String label2 = NewLabel();
sb.Append(" br " + label2 + "\n");
sb.Append(label1 + ":\n");
if (bo.op == BinaryOperator.Operation.orOp)
sb.Append(" ldc.i4 1\n");
else // bo.op == BinaryOperator.Operation.andOp
sb.Append(" ldc.i4 0\n");
sb.Append(label2 + ":\n");
}
else
{
GenExpr(sb, bo.right);
switch (bo.op)
{
case BinaryOperator.Operation.orOp:
sb.Append(" // orOp\n");
break;
case BinaryOperator.Operation.andOp:
sb.Append(" // andOp\n");
break;
case BinaryOperator.Operation.eqOp:
sb.Append(" ceq\n");
break;
case BinaryOperator.Operation.neOp:
sb.Append(" ceq\n");
sb.Append(" ldc.i4 1\n");
sb.Append(" xor\n");
break;
case BinaryOperator.Operation.ltOp:
sb.Append(" clt\n");
break;
case BinaryOperator.Operation.leOp:
sb.Append(" cgt\n");
sb.Append(" ldc.i4 1\n");
sb.Append(" xor\n");
break;
case BinaryOperator.Operation.gtOp:
sb.Append(" cgt\n");
break;
case BinaryOperator.Operation.geOp:
sb.Append(" clt\n");
sb.Append(" ldc.i4 1\n");
sb.Append(" xor\n");
break;
case BinaryOperator.Operation.addOp:
sb.Append(" add\n");
break;
case BinaryOperator.Operation.subOp:
sb.Append(" sub\n");
break;
case BinaryOperator.Operation.mulOp:
sb.Append(" mul\n");
break;
case BinaryOperator.Operation.divOp:
sb.Append(" div\n");
break;
case BinaryOperator.Operation.modOp:
sb.Append(" rem\n");
break;
default:
throw new Exception("invalid binary operator");
} // switch
} // else
} // GenBinaryOperator
private static void GenArrIdxOperator(StringBuilder sb, ArrIdxOperator aio)
{
GenLoadVarOperand(sb, aio.arr);
GenExpr(sb, aio.idx);
switch (aio.type.kind)
{
case Type.Kind.boolKind:
sb.Append(" ldelem.i1\n");
break;
case Type.Kind.intKind:
sb.Append(" ldelem.i4\n");
break;
default:
throw new Exception("invalid type kind");
} // switch
} // GenArrIdxOperator
private static void GenCall(StringBuilder sb, Symbol func, Expr apl)
{
Expr ap = apl;
while (ap != null)
{
GenExpr(sb, ap);
ap = ap.next;
} // while
sb.Append(" call ");
GenType(sb, func.type);
sb.Append(MODULE + "::" + NameList.NameOf(func.spix) + "(");
Symbol fp = func.symbols;
bool first = true;
while (fp != null && fp.kind == Symbol.Kind.parKind)
{
if (first)
sb.Append("\n ");
else
sb.Append(",\n ");
first = false;
GenType(sb, fp.type);
fp = fp.next;
} // while
sb.Append(")\n");
} // GenCall
private static void GenFuncCallOperator(StringBuilder sb, FuncCallOperator fco)
{
GenCall(sb, fco.func, fco.apl);
} // GenFuncCallOperator
private static void GenNewOperator(StringBuilder sb, NewOperator no)
{
GenExpr(sb, no.noe);
switch (no.elemType.kind)
{
case Type.Kind.boolKind:
sb.Append(" newarr [mscorlib]System.Boolean\n");
break;
case Type.Kind.intKind:
sb.Append(" newarr [mscorlib]System.Int32\n");
break;
default:
throw new Exception("invalid type kind");
} // switch
} // GenNewOperator
private static void GenExpr(StringBuilder sb, Expr e)
{
switch (e.kind)
{
case Expr.Kind.litOperandKind:
GenLoadConstOperand(sb, (LitOperand)e);
break;
case Expr.Kind.varOperandKind:
GenLoadVarOperand(sb, (VarOperand)e);
break;
case Expr.Kind.unaryOperatorKind:
GenUnaryOperator(sb, (UnaryOperator)e);
break;
case Expr.Kind.binaryOperatorKind:
GenBinaryOperator(sb, (BinaryOperator)e);
break;
case Expr.Kind.arrIdxOperatorKind:
GenArrIdxOperator(sb, (ArrIdxOperator)e);
break;
case Expr.Kind.funcCallOperatorKind:
GenFuncCallOperator(sb, (FuncCallOperator)e);
break;
case Expr.Kind.newOperatorKind:
GenNewOperator(sb, (NewOperator)e);
break;
default:
throw new Exception("invalid expression kind");
} // switch
} // GenExpr
private static void GenLoadAddrOrVarOperand(StringBuilder sb, VarOperand vo)
{
switch (vo.sy.kind)
{
case Symbol.Kind.varKind:
if (vo.sy.level == 0)
{ // global scope
sb.Append(" ldsflda ");
GenType(sb, vo.sy.type);
sb.Append(MODULE + "::" + NameList.NameOf(vo.sy.spix) + "\n");
}
else if (vo.sy.level == 1) // function scope
sb.Append(" ldloca " + vo.sy.addr + "\n");
else
throw new Exception("invalid operand scope level");
break;
case Symbol.Kind.parKind:
sb.Append(" ldarga " + vo.sy.addr + "\n");
break;
default:
throw new Exception("invalid operand kind");
} // switch
} // GenLoadAddrOrVarOperand
// === generate CIL for statements ===
private static void GenBlockStat(StringBuilder sb, BlockStat s)
{
GenStatList(sb, s.statList);
} // GenBlockStat
private static void GenIncStat(StringBuilder sb, IncStat s)
{
GenLoadVarOperand(sb, s.vo);
sb.Append(" ldc.i4 1\n");
sb.Append(" add\n");
GenStoreVarOperand(sb, s.vo);
} // GenIncStat
private static void GenDecStat(StringBuilder sb, DecStat s)
{
GenLoadVarOperand(sb, s.vo);
sb.Append(" ldc.i4 1\n");
sb.Append(" sub\n");
GenStoreVarOperand(sb, s.vo);
} // GenDecStat
private static void GenAssignStat(StringBuilder sb, AssignStat s)
{
switch (s.lhs.kind)
{
case Expr.Kind.varOperandKind:
GenExpr(sb, s.rhs);
GenStoreVarOperand(sb, (VarOperand)s.lhs);
break;
case Expr.Kind.arrIdxOperatorKind:
ArrIdxOperator aio = (ArrIdxOperator)s.lhs;
GenExpr(sb, aio.arr);
GenExpr(sb, aio.idx);
GenExpr(sb, s.rhs);
switch (aio.type.kind)
{
case Type.Kind.boolKind:
sb.Append(" stelem.i1\n");
break;
case Type.Kind.intKind:
sb.Append(" stelem.i4\n");
break;
default:
throw new Exception("invalid type kind");
} // switch
break;
default:
throw new Exception("invalid lhs kind");
} // switch
} // GenAssignStat
private static void GenCallStat(StringBuilder sb, CallStat s)
{
GenCall(sb, s.func, s.apl);
if (s.func.type.kind != Type.Kind.voidKind)
sb.Append(" pop\n");
} // GenCallStat
private static void GenIfStat(StringBuilder sb, IfStat s)
{
GenExpr(sb, s.cond);
String label1 = NewLabel();
sb.Append(" brfalse " + label1 + "\n");
GenStatList(sb, s.thenStat);
if (s.elseStat != null)
{
String label2 = NewLabel();
sb.Append(" br " + label2 + "\n");
sb.Append(label1 + ":\n");
label1 = label2;
GenStatList(sb, s.elseStat);
} // if
sb.Append(label1 + ":\n");
} // GenIfStat
private static void GenWhileStat(StringBuilder sb, WhileStat s)
{
String label1 = NewLabel();
sb.Append(label1 + ":\n");
GenExpr(sb, s.cond);
String label2 = NewLabel();
sb.Append(" brfalse " + label2 + "\n");
loopEndLabels.Push(label2);
GenStatList(sb, s.body);
loopEndLabels.Pop();
sb.Append(" br " + label1 + "\n");
sb.Append(label2 + ":\n");
} // GenWhileStat
private static void GenSwitchStat(StringBuilder sb, SwitchStat s)
{
if (s.caseStat == null && s.defaultStat == null)
{
return;
}
GenExpr(sb, s.expr);
var defaultLabel = NewLabel();
var endOfSwitchLabel = NewLabel();
var caseLabels = new System.Collections.Generic.Dictionary<Stat, string>();
var caseStat = s.caseStat;
while (caseStat != null)
{
var caseLabel = NewLabel();
caseLabels.Add(caseStat, caseLabel);
sb.AppendFormat(" dup \n");
sb.AppendFormat(" ldc.i4 {0} \n", ((CaseStat)caseStat).val);
sb.AppendFormat(" beq.s {0} \n", caseLabel);
sb.AppendFormat("\n");
caseStat = caseStat.next;
}
if (s.defaultStat != null)
{
sb.AppendLine(" br.s " + defaultLabel);
}
else
{
sb.AppendLine(" br.s " + endOfSwitchLabel);
}
loopEndLabels.Push(endOfSwitchLabel);
caseStat = s.caseStat;
while (caseStat != null)
{
sb.AppendLine(caseLabels[caseStat] + ": ");
GenStatList(sb, ((CaseStat)caseStat).stat);
caseStat = caseStat.next;
}
if (s.defaultStat != null)
{
sb.AppendLine(defaultLabel + ": ");
GenStatList(sb, s.defaultStat);
}
loopEndLabels.Pop();
sb.AppendLine(endOfSwitchLabel + ": ");
} //GenSwitchStat
private static void GenBreakStat(StringBuilder sb)
{
if (loopEndLabels.Count <= 0)
throw new Exception("break with no loop around");
String label = (String)loopEndLabels.Peek();
sb.Append(" br " + label + "\n");
} // GenBreakStat
private static void GenInputStat(StringBuilder sb, InputStat s)
{
GenLoadAddrOrVarOperand(sb, s.vo);
switch (s.vo.sy.type.kind)
{
case Type.Kind.boolKind:
sb.Append(" call void BasicIO::ReadFromCin(bool&)\n");
break;
case Type.Kind.intKind:
sb.Append(" call void BasicIO::ReadFromCin(int32&)\n");
break;
case Type.Kind.doubleKind:
sb.Append(" call void BasicIO::ReadFromCin(float64&)\n");
break;
default:
throw new Exception("invalid type");
} // switch
} // GenInputStat
private static void GenOutputStat(StringBuilder sb, OutputStat s)
{
foreach (Object o in s.values)
{
if (o is Expr)
{
Expr e = o as Expr;
GenExpr(sb, e);
sb.Append(" call void BasicIO::WriteToCout(");
GenType(sb, e.type);
sb.Append(")\n");
}
else if (o is String)
{
String str = o as String;
if (str == "\n")
{
sb.Append(" call void BasicIO::WriteEndlToCout()\n");
}
else
{
sb.Append(" ldstr \"" + str + "\"\n");
sb.Append(" call void BasicIO::WriteToCout(string)\n");
} // else
}
else
throw new Exception("invalid value");
} // foreach
} // GenOutputStat
private static void GenDeleteStat(StringBuilder sb, DeleteStat s)
{
sb.Append(" ldnull\n");
GenStoreVarOperand(sb, s.vo);
} // GenDeleteStat
private static void GenReturnStat(StringBuilder sb, ReturnStat s)
{
if (s.e != null)
GenExpr(sb, s.e);
sb.Append(" ret\n");
} // GenReturnStat
private static void GenStatList(StringBuilder sb, Stat statList)
{
Stat stat = statList;
while (stat != null)
{
switch (stat.kind)
{
case Stat.Kind.emptyStatKind:
sb.Append(" nop\n");
break;
case Stat.Kind.blockStatKind:
GenBlockStat(sb, (BlockStat)stat);
break;
case Stat.Kind.incStatKind:
GenIncStat(sb, (IncStat)stat);
break;
case Stat.Kind.decStatKind:
GenDecStat(sb, (DecStat)stat);
break;
case Stat.Kind.assignStatKind:
GenAssignStat(sb, (AssignStat)stat);
break;
case Stat.Kind.callStatKind:
GenCallStat(sb, (CallStat)stat);
break;
case Stat.Kind.ifStatKind:
GenIfStat(sb, (IfStat)stat);
break;
case Stat.Kind.whileStatKind:
GenWhileStat(sb, (WhileStat)stat);
break;
case Stat.Kind.switchStatKind:
GenSwitchStat(sb, (SwitchStat)stat);
break;
case Stat.Kind.breakStatKind:
GenBreakStat(sb);
break;
case Stat.Kind.inputStatKind:
GenInputStat(sb, (InputStat)stat);
break;
case Stat.Kind.outputStatKind:
GenOutputStat(sb, (OutputStat)stat);
break;
case Stat.Kind.returnStatKind:
GenReturnStat(sb, (ReturnStat)stat);
break;
case Stat.Kind.deleteStatKind:
GenDeleteStat(sb, (DeleteStat)stat);
break;
default:
throw new Exception("invalid statement kind");
} // switch
stat = stat.next;
} // while
} //GenStatList
private static void GenFuncBody(StringBuilder sb, Symbol funcSy)
{
nextLabNr = 0;
GenStatList(sb, funcSy.statList);
switch (funcSy.type.kind)
{
case Type.Kind.voidKind:
sb.Append(" ret\n");
break;
case Type.Kind.boolKind:
case Type.Kind.intKind:
sb.Append("DummyReturn:\n");
sb.Append(" ldc.i4 0\n");
sb.Append(" ret\n");
break;
case Type.Kind.doubleKind:
sb.Append("DummyReturn:\n");
sb.Append(" ldc.r8 0\n");
sb.Append(" ret\n");
break;
case Type.Kind.boolPtrKind:
case Type.Kind.intPtrKind:
case Type.Kind.doublePtrKind:
sb.Append("DummyReturn:\n");
sb.Append(" ldnull\n");
sb.Append(" ret\n");
break;
default:
throw new Exception("invalid function type kind");
} // switch
} // GenFuncBody
private static void GenMainFuncBody(StringBuilder sb)
{
Symbol sy = SymTab.CurSymbols();
while (sy != null)
{
if (sy.kind == Symbol.Kind.funcKind && NameList.NameOf(sy.spix) == "main")
{
sb.Append(" .maxstack 100\n");
GenLocVars(sb, sy.symbols);
GenFuncBody(sb, sy);
return;
} // if
sy = sy.next;
} // while
} // GenMainFuncBody
private static void GenCctorBody(StringBuilder sb)
{
sb.Append(" .maxstack 100\n");
Symbol sy = SymTab.CurSymbols();
while (sy != null)
{
if (sy.kind == Symbol.Kind.varKind && sy.init)
{
sb.Append(" ldc.i4 " + sy.val + "\n");
sb.Append(" stsfld ");
GenType(sb, sy.type);
sb.Append(MODULE + "::" + NameList.NameOf(sy.spix) + "\n");
} // if
sy = sy.next;
} // while
sb.Append(" ret\n");
} // GenCctorBody
public static void GenerateCilFile(String path, String moduleName)
{
if (path.Length != 0 && path[path.Length - 1] != '\\')
path = path + "\\";
MODULE = moduleName;
loopEndLabels = new Stack();
StringBuilder GLOBALS = new StringBuilder();
StringBuilder METHODS = new StringBuilder();
StringBuilder MAINBODY = new StringBuilder();
StringBuilder CCTORBODY = new StringBuilder();
GenGlobConsts(GLOBALS);
GenGlobVars(GLOBALS);
GenGlobFuncs(METHODS);
GenMainFuncBody(MAINBODY);
GenCctorBody(CCTORBODY);
try
{
FileStream ilFs = new FileStream(path + moduleName + ".il", FileMode.Create);
StreamWriter cil = new StreamWriter(ilFs);
Template t = new Template(path, "CIL.frm");
cil.WriteLine(t.Instance(
new String[] { "MODULE", "GLOBALS", "METHODS", "MAINBODY", "CCTORBODY" },
new String[]{ MODULE,
GLOBALS.ToString(),
METHODS.ToString(),
MAINBODY.ToString(),
CCTORBODY.ToString()
}));
cil.Close();
}
catch (Exception e)
{
Console.WriteLine(e);
} // catch
} // GenerateCilFile
public static void GenerateAssembly(string path, string moduleName)
{
//-----------------------------------|---------------------------------------
String ilFileName;
if (path == "")
ilFileName = moduleName + ".il";
else
ilFileName = path + moduleName + ".il";
if (File.Exists(ilFileName))
File.Delete(ilFileName);
Console.WriteLine("emitting CIL to \"" + ilFileName + "\" ...");
GenCilAsText.GenerateCilFile(path, moduleName);
String exeFileName;
if (path == "")
exeFileName = moduleName + ".exe";
else
exeFileName = path + moduleName + ".exe";
if (File.Exists(exeFileName))
File.Delete(exeFileName);
String winDir = Environment.GetEnvironmentVariable("windir");
String dotNetFwDir = winDir + "\\Microsoft.NET\\Framework\\v4.0.30319\\";
if (!File.Exists(dotNetFwDir + "ilasm.exe"))
{
Console.WriteLine("ilasm.exe not found in \"" + dotNetFwDir);
Console.WriteLine(" assembling \"" + ilFileName + "\" has to be done manually");
return;
} // if
Console.WriteLine("assembling CIL to \"" + exeFileName + "\" ...");
ProcessStartInfo psi = new ProcessStartInfo
{
FileName = dotNetFwDir + "ilasm.exe",
Arguments = "/QUIET " + ilFileName,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
}; // new
using (Process p = Process.Start(psi))
{
StreamReader stderr = p.StandardError;
String line = stderr.ReadLine();
while (line != null)
{
Console.WriteLine(line);
line = stderr.ReadLine();
} // while
p.WaitForExit();
} // using
if (!File.Exists(exeFileName))
Console.WriteLine("some errors during assembly detected");
} // GenerateAssembly
#if TEST_GENCILASTEXT
public static void Main(String[] args) {
Console.WriteLine("START: GenCilAsText");
Console.WriteLine("END");
Console.WriteLine();
Console.WriteLine("type [CR] to continue ...");
Console.ReadLine();
} // main
#endif // TEST_GENCILASTEXT
} // GenCilAsText
#endif // GENCILASTEXT
// End of GenCilAsText.cs
//=====================================|========================================
| |
/**
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
using NUnit.Framework;
namespace Facebook.CSSLayout.Tests
{
/**
* Tests for {@link LayoutEngine} and {@link CSSNode} to make sure layouts are only generated when
* needed.
*/
public class LayoutCachingTest
{
private void assertTreeHasNewLayout(bool expectedHasNewLayout, CSSNode root)
{
Assert.AreEqual(expectedHasNewLayout, root.HasNewLayout);
for (int i = 0; i < root.getChildCount(); i++)
{
assertTreeHasNewLayout(expectedHasNewLayout, root.getChildAt(i));
}
}
private void markLayoutAppliedForTree(CSSNode root)
{
root.MarkLayoutSeen();
for (int i = 0; i < root.getChildCount(); i++)
{
markLayoutAppliedForTree(root.getChildAt(i));
}
}
[Test]
public void testCachesFullTree()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
root.calculateLayout();
assertTreeHasNewLayout(true, root);
markLayoutAppliedForTree(root);
root.calculateLayout();
Assert.True(root.HasNewLayout);
assertTreeHasNewLayout(false, c0);
assertTreeHasNewLayout(false, c1);
}
[Test]
public void testInvalidatesCacheWhenChildAdded()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
CSSNode c0c1 = new CSSNode();
CSSNode c1c0 = new CSSNode();
c0c1.Width = 200;
c0c1.Height = 200;
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
c0c0.addChildAt(c1c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c0.addChildAt(c0c1, 1);
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.True(c0c1.HasNewLayout);
Assert.True(c0c0.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.False(c1c0.HasNewLayout);
}
[Test]
public void testInvalidatesCacheWhenEnumPropertyChanges()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c1.AlignSelf = CSSAlign.Center;
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.False(c0c0.HasNewLayout);
}
[Test]
public void testInvalidatesCacheWhenFloatPropertyChanges()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c1.SetMargin(CSSSpacingType.Left, 10);
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.False(c0c0.HasNewLayout);
}
[Test]
public void testInvalidatesFullTreeWhenParentWidthChanges()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
CSSNode c1c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
c1.addChildAt(c1c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c0.Height = 200;
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.True(c0c0.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.False(c1c0.HasNewLayout);
}
[Test]
public void testDoesNotInvalidateCacheWhenPropertyIsTheSame()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
root.Width = 200;
root.calculateLayout();
markLayoutAppliedForTree(root);
root.Width = 200;
root.calculateLayout();
Assert.True(root.HasNewLayout);
assertTreeHasNewLayout(false, c0);
assertTreeHasNewLayout(false, c1);
}
[Test]
public void testInvalidateCacheWhenHeightChangesPosition()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c1c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c1.addChildAt(c1c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c0.Height = 100;
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.False(c1c0.HasNewLayout);
}
[Test]
public void testInvalidatesOnNewMeasureFunction()
{
CSSNode root = new CSSNode();
CSSNode c0 = new CSSNode();
CSSNode c1 = new CSSNode();
CSSNode c0c0 = new CSSNode();
root.addChildAt(c0, 0);
root.addChildAt(c1, 1);
c0.addChildAt(c0c0, 0);
root.calculateLayout();
markLayoutAppliedForTree(root);
c1.setMeasureFunction((node, width) => new MeasureOutput(100, 20));
root.calculateLayout();
Assert.True(root.HasNewLayout);
Assert.True(c1.HasNewLayout);
Assert.True(c0.HasNewLayout);
Assert.False(c0c0.HasNewLayout);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using Microsoft.DiaSymReader.PortablePdb;
using Microsoft.DiaSymReader.Tools;
namespace Microsoft.Cci.Pdb {
/// <summary>
/// Portable PDB provider.
/// </summary>
internal static class PdbFormatProvider {
/// <summary>
/// Detect whether a given stream contains portable or Windows PDB format data
/// and deserialize CCI PDB information from the given format.
/// </summary>
/// <param name="peFilePath">Path to IL PE module (needed only for portable PDB's)</param>
/// <param name="standalonePdbPath">Path to standalone Windows PDB (not used for portable PDBs)</param>
public static PdbInfo TryLoadFunctions(
string peFilePath,
string standalonePdbPath)
{
if (!string.IsNullOrEmpty(peFilePath))
{
using (Stream peStream = new FileStream(peFilePath, FileMode.Open, FileAccess.Read))
using (PEReader peReader = new PEReader(peStream))
{
MetadataReaderProvider pdbReaderProvider;
string pdbPath;
if (peReader.TryOpenAssociatedPortablePdb(peFilePath, File.OpenRead, out pdbReaderProvider, out pdbPath))
{
using (pdbReaderProvider)
{
// Load associated portable PDB
PdbWriterForCci cciWriter = new PdbWriterForCci();
new PdbConverter().ConvertPortableToWindows<int>(
peReader,
pdbReaderProvider.GetMetadataReader(),
cciWriter,
PdbConversionOptions.SuppressSourceLinkConversion);
PdbInfo pdbInfo = new PdbInfo()
{
Functions = cciWriter.Functions,
TokenToSourceMapping = cciWriter.TokenToSourceMapping,
Age = cciWriter.Age,
Guid = cciWriter.Guid,
// Ignored for portable PDBs to avoid bringing in a dependency on Newtonsoft.Json
SourceServerData = null
};
return pdbInfo;
}
}
}
}
if (File.Exists(standalonePdbPath))
{
using (FileStream pdbInputStream = new FileStream(standalonePdbPath, FileMode.Open, FileAccess.Read))
{
if (!PdbConverter.IsPortable(pdbInputStream))
{
// Load CCI data from Windows PDB
return PdbFile.LoadFunctions(pdbInputStream);
}
}
}
// Non-existent Windows PDB or mismatched portable PDB
return null;
}
/// <summary>
/// The basic idea of the portable PDB conversion is that we let the converter run
/// and use this PdbWriterForCci class to construct the CCI-expected data structures.
/// </summary>
class PdbWriterForCci : Microsoft.DiaSymReader.PdbWriter<int>
{
/// <summary>
/// List of functions exposed by the PDB.
/// </summary>
public List<PdbFunction> Functions { get; private set; }
/// <summary>
/// Map from method tokens to source location linked lists.
/// </summary>
public Dictionary<uint, PdbTokenLine> TokenToSourceMapping { get; private set; }
/// <summary>
/// Encoded age information for the portable PDB.
/// </summary>
public int Age { get; private set; }
/// <summary>
/// Encoded GUID information for the portable PDB.
/// </summary>
public Guid Guid { get; private set; }
/// <summary>
/// List of previously defined PdbSource documents
/// </summary>
private List<PdbSource> _sourceDocuments;
/// <summary>
/// The currently open function instance.
/// </summary>
private PdbFunction _currentMethod;
/// <summary>
/// Scope stack for current method.
/// </summary>
private Stack<PdbScopeBuilder> _scopeStackForCurrentMethod;
/// <summary>
/// Currently open scope
/// </summary>
private PdbScopeBuilder _currentScope;
/// <summary>
/// Top level (non-nested) scopes for the current method.
/// </summary>
private List<PdbScope> _topLevelScopesForCurrentMethod;
/// <summary>
/// All namespaces used by the current method.
/// </summary>
private HashSet<string> _usedNamespacesForCurrentMethod;
/// <summary>
/// Map from document indices to line numbers for the currently open method.
/// </summary>
private Dictionary<int, List<PdbLine>> _linesForCurrentMethod;
/// <summary>
/// Construct the converter writer used for building the CCI data graph representing the PDB.
/// </summary>
public PdbWriterForCci()
{
Functions = new List<PdbFunction>();
TokenToSourceMapping = new Dictionary<uint, PdbTokenLine>();
_sourceDocuments = new List<PdbSource>();
_currentMethod = null;
}
/// <summary>
/// Define an indexed document to be subsequently referred to by sequence points.
/// </summary>
/// <returns>Document index that the converter will subsequently pass to DefineSequencePoints</returns>
public override int DefineDocument(string name, Guid language, Guid vendor, Guid type, Guid algorithmId, byte[] checksum)
{
int documentIndex = _sourceDocuments.Count;
_sourceDocuments.Add(new PdbSource(
name: name,
doctype: type,
language: language,
vendor: vendor,
checksumAlgorithm: algorithmId,
checksum: checksum));
return documentIndex;
}
/// <summary>
/// Add a set of sequence points in a given document to the currently open method.
/// </summary>
/// <param name="documentIndex">Zero-based index of the source document previously allocated in DefineDocument</param>
/// <param name="count">Number of sequence points to add</param>
/// <param name="offsets">IL offsets for the individual sequence points</param>
/// <param name="startLines">Start line numbers</param>
/// <param name="startColumns">Start column indices</param>
/// <param name="endLines">Ending line numbers</param>
/// <param name="endColumns">Ending column indices</param>
public override void DefineSequencePoints(
int documentIndex,
int count,
int[] offsets,
int[] startLines,
int[] startColumns,
int[] endLines,
int[] endColumns)
{
Contract.Assert(_currentMethod != null);
List<PdbLine> linesForCurrentDocument;
if (!_linesForCurrentMethod.TryGetValue(documentIndex, out linesForCurrentDocument))
{
linesForCurrentDocument = new List<PdbLine>();
_linesForCurrentMethod.Add(documentIndex, linesForCurrentDocument);
}
PdbTokenLine firstTokenLine = null;
PdbTokenLine lastTokenLine = null;
for (int sequencePointIndex = 0; sequencePointIndex < count; sequencePointIndex++)
{
PdbTokenLine newTokenLine = new PdbTokenLine(
token: _currentMethod.token,
file_id: (uint)documentIndex,
line: (uint)startLines[sequencePointIndex],
column: (uint)startColumns[sequencePointIndex],
endLine: (uint)endLines[sequencePointIndex],
endColumn: (uint)endColumns[sequencePointIndex]);
if (firstTokenLine == null)
{
firstTokenLine = newTokenLine;
}
else
{
lastTokenLine.nextLine = newTokenLine;
}
lastTokenLine = newTokenLine;
linesForCurrentDocument.Add(new PdbLine(
offset: (uint)offsets[sequencePointIndex],
lineBegin: (uint)startLines[sequencePointIndex],
colBegin: (ushort)startColumns[sequencePointIndex],
lineEnd: (uint)endLines[sequencePointIndex],
colEnd: (ushort)endColumns[sequencePointIndex]));
}
PdbTokenLine existingTokenLine;
if (TokenToSourceMapping.TryGetValue(_currentMethod.token, out existingTokenLine))
{
while (existingTokenLine.nextLine != null)
{
existingTokenLine = existingTokenLine.nextLine;
}
existingTokenLine.nextLine = firstTokenLine;
}
else
{
TokenToSourceMapping.Add(_currentMethod.token, firstTokenLine);
}
}
/// <summary>
/// Start populating symbol information pertaining to a given method.
/// </summary>
/// <param name="methodToken">MSIL metadata token representing the method</param>
public override void OpenMethod(int methodToken)
{
// Nested method opens are not supported
Contract.Assert(_currentMethod == null);
_currentMethod = new PdbFunction();
_currentMethod.token = (uint)methodToken;
_linesForCurrentMethod = new Dictionary<int, List<PdbLine>>();
_scopeStackForCurrentMethod = new Stack<PdbScopeBuilder>();
_currentScope = null;
_topLevelScopesForCurrentMethod = new List<PdbScope>();
_usedNamespacesForCurrentMethod = new HashSet<string>();
}
/// <summary>
/// Finalize method info emission and add the new element to the function list.
/// </summary>
public override void CloseMethod()
{
Contract.Assert(_currentMethod != null);
List<PdbLines> documentLineSets = new List<PdbLines>();
foreach (KeyValuePair<int, List<PdbLine>> tokenLinePair in _linesForCurrentMethod)
{
int lineCount = tokenLinePair.Value.Count;
PdbLines lines = new PdbLines(_sourceDocuments[tokenLinePair.Key], (uint)lineCount);
for (int lineIndex = 0; lineIndex < lineCount; lineIndex++)
{
lines.lines[lineIndex] = tokenLinePair.Value[lineIndex];
}
documentLineSets.Add(lines);
}
_currentMethod.scopes = _topLevelScopesForCurrentMethod.ToArray();
_currentMethod.lines = documentLineSets.ToArray();
_currentMethod.usedNamespaces = _usedNamespacesForCurrentMethod.ToArray();
Functions.Add(_currentMethod);
_currentMethod = null;
_linesForCurrentMethod = null;
_scopeStackForCurrentMethod = null;
_currentScope = null;
_topLevelScopesForCurrentMethod = null;
_usedNamespacesForCurrentMethod = null;
}
/// <summary>
/// Open scope at given IL offset within the method. The scopes may be nested.
/// </summary>
/// <param name="startOffset">Starting IL offset for the scope</param>
public override void OpenScope(int startOffset)
{
if (_currentScope != null)
{
_scopeStackForCurrentMethod.Push(_currentScope);
}
_currentScope = new PdbScopeBuilder((uint)startOffset);
}
/// <summary>
/// Close scope at given IL offset within the method.
/// </summary>
/// <param name="endOffset">Ending IL offset for the scope</param>
public override void CloseScope(int endOffset)
{
Contract.Assert(_currentScope != null);
PdbScope scope = _currentScope.Close((uint)endOffset);
if (_scopeStackForCurrentMethod.Count != 0)
{
_currentScope = _scopeStackForCurrentMethod.Pop();
_currentScope.AddChildScope(scope);
}
else
{
_currentScope = null;
_topLevelScopesForCurrentMethod.Add(scope);
}
}
/// <summary>
/// Define local variable within the current scope
/// </summary>
/// <param name="index">Slot index</param>
/// <param name="name">Variable name</param>
/// <param name="attributes">Variable properties</param>
/// <param name="localSignatureToken">Signature token representing the variable type</param>
public override void DefineLocalVariable(int index, string name, LocalVariableAttributes attributes, int localSignatureToken)
{
Contract.Assert(_currentScope != null);
PdbSlot localVariable = new PdbSlot(
slot: (uint)index,
typeToken: (uint)localSignatureToken,
name: name,
flags: (ushort)attributes);
_currentScope.AddSlot(localVariable);
}
/// <summary>
/// Define constant within the current scope
/// </summary>
/// <param name="name">Constant name</param>
/// <param name="value">Constant value</param>
/// <param name="constantSignatureToken">Signature token representing the constant type</param>
public override void DefineLocalConstant(string name, object value, int constantSignatureToken)
{
Contract.Assert(_currentScope != null);
if ((constantSignatureToken & 0xFFFFFF) != 0)
{
PdbConstant pdbConstant = new PdbConstant(
name: name,
token: (uint)constantSignatureToken,
value: value);
_currentScope.AddConstant(pdbConstant);
}
}
/// <summary>
/// Add a 'using' namespace clause to the current scope.
/// </summary>
/// <param name="importString">Namespace name to add</param>
public override void UsingNamespace(string importString)
{
Contract.Assert(_currentScope != null);
_currentScope.AddUsedNamespace(importString);
_usedNamespacesForCurrentMethod.Add(importString);
}
public override void SetAsyncInfo(int moveNextMethodToken, int kickoffMethodToken, int catchHandlerOffset, int[] yieldOffsets, int[] resumeOffsets)
{
Contract.Assert(_currentMethod != null);
_currentMethod.synchronizationInformation = new PdbSynchronizationInformation(
moveNextMethodToken,
kickoffMethodToken,
catchHandlerOffset,
yieldOffsets,
resumeOffsets);
}
public override void DefineCustomMetadata(byte[] metadata)
{
Contract.Assert(_currentMethod != null);
_currentMethod.ReadMD2CustomMetadata(new BitAccess(metadata));
}
public override void SetEntryPoint(int entryPointMethodToken)
{
// NO-OP for CCI
}
public override void UpdateSignature(Guid guid, uint stamp, int age)
{
Guid = guid;
Age = age;
}
public override void SetSourceServerData(byte[] sourceServerData)
{
// NO-OP for CCI
}
public override void SetSourceLinkData(byte[] sourceLinkData)
{
// NO-OP for CCI
}
/// <summary>
/// Helper class used to compose a hierarchical tree of method scopes.
/// At method level, we maintain a stack of these builders. Whenever we Open
/// a scope, we push a new scope builder to the stack. Once we close a scope,
/// we complete construction of the PdbScope object at the top of the stack
/// and pop it off, either adding to children of its parent scope or to the list
/// of top-level scopes accessible from the PdbFunction object.
/// </summary>
private class PdbScopeBuilder
{
/// <summary>
/// Starting IL offset for the scope gets initialized in the constructor.
/// </summary>
private readonly uint _startOffset;
/// <summary>
/// Lazily constructed list of child scopes.
/// </summary>
private List<PdbScope> _childScopes;
/// <summary>
/// Lazily constructed list of per-scope constants.
/// </summary>
private List<PdbConstant> _constants;
/// <summary>
/// Lazily constructed list of 'using' namespaces within the scope.
/// </summary>
private List<string> _usedNamespaces;
/// <summary>
/// Lazily constructed list of slots (local variables).
/// </summary>
private List<PdbSlot> _slots;
/// <summary>
/// Constructor stores the starting IL offset for the scope.
/// </summary>
public PdbScopeBuilder(uint startOffset)
{
_startOffset = startOffset;
_childScopes = new List<PdbScope>();
_constants = new List<PdbConstant>();
_slots = new List<PdbSlot>();
}
/// <summary>
/// Finalize construction of the PdbScope and return the complete PdbScope object.
/// </summary>
/// <param name="endOffset">Ending IL offset for the scope</param>
public PdbScope Close(uint endOffset)
{
PdbScope scope = new PdbScope(
address: 0,
offset: _startOffset,
length: endOffset - _startOffset,
slots: _slots.ToArray(),
constants: _constants.ToArray(),
usedNamespaces: _usedNamespaces?.ToArray());
scope.scopes = _childScopes.ToArray();
return scope;
}
/// <summary>
/// Add a scope to the list of immediate child scopes of this scope.
/// </summary>
/// <param name="childScope">Child scope to add to this scope</param>
public void AddChildScope(PdbScope childScope)
{
_childScopes.Add(childScope);
}
/// <summary>
/// Add a slot (local variable) to the list of slots for this scope.
/// </summary>
/// <param name="slot">Slot to add to this scope</param>
public void AddSlot(PdbSlot slot)
{
_slots.Add(slot);
}
/// <summary>
/// Add a constant to the list of constants available within this scope.
/// </summary>
/// <param name="constant">Constant to add to this scope</param>
public void AddConstant(PdbConstant pdbConstant)
{
_constants.Add(pdbConstant);
}
/// <summary>
/// Add a used namespace to the list of namespaces used by this scope.
/// </summary>
/// <param name="usedNamespaceName">Used namespace name to add to this scope</param>
public void AddUsedNamespace(string usedNamespaceName)
{
if (_usedNamespaces == null)
{
_usedNamespaces = new List<string>();
}
_usedNamespaces.Add(usedNamespaceName);
}
}
}
}
}
| |
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace Dwm
{
#region Enumerations
// Specifies which command is passed through the ThumbnailProperties structure
[Flags()]
internal enum ThumbnailFlags
{
RectDestination = 0x0000001, // Rectangle destination of thumbnail
RectSource = 0x0000002, // Rectangle source of thumbnail
Opacity = 0x0000004, // Opacity
Visible = 0x0000008, // Visibility
SourceClientAreaOnly = 0x00000010 // Displays only the client area of the source
}
// Stores the Thumbnail properties and a flag to indicate which properties
// are set by the DwmUpdateThumbnailProperties method
[StructLayout(LayoutKind.Sequential)]
internal struct ThumbnailProperties
{
public ThumbnailFlags flags; // Flag
public Rectangle destination; // Destination rectangle
public Rectangle source; // Source rectangle
public byte opacity; // Opacity
public bool visible; // Visibility
public bool sourceClientAreaOnly; // Displays only the client area of the source
}
#endregion
/// <summary>
/// Provides methods to display a thumbnail of a given form on another form
/// </summary>
public class Thumbnail : IDisposable
{
// Thumbnail handle
private IntPtr handle;
// ThumbnailProperties structure to be passed to DwmUpdateThumbnailProperties
private ThumbnailProperties properties;
// Indicates whether the object was disposed
private bool disposed = false;
/// <summary>
/// Creates a new thumbnail given a destination form handle and a source form handle
/// </summary>
/// <param name="hwndDestination">Handle of the form where the thumbnail will appear</param>
/// <param name="hwndSource">Handle of the form for which the thumbnail is created</param>
public Thumbnail(IntPtr hwndDestination, IntPtr hwndSource)
{
// Native API call
handle = DwmRegisterThumbnail(hwndDestination, hwndSource);
// Initialize properties structure
properties = new ThumbnailProperties();
}
/// <summary>
/// Creates a new thumbnail given a destination form and a source form handle
/// </summary>
/// <param name="destination">Form where the thumbnail will appear</param>
/// <param name="hwndSource">Handle of the form for which the thumbnail is created</param>
public Thumbnail(Form destination, IntPtr hwndSource)
: this(destination.Handle, hwndSource)
{
}
/// <summary>
/// Creates a new thumbnail given a destination form and a source form
/// </summary>
/// <param name="destination">Form where the thumbnail will appear</param>
/// <param name="source">Form for which the thumbnail is created</param>
public Thumbnail(Form destination, Form source)
: this(destination.Handle, source.Handle)
{
}
/// <summary>
/// Gets the size of the thumbnail source
/// </summary>
/// <returns>Size structure indicating the size of the thumbnail source</returns>
public Size GetSourceSize()
{
// Initialize structure
Size result = new Size();
// Check if handle is valid
if (handle != IntPtr.Zero)
{
try
{
// Native API call
DwmQueryThumbnailSourceSize(handle, out result);
}
// If source or destination handles become invalid, the thumbnail handle
// will also become invalid and an ArgumentException will be thrown
catch (ArgumentException)
{
// Handle became invalid - set it to null
this.handle = IntPtr.Zero;
}
}
return result;
}
/// <summary>
/// Sets the rectangle that will be shown by the thumbnail
/// </summary>
/// <param name="sourceRectangle">Rectangle on the source form to be shown in thumbnail</param>
public void SetSourceRectangle(Rectangle sourceRectangle)
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
// Prepare command
properties.flags = ThumbnailFlags.RectSource;
properties.source = sourceRectangle;
try
{
// Native API call
DwmUpdateThumbnailProperties(handle, ref properties);
}
// If source or destination handles become invalid, the thumbnail handle
// will also become invalid and an ArgumentException will be thrown
catch (ArgumentException)
{
// Handle became invalid - set it to null
handle = IntPtr.Zero;
}
}
}
/// <summary>
/// Sets the rectangle on which the thumbnail will be drawn
/// </summary>
/// <param name="destinationRectangle">Rectangle on the destination form on which to draw
/// the thumbnail</param>
public void SetDestinationRectangle(Rectangle destinationRectangle)
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
// Prepare command
properties.flags = ThumbnailFlags.RectDestination;
properties.destination = destinationRectangle;
try
{
// Native API call
DwmUpdateThumbnailProperties(handle, ref properties);
}
catch (ArgumentException)
{
// Handle became invalid - set it to null
handle = IntPtr.Zero;
}
}
}
/// <summary>
/// Sets the opacity of the thumbnail
/// </summary>
/// <param name="opacity">Opacity value</param>
public void SetOpacity(byte opacity)
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
// Prepare command
properties.flags = ThumbnailFlags.Opacity;
properties.opacity = opacity;
try
{
// Native API call
DwmUpdateThumbnailProperties(handle, ref properties);
}
catch (ArgumentException)
{
// Handle became invalid - set it to null
handle = IntPtr.Zero;
}
}
}
/// <summary>
/// Sets the visiblity of the thumbnail
/// </summary>
/// <param name="visible">True to show the thumbnail, false to hide it</param>
public void SetVisible(bool visible)
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
// Prepare command
properties.flags = ThumbnailFlags.Visible;
properties.visible = visible;
try
{
// Native API call
DwmUpdateThumbnailProperties(handle, ref properties);
}
catch (ArgumentException)
{
// Handle became invalid - set it to null
handle = IntPtr.Zero;
}
}
}
/// <summary>
/// Sets the thumbnail to show only the client area of the source
/// </summary>
/// <param name="sourceClientAreaOnly">True to show only client area, false otherwise</param>
public void SetSourceClientAreaOnly(bool sourceClientAreaOnly)
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
// Prepare command
properties.flags = ThumbnailFlags.SourceClientAreaOnly;
properties.sourceClientAreaOnly = sourceClientAreaOnly;
try
{
// Native API call
DwmUpdateThumbnailProperties(handle, ref properties);
}
catch (ArgumentException)
{
// Handle became invalid - set it to null
handle = IntPtr.Zero;
}
}
}
// Unregister the thumbnail
private void UnRegisterThumbnail()
{
// Check if handle is valid
if (handle != IntPtr.Zero)
{
try
{
// Native API call
DwmUnregisterThumbnail(handle);
}
catch (ArgumentException)
{
}
handle = IntPtr.Zero;
}
}
/// <summary>
/// Dispose of the thumbnail
/// </summary>
public void Dispose()
{
// Unregister the thumbnail to free the handle
if (!this.disposed)
{
UnRegisterThumbnail();
}
disposed = true;
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose of the thumbnail and destroy the object
/// </summary>
~Thumbnail()
{
Dispose();
}
#region API imports
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmQueryThumbnailSourceSize(IntPtr hThumbnail, out Size size);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern IntPtr DwmRegisterThumbnail(IntPtr hwndDestination, IntPtr hwndSource);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmUnregisterThumbnail(IntPtr hThumbnail);
[DllImport("dwmapi.dll", PreserveSig = false)]
private static extern void DwmUpdateThumbnailProperties(IntPtr hThumbnailId, ref ThumbnailProperties ptnProperties);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using Excel.Core.Binary12Format;
using System.IO;
using Excel.Core;
using System.Data;
namespace Excel
{
public class ExcelBinary12Reader : IExcelDataReader
{
#region Members
private XlsbWorkbook _workbook;
private bool _isValid;
private bool _isClosed;
private bool _isFirstRead;
private string _exceptionMessage;
private int _depth;
private int _resultIndex;
private int _emptyRowCount;
private ZipWorker _zipWorker;
private Stream _sheetStream;
private object[] _cellsValues;
private object[] _savedCellsValues;
private bool disposed;
#endregion
internal ExcelBinary12Reader()
{
_isValid = true;
_isFirstRead = true;
}
private void ReadGlobals()
{
_workbook = new XlsbWorkbook(
_zipWorker.GetWorkbookStream(),
_zipWorker.GetSharedStringsStream(),
_zipWorker.GetStylesStream());
}
#region IExcelDataReader Members
public void Initialize(System.IO.Stream fileStream)
{
_zipWorker = new ZipWorker(true);
_zipWorker.Extract(fileStream);
if (!_zipWorker.IsValid)
{
_isValid = false;
_exceptionMessage = _zipWorker.ExceptionMessage;
Close();
return;
}
ReadGlobals();
}
public System.Data.DataSet AsDataSet()
{
return AsDataSet(false);
}
public System.Data.DataSet AsDataSet(bool convertOADateTime)
{
throw new Exception("The method or operation is not implemented.");
}
public bool IsValid
{
get { return _isValid; }
}
public string ExceptionMessage
{
get { return _exceptionMessage; }
}
public string Name
{
get
{
return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].Name : null;
}
}
public int ResultsCount
{
get { return _workbook == null ? -1 : _workbook.Sheets.Count; }
}
#endregion
#region IDataReader Members
public void Close()
{
_isClosed = true;
if (_sheetStream != null) _sheetStream.Close();
if (_zipWorker != null) _zipWorker.Dispose();
}
public int Depth
{
get { return _depth; }
}
public bool IsClosed
{
get { return _isClosed; }
}
public bool NextResult()
{
throw new Exception("The method or operation is not implemented.");
}
public bool Read()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
#region IDataRecord Members
public int FieldCount
{
get { return (_resultIndex >= 0 && _resultIndex < ResultsCount) ? _workbook.Sheets[_resultIndex].ColumnsCount : -1; }
}
public bool GetBoolean(int i)
{
if (IsDBNull(i)) return false;
return Boolean.Parse(_cellsValues[i].ToString());
}
public DateTime GetDateTime(int i)
{
if (IsDBNull(i)) return DateTime.MinValue;
try
{
return (DateTime)_cellsValues[i];
}
catch (InvalidCastException)
{
return DateTime.MinValue;
}
}
public decimal GetDecimal(int i)
{
if (IsDBNull(i)) return decimal.MinValue;
return decimal.Parse(_cellsValues[i].ToString());
}
public double GetDouble(int i)
{
if (IsDBNull(i)) return double.MinValue;
return double.Parse(_cellsValues[i].ToString());
}
public float GetFloat(int i)
{
if (IsDBNull(i)) return float.MinValue;
return float.Parse(_cellsValues[i].ToString());
}
public short GetInt16(int i)
{
if (IsDBNull(i)) return short.MinValue;
return short.Parse(_cellsValues[i].ToString());
}
public int GetInt32(int i)
{
if (IsDBNull(i)) return int.MinValue;
return int.Parse(_cellsValues[i].ToString());
}
public long GetInt64(int i)
{
if (IsDBNull(i)) return long.MinValue;
return long.Parse(_cellsValues[i].ToString());
}
public string GetString(int i)
{
if (IsDBNull(i)) return null;
return _cellsValues[i].ToString();
}
public object GetValue(int i)
{
return _cellsValues[i];
}
public bool IsDBNull(int i)
{
return (null == _cellsValues[i]) || (DBNull.Value == _cellsValues[i]);
}
public object this[int i]
{
get { return _cellsValues[i]; }
}
#endregion
#region IDisposable Members
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (!this.disposed)
{
if (disposing)
{
if (_zipWorker != null) _zipWorker.Dispose();
if (_sheetStream != null) _sheetStream.Close();
}
_zipWorker = null;
_sheetStream = null;
_workbook = null;
_cellsValues = null;
_savedCellsValues = null;
disposed = true;
}
}
~ExcelBinary12Reader()
{
Dispose(false);
}
#endregion
#region Not Supported IDataReader Members
public DataTable GetSchemaTable()
{
throw new NotSupportedException();
}
public int RecordsAffected
{
get { throw new NotSupportedException(); }
}
#endregion
#region Not Supported IDataRecord Members
public byte GetByte(int i)
{
throw new NotSupportedException();
}
public long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public char GetChar(int i)
{
throw new NotSupportedException();
}
public long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotSupportedException();
}
public IDataReader GetData(int i)
{
throw new NotSupportedException();
}
public string GetDataTypeName(int i)
{
throw new NotSupportedException();
}
public Type GetFieldType(int i)
{
throw new NotSupportedException();
}
public Guid GetGuid(int i)
{
throw new NotSupportedException();
}
public string GetName(int i)
{
throw new NotSupportedException();
}
public int GetOrdinal(string name)
{
throw new NotSupportedException();
}
public int GetValues(object[] values)
{
throw new NotSupportedException();
}
public object this[string name]
{
get { throw new NotSupportedException(); }
}
#endregion
#region IExcelDataReader Members
public bool IsFirstRowAsColumnNames
{
get
{
throw new Exception("The method or operation is not implemented.");
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetItemObjObjListDictionaryTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
ListDictionary ld;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] ListDictionary is constructed as expected
//-----------------------------------------------------------------
ld = new ListDictionary();
// [] set Item() on empty dictionary
//
cnt = ld.Count;
Assert.Throws<ArgumentNullException>(() => { ld[null] = "item"; });
cnt = ld.Count;
ld["some_string"] = "item";
if (ld.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add item"));
}
if (String.Compare(ld["some_string"].ToString(), "item") != 0)
{
Assert.False(true, string.Format("Error, failed to set item"));
}
cnt = ld.Count;
Hashtable lbl = new Hashtable();
ArrayList b = new ArrayList();
ld[lbl] = b;
if (ld.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add item"));
}
if (!ld[lbl].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set object-item"));
}
// [] set Item() on dictionary filled with simple strings
//
cnt = ld.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
ld.Add(keys[i], values[i]);
}
if (ld.Count != cnt + len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len));
}
//
for (int i = 0; i < len; i++)
{
if (!ld.Contains(keys[i]))
{
Assert.False(true, string.Format("Error, doesn't contain key", i));
}
ld[keys[i]] = "newValue" + i;
if (String.Compare(ld[keys[i]].ToString(), "newValue" + i) != 0)
{
Assert.False(true, string.Format("Error, failed to set value", i));
}
ld[keys[i]] = b;
if (!ld[keys[i]].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set object-value", i));
}
}
//
// Intl strings
// [] set Item() on dictionary filled with Intl strings
//
string[] intlValues = new string[len * 2 + 1];
// fill array with unique strings
//
for (int i = 0; i < len * 2 + 1; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLower() == intlValues[i].ToUpper())
caseInsensitive = true;
}
cnt = ld.Count;
for (int i = 0; i < len; i++)
{
ld.Add(intlValues[i + len], intlValues[i]);
}
if (ld.Count != (cnt + len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, cnt + len));
}
for (int i = 0; i < len; i++)
{
//
if (!ld.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, doesn't contain key", i));
}
ld[intlValues[i + len]] = intlValues[len * 2];
if (String.Compare(ld[intlValues[i + len]].ToString(), intlValues[len * 2]) != 0)
{
Assert.False(true, string.Format("Error, failed to set value", i));
}
ld[intlValues[i + len]] = b;
if (!ld[intlValues[i + len]].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set object-value", i));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpper();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLower();
}
ld.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
// uppercase key
if (!ld.Contains(intlValues[i + len]))
{
Assert.False(true, string.Format("Error, doesn't contain key", i));
}
ld[intlValues[i + len]] = b;
if (!ld[intlValues[i + len]].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set via uppercase key", i));
}
}
ld.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
ld.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
// LD is case-sensitive by default - new entries should be added
for (int i = 0; i < len; i++)
{
// lowercase key
cnt = ld.Count;
ld[intlValuesLower[i + len]] = "item";
if (ld[intlValuesLower[i + len]] == null)
{
Assert.False(true, string.Format("Error, failed: returned non-null for lowercase key", i));
}
if (!caseInsensitive && String.Compare(ld[intlValues[i + len]].ToString(), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, failed: changed value via lowercase key", i));
}
// lowercase itemshould be added to the dictionary
if (String.Compare(ld[intlValuesLower[i + len]].ToString(), "item") != 0)
{
Assert.False(true, string.Format("Error, failed: didn't add when set via lowercase key", i));
}
}
//
// [] set Item() on filled dictionary with case-insensitive comparer
ld = new ListDictionary(new InsensitiveComparer());
len = values.Length;
ld.Clear();
string kk = "key";
for (int i = 0; i < len; i++)
{
ld.Add(kk + i, values[i]);
}
if (ld.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, len));
}
for (int i = 0; i < len; i++)
{
if (ld[kk.ToUpper() + i] == null)
{
Assert.False(true, string.Format("Error, returned null for differently cased key", i));
}
else
{
ld[kk.ToUpper() + i] = "Item" + i;
if (String.Compare(ld[kk.ToUpper() + i].ToString(), "Item" + i) != 0)
{
Assert.False(true, string.Format("Error, failed to set value", i));
}
ld[kk.ToUpper() + i] = b;
if (!ld[kk.ToUpper() + i].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set object-value", i));
}
}
}
//
// [] set Item(null) on filled LD
//
ld = new ListDictionary();
cnt = ld.Count;
if (ld.Count < len)
{
ld.Clear();
for (int i = 0; i < len; i++)
{
ld.Add(keys[i], values[i]);
}
}
Assert.Throws<ArgumentNullException>(() => { ld[null] = "item"; });
// [] set Item(special_object)
//
ld = new ListDictionary();
ld.Clear();
b = new ArrayList();
ArrayList b1 = new ArrayList();
lbl = new Hashtable();
Hashtable lbl1 = new Hashtable();
ld.Add(lbl, b);
ld.Add(lbl1, b1);
if (ld.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", ld.Count, 2));
}
ld[lbl] = b1;
if (!ld[lbl].Equals(b1))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
ld[lbl1] = b;
if (!ld[lbl1].Equals(b))
{
Assert.False(true, string.Format("Error, failed to set special object"));
}
//
// [] set to null
//
ld = new ListDictionary();
cnt = ld.Count;
ld["null_key"] = null;
if (ld.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add entry"));
}
if (ld["null_key"] != null)
{
Assert.False(true, string.Format("Error, failed to add entry with null value"));
}
cnt = ld.Count;
ld.Add("key", "value");
if (ld.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, failed to add entry"));
}
cnt = ld.Count;
ld["key"] = null;
if (ld["key"] != null)
{
Assert.False(true, string.Format("Error, failed to set entry to null "));
}
}
}
}
| |
using System.Diagnostics;
using CoreAnimation;
using CoreGraphics;
namespace BLKFlexibleHeightBarDemo
{
public class BLKFlexibleHeightBarSubviewLayoutAttributes
{
CGRect _frame;
public CGRect Frame
{
get
{
return _frame;
}
set
{
SetFrame (value);
}
}
CGRect _bounds;
public CGRect Bounds
{
get
{
return _bounds;
}
set
{
SetBounds (value);
}
}
CGPoint _center;
public CGPoint Center
{
get
{
return _center;
}
set
{
SetCenter (value);
}
}
CGSize _size;
public CGSize Size
{
get
{
return _size;
}
set
{
SetSize (value);
}
}
CATransform3D _transform3D;
public CATransform3D Transform3D
{
get
{
return _transform3D;
}
set
{
SetTransform3D (value);
}
}
CGAffineTransform _transform;
public CGAffineTransform Transform
{
get
{
return _transform;
}
set
{
SetTransform (value);
}
}
public float Alpha
{
get;
set;
}
public int ZIndex
{
get;
set;
}
public bool Hidden
{
get;
set;
}
public BLKFlexibleHeightBarSubviewLayoutAttributes ()
{
_frame = CGRect.Empty;
_bounds = CGRect.Empty;
_center = CGPoint.Empty;
_size = CGSize.Empty;
_transform3D = CATransform3D.Identity;
_transform = CGAffineTransform.MakeIdentity ();
Alpha = 1f;
ZIndex = 0;
Hidden = false;
}
public BLKFlexibleHeightBarSubviewLayoutAttributes (BLKFlexibleHeightBarSubviewLayoutAttributes layoutAttributes)
{
_frame = layoutAttributes._frame;
_bounds = layoutAttributes._bounds;
_center = layoutAttributes._center;
_size = layoutAttributes._size;
_transform3D = layoutAttributes._transform3D;
_transform = layoutAttributes._transform;
Alpha = layoutAttributes.Alpha;
ZIndex = layoutAttributes.ZIndex;
Hidden = layoutAttributes.Hidden;
}
bool TransformsAreIdentity ()
{
return _transform.IsIdentity && _transform3D.IsIdentity;
}
void SetFrame (CGRect frame)
{
if (TransformsAreIdentity ())
{
_frame = frame;
}
_center = new CGPoint (frame.GetMidX (), frame.GetMidY ());
_size = new CGSize (_frame.Width, _frame.Height);
_bounds = new CGRect (_bounds.GetMinX (), _bounds.GetMinY (), _size.Width, _size.Height);
}
void SetBounds (CGRect bounds)
{
Debug.Assert (bounds.X == 0.0 && bounds.Y == 0.0, @"Bounds must be set with a (0,0) origin");
_bounds = bounds;
_size = new CGSize (_bounds.Width, _bounds.Height);
}
void SetCenter (CGPoint center)
{
_center = center;
if (TransformsAreIdentity ())
{
_frame = new CGRect (center.X - _bounds.GetMidX (), center.Y - _bounds.GetMidY (), _frame.Width, _frame.Height);
}
}
void SetSize (CGSize size)
{
_size = size;
if (TransformsAreIdentity ())
{
_frame = new CGRect (_frame.GetMinX (), _frame.GetMinY (), size.Width, size.Height);
}
_bounds = new CGRect (_bounds.GetMinX (), _bounds.GetMinY (), size.Width, size.Height);
}
void SetTransform3D (CATransform3D transform3D)
{
_transform3D = transform3D;
_transform = new CGAffineTransform (transform3D.m11, transform3D.m12, transform3D.m21, transform3D.m22, transform3D.m41, transform3D.m42);
if (!transform3D.IsIdentity)
{
_frame = CGRect.Empty;
}
}
void SetTransform (CGAffineTransform transform)
{
_transform = transform;
_transform3D = CATransform3D.MakeFromAffine (transform);
if (CGAffineTransform.MakeIdentity () != transform)
{
_frame = CGRect.Empty;
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="LibraryHelpers.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation.
// </copyright>
//-----------------------------------------------------------------------
namespace Microsoft.Isam.Esent.Interop
{
using System;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Isam.Esent.Interop.Implementation;
/// <summary>
/// Contains several helper functions that are useful in the test binary.
/// In particular, it contains functionality that is not available in
/// reduced-functionality environments (such as CoreClr).
/// </summary>
internal static class LibraryHelpers
{
/// <summary>Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
/// <filterpriority>1</filterpriority>
public static readonly char DirectorySeparatorChar = '\\';
/// <summary>Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization.</summary>
/// <filterpriority>1</filterpriority>
public static readonly char AltDirectorySeparatorChar = '/';
/// <summary>
/// Gets an ASCII encoder.
/// </summary>
public static Encoding EncodingASCII
{
get
{
#if MANAGEDESENT_ON_CORECLR
return SlowAsciiEncoding.Encoding;
#else
return Encoding.ASCII;
#endif
}
}
/// <summary>
/// Gets a new ASCII encoder. It's preferred to use EncodingASCII, but some applications (e.g. tests)
/// may want a different Encoding object.
/// </summary>
public static Encoding NewEncodingASCII
{
get
{
#if MANAGEDESENT_ON_CORECLR
return new SlowAsciiEncoding();
#else
return new ASCIIEncoding();
#endif
}
}
// This should be dead code when running on Core CLR; This is only called by
// GetIndexInfoFromIndexlist() when called on a pre-Win8 system, and Core CLR
// is only on Win8 anyway.
#if !MANAGEDESENT_ON_CORECLR
/// <summary>
/// Creates a CultureInfo object when given the LCID.
/// </summary>
/// <param name="lcid">
/// The lcid passed in.
/// </param>
/// <returns>
/// A CultureInfo object.
/// </returns>
public static CultureInfo CreateCultureInfoByLcid(int lcid)
{
return new CultureInfo(lcid);
}
#endif // !MANAGEDESENT_ON_CORECLR
/// <summary>
/// Allocates memory on the native heap.
/// </summary>
/// <returns>A pointer to native memory.</returns>
/// <param name="size">The size of the memory desired.</param>
public static IntPtr MarshalAllocHGlobal(int size)
{
#if MANAGEDESENT_ON_CORECLR && !MANAGEDESENT_ON_WSA
return Win32.NativeMethods.LocalAlloc(0, new UIntPtr((uint)size));
#else
return Marshal.AllocHGlobal(size);
#endif
}
/// <summary>
/// Frees memory that was allocated on the native heap.
/// </summary>
/// <param name="buffer">A pointer to native memory.</param>
public static void MarshalFreeHGlobal(IntPtr buffer)
{
#if MANAGEDESENT_ON_CORECLR && !MANAGEDESENT_ON_WSA
Win32.NativeMethods.LocalFree(buffer);
#else
Marshal.FreeHGlobal(buffer);
#endif
}
/// <summary>Copies the contents of a managed <see cref="T:System.String" /> into unmanaged memory.</summary>
/// <returns>The address, in unmanaged memory, to where the <paramref name="managedString" /> was copied, or 0 if <paramref name="managedString" /> is null.</returns>
/// <param name="managedString">A managed string to be copied.</param>
/// <exception cref="T:System.OutOfMemoryException">The method could not allocate enough native heap memory.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="managedString" /> parameter exceeds the maximum length allowed by the operating system.</exception>
public static IntPtr MarshalStringToHGlobalUni(string managedString)
{
#if MANAGEDESENT_ON_CORECLR && !MANAGEDESENT_ON_WSA
return MyStringToHGlobalUni(managedString);
#else
return Marshal.StringToHGlobalUni(managedString);
#endif
}
/// <summary>
/// Retrieves the managed ID of the current thread.
/// </summary>
/// <returns>The ID of the current thread.</returns>
public static int GetCurrentManagedThreadId()
{
#if MANAGEDESENT_ON_CORECLR
return Environment.CurrentManagedThreadId;
#else
return Thread.CurrentThread.ManagedThreadId;
#endif
}
/// <summary>
/// Cancels an <see cref="M:System.Threading.Thread.Abort(System.Object)"/> requested for the current thread.
/// </summary>
/// <exception cref="T:System.Threading.ThreadStateException">Abort was not invoked on the current thread. </exception><exception cref="T:System.Security.SecurityException">The caller does not have the required security permission for the current thread. </exception><filterpriority>2</filterpriority><PermissionSet><IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="ControlThread"/></PermissionSet>
public static void ThreadResetAbort()
{
#if MANAGEDESENT_ON_CORECLR
// Do nothing.
#else
Thread.ResetAbort();
#endif
}
// FUTURE-2013/12/16-martinc. It appears that all of this hacking for running on Core CLR may no longer be necessary.
// We initially ported to an early version of Core CLR that had a lot of functionality missing. By the time
// Windows Store Apps came out in Windows 8, many of these functions were added back.
#if MANAGEDESENT_ON_CORECLR && !MANAGEDESENT_ON_WSA
// System.Runtime.InteropServices.Marshal
/// <summary>Copies the contents of a managed <see cref="T:System.String" /> into unmanaged memory.</summary>
/// <returns>The address, in unmanaged memory, to where the <paramref name="managedString" /> was copied, or 0 if <paramref name="managedString" /> is null.</returns>
/// <param name="managedString">A managed string to be copied.</param>
/// <exception cref="T:System.OutOfMemoryException">The method could not allocate enough native heap memory.</exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="managedString" /> parameter exceeds the maximum length allowed by the operating system.</exception>
[SecurityCritical]
private static unsafe IntPtr MyStringToHGlobalUni(string managedString)
{
if (managedString == null)
{
return IntPtr.Zero;
}
int charCountWithNull = managedString.Length + 1;
int byteCount = charCountWithNull * sizeof(char);
if (byteCount < managedString.Length)
{
throw new ArgumentOutOfRangeException("managedString");
}
UIntPtr sizetdwBytes = new UIntPtr((uint)byteCount);
IntPtr rawBuffer = Win32.NativeMethods.LocalAlloc(0, sizetdwBytes);
if (rawBuffer == IntPtr.Zero)
{
throw new OutOfMemoryException();
}
fixed (char* sourcePointer = managedString)
{
byte* destPointer = (byte*)rawBuffer;
var unicodeEncoding = new System.Text.UnicodeEncoding();
int bytesWritten = unicodeEncoding.GetBytes(sourcePointer, charCountWithNull, destPointer, byteCount);
}
return rawBuffer;
}
#endif // MANAGEDESENT_ON_CORECLR && !MANAGEDESENT_ON_WSA
/// <summary>Returns a <see cref="T:System.DateTime" /> equivalent to the specified OLE Automation Date.</summary>
/// <returns>A <see cref="T:System.DateTime" /> that represents the same date and time as <paramref name="d" />.</returns>
/// <param name="d">An OLE Automation Date value. </param>
/// <exception cref="T:System.ArgumentException">The date is not a valid OLE Automation Date value. </exception>
/// <filterpriority>1</filterpriority>
public static DateTime FromOADate(double d)
{
#if MANAGEDESENT_ON_CORECLR
return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
#else
return DateTime.FromOADate(d);
#endif
}
#if MANAGEDESENT_ON_CORECLR
/// <summary>
/// Copied from the reflected implementation.
/// </summary>
/// <param name="value">The date, as a 64bit integer.</param>
/// <returns>The date, as a double representation.</returns>
internal static double TicksToOADate(long value)
{
if (value == 0L)
{
return 0.0;
}
if (value < 864000000000L)
{
value += 599264352000000000L;
}
if (value < 31241376000000000L)
{
throw new OverflowException();
}
long num = (value - 599264352000000000L) / 10000L;
if (num < 0L)
{
long num2 = num % 86400000L;
if (num2 != 0L)
{
num -= (86400000L + num2) * 2L;
}
}
return (double)num / 86400000.0;
}
/// <summary>
/// Copied from the reflected implementation.
/// </summary>
/// <param name="value">The date, as a double representation.</param>
/// <returns>The date, as a 64bit integer.</returns>
internal static long DoubleDateToTicks(double value)
{
if (value >= 2958466.0 || value <= -657435.0)
{
throw new ArgumentException("value does not represent a valid date", "value");
}
long num = (long)((value * 86400000.0) + ((value >= 0.0) ? 0.5 : -0.5));
if (num < 0L)
{
num -= (num % 86400000L) * 2L;
}
num += 59926435200000L;
if (num < 0L || num >= 315537897600000L)
{
throw new ArgumentException("value does not represent a valid date", "value");
}
return num * 10000L;
}
#endif
}
}
| |
using IntuiLab.Kinect.DataUserTracking.Events;
using Microsoft.Kinect;
using Microsoft.Kinect.Toolkit.Interaction;
using System;
using System.Collections.Generic;
using System.Drawing;
namespace IntuiLab.Kinect.DataUserTracking
{
/// <summary>
/// This classe permit to manage the data user in pointing mode.
/// It resume operation of the UserData class, but the the gestures recognizer engine enabled just the postures.
/// </summary>
internal class UserDataPointing : UserData, IDisposable
{
#region Fields
/// <summary>
/// User hands data
/// This dictionnary record the hand left and hand right data for an user
/// </summary>
private Dictionary<InteractionHandType, HandData> m_UserHandsData;
#endregion
#region Events
#region UserHandActive
/// <summary>
/// Event triggered when a hand became active
/// </summary>
public event EventHandler<HandActiveEventArgs> UserHandActive;
/// <summary>
/// Raise event UserHandActive
/// </summary>
protected void RaiseUserHandActive(object sender, HandActiveEventArgs e)
{
if (UserHandActive != null)
{
UserHandActive(this, e);
}
}
#endregion
#region UserHandMove
/// <summary>
/// Event triggered when a hand moved
/// </summary>
public event EventHandler<HandMoveEventArgs> UserHandMove;
/// <summary>
/// Raise event UserHandMove
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RaisUserHandMove(object sender, HandMoveEventArgs e)
{
if (UserHandMove != null)
{
UserHandMove(this, e);
}
}
#endregion
#region UserHandGripStateChanged
/// <summary>
/// Event triggered when a hand's grip state changed
/// </summary>
public event EventHandler<HandGripStateChangeEventArgs> UserHandGripStateChanged;
/// <summary>
/// Raise event UserHandGripStateChanged
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void RaisUserHandGripStateChnged(object sender, HandGripStateChangeEventArgs e)
{
if (UserHandGripStateChanged != null)
{
UserHandGripStateChanged(this, e);
}
}
#endregion
#endregion
#region Constructor
/// <summary>
/// Constructor
/// </summary>
/// <param name="userId">User ID</param>
/// <param name="refSkeleton">User Skeleton</param>
/// <param name="depth">User/Kinect sensor distance</param>
/// <param name="timesTamp">SkeletonFrame TimesTamp</param>
public UserDataPointing(int userId, Skeleton refSkeleton, double depth, long timesTamp)
: base(userId,refSkeleton,depth,timesTamp)
{
// Initialize the hand data for the user's hands
m_UserHandsData = new Dictionary<InteractionHandType, HandData>();
m_UserHandsData[InteractionHandType.Left] = new HandData(InteractionHandType.Left);
m_UserHandsData[InteractionHandType.Right] = new HandData(InteractionHandType.Right);
m_UserHandsData[InteractionHandType.Left].HandIsActive += OnUserHandActive;
m_UserHandsData[InteractionHandType.Right].HandIsActive += OnUserHandActive;
m_UserHandsData[InteractionHandType.Left].HandMove += OnUserHandMove;
m_UserHandsData[InteractionHandType.Right].HandMove += OnUserHandMove;
m_UserHandsData[InteractionHandType.Left].HandGripStateChanged += OnUserHandGripStateChanged;
m_UserHandsData[InteractionHandType.Right].HandGripStateChanged += OnUserHandGripStateChanged;
}
#endregion
#region Public Methods
/// <summary>
/// Update the data hands of the user
/// </summary>
/// <param name="userInfos">The datas for the hand left and right</param>
public void UpdateDataHands(UserInfo userInfos)
{
// get the hands datas
var hands = userInfos.HandPointers;
if (hands.Count != 0)
{
// for each hands, update the datas
foreach (var hand in hands)
{
m_UserHandsData[hand.HandType].UpdateHandData(new PointF((float)hand.X, (float)hand.Y), hand.HandEventType, hand.IsActive, hand.IsPrimaryForUser);
}
}
}
#endregion
#region Event Handler's
/// <summary>
/// Callback when a hand is active
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnUserHandActive(object sender, HandActiveEventArgs e)
{
RaiseUserHandActive(this, new HandActiveEventArgs
{
HandType = e.HandType,
IsActive = e.IsActive,
PositionOnScreen = e.PositionOnScreen,
userID = this.UserID
});
}
/// <summary>
/// Callback when a hand moved
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnUserHandMove(object sender, HandMoveEventArgs e)
{
RaisUserHandMove(this, new HandMoveEventArgs
{
HandType = e.HandType,
userID = this.UserID,
PositionOnScreen = e.PositionOnScreen,
RawPosition = e.RawPosition,
IsGrip = e.IsGrip
});
}
/// <summary>
/// Callback when the hand's grip state changed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnUserHandGripStateChanged(object sender, HandGripStateChangeEventArgs e)
{
RaisUserHandGripStateChnged(this, new HandGripStateChangeEventArgs
{
HandType = e.HandType,
userID = this.UserID,
IsGrip = e.IsGrip,
RawPosition = e.RawPosition
});
}
#endregion
#region IDisposable's members
/// <summary>
/// Dispose this instance.
/// </summary>
public void DisposeUserDataPointing()
{
m_UserHandsData[InteractionHandType.Left].HandIsActive -= OnUserHandActive;
m_UserHandsData[InteractionHandType.Right].HandIsActive -= OnUserHandActive;
m_UserHandsData[InteractionHandType.Left].HandMove -= OnUserHandMove;
m_UserHandsData[InteractionHandType.Right].HandMove -= OnUserHandMove;
m_UserHandsData[InteractionHandType.Left].HandGripStateChanged -= OnUserHandGripStateChanged;
m_UserHandsData[InteractionHandType.Right].HandGripStateChanged -= OnUserHandGripStateChanged;
// Call the dispose to the UserData class.
base.Dispose();
}
#endregion
}
}
| |
namespace System.IO.Compression2
{
using System;
using System.Diagnostics;
internal class FastEncoderWindow
{
private byte[] window; // complete bytes window
private int bufPos; // the start index of uncompressed bytes
private int bufEnd; // the end index of uncompressed bytes
// Be very careful about increasing the window size; the code tables will have to
// be updated, since they assume that extra_distance_bits is never larger than a
// certain size.
private const int FastEncoderHashShift = 4;
private const int FastEncoderHashtableSize = 2048;
private const int FastEncoderHashMask = FastEncoderHashtableSize - 1;
private const int FastEncoderWindowSize = 8192;
private const int FastEncoderWindowMask = FastEncoderWindowSize - 1;
private const int FastEncoderMatch3DistThreshold = 16384;
internal const int MaxMatch = 258;
internal const int MinMatch = 3;
// Following constants affect the search,
// they should be modifiable if we support different compression levels in future.
private const int SearchDepth = 32;
private const int GoodLength = 4;
private const int NiceLength = 32;
private const int LazyMatchThreshold = 6;
// Hashtable structure
private ushort[] prev; // next most recent occurance of chars with same hash value
private ushort[] lookup; // hash table to find most recent occurance of chars with same hash value
public FastEncoderWindow()
{
ResetWindow();
}
public int BytesAvailable
{ // uncompressed bytes
get
{
Debug.Assert(bufEnd - bufPos >= 0, "Ending pointer can't be in front of starting pointer!");
return bufEnd - bufPos;
}
}
public DeflateInput UnprocessedInput
{
get
{
DeflateInput input = new DeflateInput();
input.Buffer = window;
input.StartIndex = bufPos;
input.Count = bufEnd - bufPos;
return input;
}
}
public void FlushWindow()
{
ResetWindow();
}
private void ResetWindow()
{
window = new byte[2 * FastEncoderWindowSize + MaxMatch + 4];
prev = new ushort[FastEncoderWindowSize + MaxMatch];
lookup = new ushort[FastEncoderHashtableSize];
bufPos = FastEncoderWindowSize;
bufEnd = bufPos;
}
public int FreeWindowSpace
{ // Free space in the window
get
{
return 2 * FastEncoderWindowSize - bufEnd;
}
}
// copy bytes from input buffer into window
public void CopyBytes(byte[] inputBuffer, int startIndex, int count)
{
Array.Copy(inputBuffer, startIndex, window, bufEnd, count);
bufEnd += count;
}
// slide the history window to the left by FastEncoderWindowSize bytes
public void MoveWindows()
{
int i;
Debug.Assert(bufPos == 2 * FastEncoderWindowSize, "only call this at the end of the window");
// verify that the hash table is correct
VerifyHashes(); // Debug only code
Array.Copy(window, bufPos - FastEncoderWindowSize, window, 0, FastEncoderWindowSize);
// move all the hash pointers back
for (i = 0; i < FastEncoderHashtableSize; i++)
{
int val = ((int)lookup[i]) - FastEncoderWindowSize;
if (val <= 0)
{ // too far away now? then set to zero
lookup[i] = (ushort)0;
}
else
{
lookup[i] = (ushort)val;
}
}
// prev[]'s are absolute pointers, not relative pointers, so we have to move them back too
// making prev[]'s into relative pointers poses problems of its own
for (i = 0; i < FastEncoderWindowSize; i++)
{
long val = ((long)prev[i]) - FastEncoderWindowSize;
if (val <= 0)
{
prev[i] = (ushort)0;
}
else
{
prev[i] = (ushort)val;
}
}
#if DEBUG
// For debugging, wipe the window clean, so that if there is a bug in our hashing,
// the hash pointers will now point to locations which are not valid for the hash value
// (and will be caught by our ASSERTs).
Array.Clear(window, FastEncoderWindowSize, window.Length - FastEncoderWindowSize);
#endif
VerifyHashes(); // debug: verify hash table is correct
bufPos = FastEncoderWindowSize;
bufEnd = bufPos;
}
private uint HashValue(uint hash, byte b)
{
return (hash << FastEncoderHashShift) ^ b;
}
// insert string into hash table and return most recent location of same hash value
private uint InsertString(ref uint hash)
{
// Note we only use the lowest 11 bits of the hash vallue (hash table size is 11).
// This enables fast calculation of hash value for the input string.
// If we want to get the next hash code starting at next position,
// we can just increment bufPos and call this function.
hash = HashValue(hash, window[bufPos + 2]);
// Need to assert the hash value
uint search = lookup[hash & FastEncoderHashMask];
lookup[hash & FastEncoderHashMask] = (ushort)bufPos;
prev[bufPos & FastEncoderWindowMask] = (ushort)search;
return search;
}
//
// insert strings into hashtable
// Arguments:
// hash : intial hash value
// matchLen : 1 + number of strings we need to insert.
//
private void InsertStrings(ref uint hash, int matchLen)
{
Debug.Assert(matchLen > 0, "Invalid match Len!");
if (bufEnd - bufPos <= matchLen)
{
bufPos += (matchLen - 1);
}
else
{
while (--matchLen > 0)
{
InsertString(ref hash);
bufPos++;
}
}
}
//
// Find out what we should generate next. It can be a symbol, a distance/length pair
// or a symbol followed by distance/length pair
//
internal bool GetNextSymbolOrMatch(Match match)
{
Debug.Assert(bufPos >= FastEncoderWindowSize && bufPos < (2 * FastEncoderWindowSize), "Invalid Buffer Position!");
// initialise the value of the hash, no problem if locations bufPos, bufPos+1
// are invalid (not enough data), since we will never insert using that hash value
uint hash = HashValue(0, window[bufPos]);
hash = HashValue(hash, window[bufPos + 1]);
int matchLen;
int matchPos = 0;
VerifyHashes(); // Debug only code
if (bufEnd - bufPos <= 3)
{
// The hash value becomes corrupt when we get within 3 characters of the end of the
// input window, since the hash value is based on 3 characters. We just stop
// inserting into the hash table at this point, and allow no matches.
matchLen = 0;
}
else
{
// insert string into hash table and return most recent location of same hash value
int search = (int)InsertString(ref hash);
// did we find a recent location of this hash value?
if (search != 0)
{
// yes, now find a match at what we'll call position X
matchLen = FindMatch(search, out matchPos, SearchDepth, NiceLength);
// truncate match if we're too close to the end of the input window
if (bufPos + matchLen > bufEnd)
{
matchLen = bufEnd - bufPos;
}
}
else
{
// no most recent location found
matchLen = 0;
}
}
if (matchLen < MinMatch)
{
// didn't find a match, so output unmatched char
match.State = MatchState.HasSymbol;
match.Symbol = window[bufPos];
bufPos++;
}
else
{
// bufPos now points to X+1
bufPos++;
// is this match so good (long) that we should take it automatically without
// checking X+1 ?
if (matchLen <= LazyMatchThreshold)
{
int nextMatchLen;
int nextMatchPos = 0;
// search at position X+1
int search = (int)InsertString(ref hash);
// no, so check for a better match at X+1
if (search != 0)
{
nextMatchLen = FindMatch(search, out nextMatchPos,
matchLen < GoodLength ? SearchDepth : (SearchDepth >> 2), NiceLength);
// truncate match if we're too close to the end of the window
// note: nextMatchLen could now be < MinMatch
if (bufPos + nextMatchLen > bufEnd)
{
nextMatchLen = bufEnd - bufPos;
}
}
else
{
nextMatchLen = 0;
}
// right now X and X+1 are both inserted into the search tree
if (nextMatchLen > matchLen)
{
// since nextMatchLen > matchLen, it can't be < MinMatch here
// match at X+1 is better, so output unmatched char at X
match.State = MatchState.HasSymbolAndMatch;
match.Symbol = window[bufPos - 1];
match.Position = nextMatchPos;
match.Length = nextMatchLen;
// insert remainder of second match into search tree
// example: (*=inserted already)
//
// X X+1 X+2 X+3 X+4
// * *
// nextmatchlen=3
// bufPos
//
// If nextMatchLen == 3, we want to perform 2
// insertions (at X+2 and X+3). However, first we must
// inc bufPos.
//
bufPos++; // now points to X+2
matchLen = nextMatchLen;
InsertStrings(ref hash, matchLen);
}
else
{
// match at X is better, so take it
match.State = MatchState.HasMatch;
match.Position = matchPos;
match.Length = matchLen;
// Insert remainder of first match into search tree, minus the first
// two locations, which were inserted by the FindMatch() calls.
//
// For example, if matchLen == 3, then we've inserted at X and X+1
// already (and bufPos is now pointing at X+1), and now we need to insert
// only at X+2.
//
matchLen--;
bufPos++; // now bufPos points to X+2
InsertStrings(ref hash, matchLen);
}
}
else
{ // match_length >= good_match
// in assertion: bufPos points to X+1, location X inserted already
// first match is so good that we're not even going to check at X+1
match.State = MatchState.HasMatch;
match.Position = matchPos;
match.Length = matchLen;
// insert remainder of match at X into search tree
InsertStrings(ref hash, matchLen);
}
}
if (bufPos == 2 * FastEncoderWindowSize)
{
MoveWindows();
}
return true;
}
//
// Find a match starting at specified position and return length of match
// Arguments:
// search : where to start searching
// matchPos : return match position here
// searchDepth : # links to traverse
// NiceLength : stop immediately if we find a match >= NiceLength
//
private int FindMatch(int search, out int matchPos, int searchDepth, int niceLength)
{
Debug.Assert(bufPos >= 0 && bufPos < 2 * FastEncoderWindowSize, "Invalid Buffer position!");
Debug.Assert(search < bufPos, "Invalid starting search point!");
Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos));
int bestMatch = 0; // best match length found so far
int bestMatchPos = 0; // absolute match position of best match found
// the earliest we can look
int earliest = bufPos - FastEncoderWindowSize;
Debug.Assert(earliest >= 0, "bufPos is less than FastEncoderWindowSize!");
byte wantChar = window[bufPos];
while (search > earliest)
{
// make sure all our hash links are valid
Debug.Assert(RecalculateHash((int)search) == RecalculateHash(bufPos), "Corrupted hash link!");
// Start by checking the character that would allow us to increase the match
// length by one. This improves performance quite a bit.
if (window[search + bestMatch] == wantChar)
{
int j;
// Now make sure that all the other characters are correct
for (j = 0; j < MaxMatch; j++)
{
if (window[bufPos + j] != window[search + j])
{
break;
}
}
if (j > bestMatch)
{
bestMatch = j;
bestMatchPos = search; // absolute position
if (j > NiceLength)
{
break;
}
wantChar = window[bufPos + j];
}
}
if (--searchDepth == 0)
{
break;
}
Debug.Assert(prev[search & FastEncoderWindowMask] < search, "we should always go backwards!");
search = prev[search & FastEncoderWindowMask];
}
// doesn't necessarily mean we found a match; bestMatch could be > 0 and < MinMatch
matchPos = bufPos - bestMatchPos - 1; // convert absolute to relative position
// don't allow match length 3's which are too far away to be worthwhile
if (bestMatch == 3 && matchPos >= FastEncoderMatch3DistThreshold)
{
return 0;
}
Debug.Assert(bestMatch < MinMatch || matchPos < FastEncoderWindowSize, "Only find match inside FastEncoderWindowSize");
return bestMatch;
}
[Conditional("DEBUG")]
private void VerifyHashes()
{
for (int i = 0; i < FastEncoderHashtableSize; i++)
{
ushort where = lookup[i];
ushort nextWhere;
while (where != 0 && bufPos - where < FastEncoderWindowSize)
{
Debug.Assert(RecalculateHash(where) == i, "Incorrect Hashcode!");
nextWhere = prev[where & FastEncoderWindowMask];
if (bufPos - nextWhere >= FastEncoderWindowSize)
{
break;
}
Debug.Assert(nextWhere < where, "pointer is messed up!");
where = nextWhere;
}
}
}
// can't use conditional attribute here.
private uint RecalculateHash(int position)
{
return (uint)(((window[position] << (2 * FastEncoderHashShift)) ^
(window[position + 1] << FastEncoderHashShift) ^
(window[position + 2])) & FastEncoderHashMask);
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// 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 System.IO;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
namespace Mono.Cecil.Mdb {
public sealed class MdbReaderProvider : ISymbolReaderProvider {
public ISymbolReader GetSymbolReader (ModuleDefinition module, string fileName)
{
Mixin.CheckModule (module);
Mixin.CheckFileName (fileName);
return new MdbReader (module, MonoSymbolFile.ReadSymbolFile (Mixin.GetMdbFileName (fileName), module.Mvid));
}
public ISymbolReader GetSymbolReader (ModuleDefinition module, Stream symbolStream)
{
Mixin.CheckModule (module);
Mixin.CheckStream (symbolStream);
var file = MonoSymbolFile.ReadSymbolFile (symbolStream);
if (module.Mvid != file.Guid) {
var file_stream = symbolStream as FileStream;
if (file_stream != null)
throw new MonoSymbolFileException ("Symbol file `{0}' does not match assembly", file_stream.Name);
throw new MonoSymbolFileException ("Symbol file from stream does not match assembly");
}
return new MdbReader (module, file);
}
}
public sealed class MdbReader : ISymbolReader {
readonly ModuleDefinition module;
readonly MonoSymbolFile symbol_file;
readonly Dictionary<string, Document> documents;
public MdbReader (ModuleDefinition module, MonoSymbolFile symFile)
{
this.module = module;
this.symbol_file = symFile;
this.documents = new Dictionary<string, Document> ();
}
#if !READ_ONLY
public ISymbolWriterProvider GetWriterProvider ()
{
return new MdbWriterProvider ();
}
#endif
public bool ProcessDebugHeader (ImageDebugHeader header)
{
return symbol_file.Guid == module.Mvid;
}
public MethodDebugInformation Read (MethodDefinition method)
{
var method_token = method.MetadataToken;
var entry = symbol_file.GetMethodByToken (method_token.ToInt32 ());
if (entry == null)
return null;
var info = new MethodDebugInformation (method);
info.code_size = ReadCodeSize (method);
var scopes = ReadScopes (entry, info);
ReadLineNumbers (entry, info);
ReadLocalVariables (entry, scopes);
return info;
}
static int ReadCodeSize (MethodDefinition method)
{
return method.Module.Read (method, (m, reader) => reader.ReadCodeSize (m));
}
static void ReadLocalVariables (MethodEntry entry, ScopeDebugInformation [] scopes)
{
var locals = entry.GetLocals ();
foreach (var local in locals) {
var variable = new VariableDebugInformation (local.Index, local.Name);
var index = local.BlockIndex;
if (index < 0 || index >= scopes.Length)
continue;
var scope = scopes [index];
if (scope == null)
continue;
scope.Variables.Add (variable);
}
}
void ReadLineNumbers (MethodEntry entry, MethodDebugInformation info)
{
var table = entry.GetLineNumberTable ();
info.sequence_points = new Collection<SequencePoint> (table.LineNumbers.Length);
for (var i = 0; i < table.LineNumbers.Length; i++) {
var line = table.LineNumbers [i];
if (i > 0 && table.LineNumbers [i - 1].Offset == line.Offset)
continue;
info.sequence_points.Add (LineToSequencePoint (line));
}
}
Document GetDocument (SourceFileEntry file)
{
var file_name = file.FileName;
Document document;
if (documents.TryGetValue (file_name, out document))
return document;
document = new Document (file_name) {
Hash = file.Checksum,
};
documents.Add (file_name, document);
return document;
}
static ScopeDebugInformation [] ReadScopes (MethodEntry entry, MethodDebugInformation info)
{
var blocks = entry.GetCodeBlocks ();
var scopes = new ScopeDebugInformation [blocks.Length + 1];
info.scope = scopes [0] = new ScopeDebugInformation {
Start = new InstructionOffset (0),
End = new InstructionOffset (info.code_size),
};
foreach (var block in blocks) {
if (block.BlockType != CodeBlockEntry.Type.Lexical && block.BlockType != CodeBlockEntry.Type.CompilerGenerated)
continue;
var scope = new ScopeDebugInformation ();
scope.Start = new InstructionOffset (block.StartOffset);
scope.End = new InstructionOffset (block.EndOffset);
scopes [block.Index + 1] = scope;
if (!AddScope (info.scope.Scopes, scope))
info.scope.Scopes.Add (scope);
}
return scopes;
}
static bool AddScope (Collection<ScopeDebugInformation> scopes, ScopeDebugInformation scope)
{
foreach (var sub_scope in scopes) {
if (sub_scope.HasScopes && AddScope (sub_scope.Scopes, scope))
return true;
if (scope.Start.Offset >= sub_scope.Start.Offset && scope.End.Offset <= sub_scope.End.Offset) {
sub_scope.Scopes.Add (scope);
return true;
}
}
return false;
}
SequencePoint LineToSequencePoint (LineNumberEntry line)
{
var source = symbol_file.GetSourceFile (line.File);
return new SequencePoint (line.Offset, GetDocument (source)) {
StartLine = line.Row,
EndLine = line.EndRow,
StartColumn = line.Column,
EndColumn = line.EndColumn,
};
}
public void Dispose ()
{
symbol_file.Dispose ();
}
}
static class MethodEntryExtensions {
public static bool HasColumnInfo (this MethodEntry entry)
{
return (entry.MethodFlags & MethodEntry.Flags.ColumnsInfoIncluded) != 0;
}
public static bool HasEndInfo (this MethodEntry entry)
{
return (entry.MethodFlags & MethodEntry.Flags.EndInfoIncluded) != 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ExpressRouteCircuitsOperations operations.
/// </summary>
public partial interface IExpressRouteCircuitsOperations
{
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets information about the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuit>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuit>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised ARP table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsArpTableListResult>> ListArpTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised routes table associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableListResult>> ListRoutesTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised routes table summary associated with
/// the express route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableSummaryListResult>> ListRoutesTableSummaryWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the stats from an express route circuit in a resource
/// group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitStats>> GetStatsWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all stats from an express route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitStats>> GetPeeringStatsWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates an express route circuit.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the circuit.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update express route circuit
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuit>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised ARP table associated with the express
/// route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsArpTableListResult>> BeginListArpTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised routes table associated with the
/// express route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableListResult>> BeginListRoutesTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the currently advertised routes table summary associated with
/// the express route circuit in a resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='circuitName'>
/// The name of the express route circuit.
/// </param>
/// <param name='peeringName'>
/// The name of the peering.
/// </param>
/// <param name='devicePath'>
/// The path of the device.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableSummaryListResult>> BeginListRoutesTableSummaryWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the express route circuits in a resource group.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets all the express route circuits in a subscription.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Xml;
namespace StrumpyShaderEditor
{
public class NodeEditor : EditorWindow
{
private Vector3 _currentMousePosition = Vector3.zero;
public OutputChannelReference SelectedOutputChannel { set; private get; }
public InputChannelReference SelectedInputChannel { set; private get; }
private ShaderGraph _nextGraph;
private ShaderGraph _selectedGraph;
private readonly List<Type> _serializableTypes = new List<Type>();
private readonly string _shaderEditorResourceDir;
private readonly string _autosavePath;
private readonly string _internalTempDir;
private readonly string _internalTempUnityPath;
private readonly string _tempShaderPathFull;
private readonly string _shaderTemplatePath;
private readonly string _graphsDir;
private readonly PopupMenu _popupMenu;
private const string TempShaderName = "TempShader";
private Node _selectedNode;
private Node NextSelectedNode;
private GraphHistory _undoChain;
private SubGraphType _currentSubGraphType = SubGraphType.Pixel;
private PreviewWindowInternal _previewWindow;
private bool _shouldOpenPreviewWindow = true;
protected NodeEditor( )
{
_shaderEditorResourceDir = Application.dataPath
+ Path.DirectorySeparatorChar
+ "StrumpyShaderEditor"
+ Path.DirectorySeparatorChar
+ "Editor"
+ Path.DirectorySeparatorChar
+ "Resources"
+ Path.DirectorySeparatorChar;
_internalTempDir = "Internal"
+ Path.DirectorySeparatorChar
+ "Temp"
+ Path.DirectorySeparatorChar;
_internalTempUnityPath = "Internal/Temp/";
_autosavePath = _shaderEditorResourceDir
+ _internalTempDir
+ "autosave.sgraph";
_tempShaderPathFull = _shaderEditorResourceDir
+ _internalTempDir
+ TempShaderName + ".shader";
_shaderTemplatePath = _shaderEditorResourceDir
+ "Internal"
+ Path.DirectorySeparatorChar
+ "ShaderTemplate.template";
_graphsDir = _shaderEditorResourceDir
+ "Public"
+ Path.DirectorySeparatorChar
+ "Graphs";
_selectedGraph = new ShaderGraph();
_popupMenu = new PopupMenu( );
//Find all the nodes that exist in the assembly (for submission to popup menu)
var types = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes());
foreach (var type in types)
{
foreach (var attribute in Attribute.GetCustomAttributes(type).OfType<NodeMetaData>())
{
NodeMetaData attribute2 = attribute;
_popupMenu.AddItem( new ExecutableMenuItem( attribute.Category, attribute.DisplayName,
delegate( Vector2 location ){
var toAdd = Activator.CreateInstance(attribute2.NodeType) as Node;
if (toAdd == null)
{
return;
}
_selectedGraph.CurrentSubGraph.AddNode(toAdd);
toAdd.NodePositionInGraph = new EditorRect( location.x, location.y, 10f, 10f);
MarkDirty();
}, String.IsNullOrEmpty(attribute.Descriptor) ? "" : attribute.Descriptor ) );
}
}
_popupMenu.SortMenu();
//Find all the serializable types
_serializableTypes.Clear();
foreach (var type in types)
{
var typeAttributes = Attribute.GetCustomAttributes(type);
foreach (var attribute in typeAttributes)
{
if (attribute is DataContractAttribute)
{
_serializableTypes.Add(type);
}
}
}
//Finally load the last graph
LoadLastGraph();
_selectedGraph.Initialize( new Rect( 0,0, Screen.width, Screen.height ), true );
_undoChain = new GraphHistory( _serializableTypes );
_shouldOpenPreviewWindow = true;
}
public void OnLostFocus()
{
_doingSelectBox = false;
SelectedInputChannel = null;
SelectedOutputChannel = null;
}
public ShaderGraph CurrentGraph
{
get{ return _selectedGraph; }
}
private void MarkDirty()
{
_selectedGraph.MarkDirty();
//Add an undo layer here
CacheLastGraph();
_undoChain.AddUndoLevel( _selectedGraph );
}
private bool _shouldUpdateShader;
public void UpdateShader()
{
_shouldUpdateShader = true;
}
public bool ShaderNeedsUpdate()
{
return _graphNeedsUpdate;
}
//State variables
private bool _shouldExportShader;
private bool _shouldSaveGraph;
private bool _shouldLoadGraph;
private bool _isPlayingInEditor;
private bool _markDirtyOnLoad;
private bool _quickSaving;
private string _lastGraphPath;
private bool _quickExport;
private string _lastExportPath;
private string _overrideLoadPath;
private static bool PreviewSupported()
{
return SystemInfo.supportsRenderTextures && SystemInfo.SupportsRenderTextureFormat( RenderTextureFormat.ARGB32 );
}
private void DisablePreview()
{
if( _previewWindow != null )
{
_previewWindow.ShouldUpdate = false;
_previewWindow.Close();
_previewWindow = null;
}
}
public void OnDisable()
{
CacheLastGraph();
DisablePreview();
}
public void Update()
{
wantsMouseMove = true;
//Need to force recreate the preview window if transitioning from
//game to editor or back
if( _isPlayingInEditor != EditorApplication.isPlaying )
{
DisablePreview();
_shouldOpenPreviewWindow = true;
_isPlayingInEditor = EditorApplication.isPlaying;
}
if( _shouldOpenPreviewWindow && PreviewSupported() )
{
//Find the preview window
var types = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany(s => s.GetTypes());
var previewWindowType = types.FirstOrDefault( x => x.FullName == "StrumpyPreviewWindow" );
if( previewWindowType != null )
{
_previewWindow = GetWindow( previewWindowType, true, "Preview" ) as PreviewWindowInternal;
if (_previewWindow != null)
{
_previewWindow.Initialize(this);
_previewWindow.wantsMouseMove = true;
_previewWindow.ShouldUpdate = true;
_shouldOpenPreviewWindow = false;
}
}
}
//Update preview
if (_shouldUpdateShader)
{
if (_selectedGraph.IsGraphValid())
{
File.WriteAllText(_tempShaderPathFull, _selectedGraph.GetShader(_shaderTemplatePath, true));
var currentShader = Resources.Load(_internalTempUnityPath + TempShaderName) as Shader;
var path = AssetDatabase.GetAssetPath(currentShader);
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
if( _previewWindow != null )
_previewWindow.PreviewMaterial = new Material(currentShader);
_graphNeedsUpdate = false;
InstructionCounter.CountInstructions(); // Update the instruction count
CacheCount(); // Solve the tooltip (Cached)
}
else
{
EditorUtility.DisplayDialog("Save Shader Error", "Cannot update shader, there are errors in the graph", "Ok");
}
_shouldUpdateShader = false;
}
//Save graph
if (_shouldSaveGraph)
{
var path = _quickSaving ? _lastGraphPath : EditorUtility.SaveFilePanel("Save shader graph to file...", _graphsDir, "shader.sgraph", "sgraph");
if (!string.IsNullOrEmpty(path))
{
var writer = new FileStream(path, FileMode.Create);
var ser = new DataContractSerializer(typeof (ShaderGraph), _serializableTypes, int.MaxValue, false, false, null);
ser.WriteObject(writer, _selectedGraph);
writer.Close();
_lastGraphPath = path;
}
_shouldSaveGraph = false;
_quickSaving = false;
}
//Load graph
if( _shouldLoadGraph )
{
var loadDir = _graphsDir;
if(!String.IsNullOrEmpty(_lastGraphPath))
loadDir = _lastGraphPath;
var path = string.IsNullOrEmpty(_overrideLoadPath) ? EditorUtility.OpenFilePanel("Load shader graph...", loadDir, "sgraph") : _overrideLoadPath;
bool didLoad = false;
if (!string.IsNullOrEmpty(path))
{
try
{
using( var fs = new FileStream(path, FileMode.Open) )
{
using( var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()) )
{
var ser = new DataContractSerializer(typeof (ShaderGraph), _serializableTypes, int.MaxValue, false, false, null);
var loaded = ser.ReadObject(reader, true) as ShaderGraph;
if (loaded != null)
{
_undoChain = new GraphHistory( _serializableTypes );
_nextGraph = loaded;
loaded.Initialize( new Rect(0, 0, Screen.width, Screen.height), true);
_lastGraphPath = path;
_lastExportPath = "";
didLoad = true;
}
}
}
}
catch( Exception e ){
Debug.Log( e );
}
//Try loading autosave graph (it's in a differnt xml format)
try
{
if( !didLoad )
{
using( var fs = new FileStream(path, FileMode.Open) )
{
using( var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas()) )
{
var ser = new DataContractSerializer(typeof(AutoSaveGraph), _serializableTypes, int.MaxValue, false, false, null);
var loaded = ser.ReadObject(reader, true) as AutoSaveGraph;
if (loaded != null)
{
_undoChain = new GraphHistory( _serializableTypes );
_nextGraph = loaded.Graph;
_nextGraph.Initialize( new Rect(0, 0, Screen.width, Screen.height), true);
_lastGraphPath = "";
_lastExportPath = "";
didLoad = true;
}
}
}
}
}
catch( Exception e)
{
Debug.Log(e);
}
if( !didLoad )
{
EditorUtility.DisplayDialog("Load Shader Error", "Could not load shader", "Ok");
}
}
_shouldLoadGraph = false;
_shouldUpdateShader = true;
_overrideLoadPath = "";
}
//Export the shader to a .shader file
if (_shouldExportShader)
{
if (_selectedGraph.IsGraphValid())
{
var path = _quickExport ? _lastExportPath : EditorUtility.SaveFilePanel("Export shader to file...", Application.dataPath, "shader.shader", "shader");
_lastExportPath = path; // For quick exporting - Texel
if (!string.IsNullOrEmpty(path))
{
File.WriteAllText(path, _selectedGraph.GetShader(_shaderTemplatePath, false));
AssetDatabase.Refresh(); // Investigate if this is optimal
}
InstructionCounter.CountInstructions(); // Update the instruction count
CacheCount(); // Solve the tooltip (Cached)
}
else
{
EditorUtility.DisplayDialog("Export Shader Error", "Cannot export shader, there are errors in the graph", "Ok");
}
_shouldExportShader = false;
_quickExport = false;
}
Repaint();
}
/* Autosave structure */
[DataContract(Namespace = "http://strumpy.net/ShaderEditor/")]
private class AutoSaveGraph
{
[DataMember]
public ShaderGraph Graph;
[DataMember]
public string ExportPath;
[DataMember]
public string SavePath;
}
//Create an 'autosave' of the last graph
public void CacheLastGraph()
{
if (!Directory.Exists(Application.dataPath))
{
Directory.CreateDirectory(Application.dataPath);
}
var toSave = new AutoSaveGraph
{
Graph = _selectedGraph,
ExportPath = _lastExportPath,
SavePath = _lastGraphPath
};
var writer = new FileStream(_autosavePath, FileMode.Create);
var ser = new DataContractSerializer(typeof(AutoSaveGraph), _serializableTypes, int.MaxValue, false, false, null);
ser.WriteObject(writer, toSave);
writer.Close();
}
//Load the last 'autosave' graph
private void LoadLastGraph()
{
var fi = new FileInfo(_autosavePath);
if (fi.Exists)
{
try{
var fs = fi.OpenRead();
var reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
var ser = new DataContractSerializer(typeof(AutoSaveGraph), _serializableTypes, int.MaxValue, false, false, null);
var loaded = ser.ReadObject(reader, true) as AutoSaveGraph;
if (loaded != null)
{
_nextGraph = loaded.Graph;
if( !string.IsNullOrEmpty( loaded.ExportPath ) && File.Exists( loaded.ExportPath ) )
_lastExportPath = loaded.ExportPath;
if( !string.IsNullOrEmpty( loaded.SavePath ) && File.Exists( loaded.SavePath ) )
_lastGraphPath = loaded.SavePath;
_nextGraph.Initialize( new Rect( 0, 0, Screen.width, Screen.height ), true);
_markDirtyOnLoad = true;
}
reader.Close();
fs.Close();
}
catch( Exception e )
{
Debug.Log( e );
EditorUtility.DisplayDialog("Load Shader Error", "Could not load shader", "Ok");
}
}
}
//Build a list of how many instructions the last compiled shader uses.
private bool _isInstructionCountCached = false;
private string _instructionCountDetails;
private string _instructionCountTooltip;
private void CacheCount() {
var count = "Instruction Count: \n";
count += "ALU: ";
count += InstructionCounter.lastCount.GL.ALU < 0 ? "N/A" : InstructionCounter.lastCount.GL.ALU.ToString();
count += "\n";
count += "TEX: ";
count += InstructionCounter.lastCount.GL.TEX < 0 ? "N/A" : InstructionCounter.lastCount.GL.TEX.ToString();
_instructionCountDetails = count;
var verbose = "GL: ";
verbose += "\nALU: ";
verbose += InstructionCounter.lastCount.GL.ALU < 0 ? "N/A" : InstructionCounter.lastCount.GL.ALU.ToString();
verbose += " V_ALU: ";
verbose += InstructionCounter.lastCount.GL.ALU < 0 ? "N/A" : InstructionCounter.lastCount.GL.V_ALU.ToString();
verbose += " TEX: ";
verbose += InstructionCounter.lastCount.GL.TEX < 0 ? "N/A" : InstructionCounter.lastCount.GL.TEX.ToString();
verbose += "\nD3D: ";
verbose += "\nALU: ";
verbose += InstructionCounter.lastCount.D3D.ALU < 0 ? "N/A" : InstructionCounter.lastCount.D3D.ALU.ToString();
verbose += " V_ALU: ";
verbose += InstructionCounter.lastCount.D3D.ALU < 0 ? "N/A" : InstructionCounter.lastCount.D3D.V_ALU.ToString();
verbose += " TEX: ";
verbose += InstructionCounter.lastCount.D3D.TEX < 0 ? "N/A" : InstructionCounter.lastCount.D3D.TEX.ToString();
_instructionCountTooltip = verbose;
}
//Drawing related states / areas
private bool _graphNeedsUpdate;
private bool _showComments = true;
private Vector2 _editorFieldOffset = Vector2.zero;
private Rect _drawArea;
private Rect _detailsBox;
private Rect _optionsBox;
private bool _focusChanged;
private bool _focusChangedUpdate;
public void OnGUI()
{
if (!_isInstructionCountCached)
CacheCount();
GUI.Label(new Rect(5,0,95,45),new GUIContent(_instructionCountDetails,_instructionCountTooltip));
_reservedArea.Clear();
_drawArea = new Rect( 0, 0, Screen.width-300, Screen.height-23 );
_detailsBox = new Rect(Screen.width - 300,0, 300, Screen.height - 40);
_optionsBox = new Rect(Screen.width - 300,Screen.height - 40, 300 , 25);
//Mouse clicks in the reserved area do not attemp to select on graph
_reservedArea.Add( _detailsBox );
_reservedArea.Add( _optionsBox );
_currentMousePosition.x = Event.current.mousePosition.x;
_currentMousePosition.y = Event.current.mousePosition.y;
// Handle Minimap! (Texel)
if (_middleMouseDrag) {
var oldColor = GUI.color;
var trans = GUI.color * new Vector4(1,1,1,0.3f); // Fairly transparent
// First, draw the bounds of the graph. This requires min/maxing the graph
var drawCenter = new Vector2((_drawArea.x + (_drawArea.width * 0.5f)),_drawArea.y + (_drawArea.height * 0.5f));
drawCenter.x -= _drawArea.width * 0.1f;
drawCenter.y -= _drawArea.height * 0.1f;
var redSize = new Vector2(_drawArea.width,_drawArea.height) * 0.2f;
GUI.color = trans;
GUI.Box(new Rect(drawCenter.x,drawCenter.y,redSize.x,redSize.y),"");
GUI.color = oldColor;
var oldBkg = GUI.backgroundColor;
// Now we will draw the graph centered around the offset (Scaled down ten times)
//Rect[] rects = _selectedGraph.CurrentSubGraph.nodePositions;
foreach(Node node in _selectedGraph.CurrentSubGraph.Nodes) {
var rect = node.NodePositionInGraph;
var delta = new Vector2(rect.x,rect.y);// - offset;
var size = new Vector2(rect.width,rect.height);
delta *= 0.2f; size *= 0.2f;
delta += drawCenter;
switch (node.CurrentState) {
case (NodeState.Valid):
GUI.color = Color.white;
break;
case (NodeState.NotConnected):
GUI.color = new Color (0.8f, 0.8f, 1f);
break;
case (NodeState.CircularReferenceInGraph):
GUI.color = new Color (0.8f, 0.8f, 0f);
break;
case (NodeState.Error):
GUI.color = Color.red;
break;
}
if( node == _selectedNode )
GUI.backgroundColor = Color.Lerp(GUI.backgroundColor,Color.green,0.5f);
GUI.Box(new Rect(delta.x,delta.y,size.x,size.y),"");
GUI.color = oldColor;
GUI.backgroundColor = oldBkg;
}
}
HandleEvents();
//GUI fixup for changed focus
GUI.SetNextControlName("FocusFixup");
EditorGUI.Toggle(new Rect(-100, -100, 1, 1), false);
if (_focusChangedUpdate)
{
GUI.FocusControl("FocusFixup");
_focusChangedUpdate = false;
}
//Update each node and draw them
_selectedGraph.UpdateErrorState();
GUILayout.BeginArea( _drawArea );
_selectedGraph.Draw( this, _showComments, _drawArea );
UpdateIOChannels();
DrawIOLines(_drawArea);
GUILayout.EndArea( );
if( _doingSelectBox )
{
var oldColor = GUI.color;
var newColor = GUI.color;
newColor.a = 0.4f;
GUI.color = newColor;
GUI.Box( GetSelectionArea(), "" );
GUI.color = oldColor;
}
DrawSettings();
//Handle node delete / undo and redo
if( !GUI.changed && Event.current.type == EventType.KeyDown )
{
if (Event.current.keyCode == KeyCode.Z
&& ( Event.current.modifiers == EventModifiers.Alt ) )
{
var graph = _undoChain.Undo();
if( graph != null )
{
_nextGraph = graph;
_nextGraph.Initialize( new Rect( 0, 0, Screen.width, Screen.height ), false);
_graphNeedsUpdate = true;
NextSelectedNode = _nextGraph.FirstSelected;
_updateSelection = true;
Event.current.Use();
}
return;
}
if (Event.current.keyCode == KeyCode.Z
&& ( Event.current.modifiers == (EventModifiers.Alt | EventModifiers.Shift ) ) )
{
var graph = _undoChain.Redo();
if( graph != null )
{
_nextGraph = graph;
_nextGraph.Initialize( new Rect( 0, 0, Screen.width, Screen.height ), false);
_graphNeedsUpdate = true;
NextSelectedNode = _nextGraph.FirstSelected;
_updateSelection = true;
Event.current.Use();
}
return;
}
if (Event.current.keyCode == KeyCode.Delete || Event.current.keyCode == KeyCode.Backspace)
{
_selectedGraph.CurrentSubGraph.DeleteSelected();
NextSelectedNode = null;
_graphNeedsUpdate = true;
_updateSelection = true;
SelectedInputChannel = null;
SelectedOutputChannel = null;
MarkDirty();
Event.current.Use();
}
}
//Draw the current subgraph type
var oldFontSize = GUI.skin.label.fontSize;
var oldFontStyle = GUI.skin.label.fontStyle;
GUI.skin.label.fontSize = 30;
GUI.skin.label.fontStyle = FontStyle.BoldAndItalic;
GUILayout.BeginArea( _drawArea );
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Label( _currentSubGraphType.DisplayName(), GUI.skin.label );
GUILayout.Space( 10 );
GUILayout.EndHorizontal();
GUILayout.EndArea();
GUI.skin.label.fontSize = oldFontSize;
GUI.skin.label.fontStyle = oldFontStyle;
DrawOptions();
}
private enum FileMenuOptions
{
NewGraph,
LoadGraph,
SaveGraph,
SaveAsGraph,
ExportGraph,
ExportAsGraph
}
private void FileMenuSelect( object objProperty )
{
if( objProperty.GetType() != typeof( FileMenuOptions ) )
{
return;
}
var option = (FileMenuOptions)objProperty;
switch( option )
{
case FileMenuOptions.NewGraph:
{
if (EditorUtility.DisplayDialog("New Graph","Old graph will be lost, are you sure?","Confirm","Cancel")) {
_nextGraph = new ShaderGraph();
_nextGraph.Initialize( new Rect( 0, 0, Screen.width, Screen.height ), true);
_graphNeedsUpdate = true;
_lastGraphPath = "";
_lastExportPath = "";
_undoChain = new GraphHistory( _serializableTypes );
_markDirtyOnLoad = true;
}
break;
}
case FileMenuOptions.ExportGraph:
case FileMenuOptions.ExportAsGraph:
{
_shouldExportShader = true;
if (!String.IsNullOrEmpty(_lastExportPath) &&
option == FileMenuOptions.ExportGraph)
{
_quickExport = true;
}
if (!String.IsNullOrEmpty(_lastGraphPath))
{
_shouldSaveGraph = true;
_quickSaving = true;
}
break;
}
case FileMenuOptions.SaveGraph:
case FileMenuOptions.SaveAsGraph:
{
_shouldSaveGraph = true;
if (!String.IsNullOrEmpty(_lastGraphPath) &&
option == FileMenuOptions.SaveGraph)
{
_quickSaving = true;
}
break;
}
case FileMenuOptions.LoadGraph:
{
_shouldLoadGraph = true;
break;
}
}
}
private void SubGraphSelect( object objProperty )
{
if( objProperty.GetType() != typeof( SubGraphType ) )
{
return;
}
_currentSubGraphType = (SubGraphType) objProperty;
SelectedInputChannel = null;
SelectedOutputChannel = null;
}
private enum OptionsSelection
{
None=-1,
File,
Comments,
Graphs,
Preview
}
private void DrawOptions()
{
GUILayout.BeginArea( _optionsBox );
GUILayout.BeginHorizontal();
var file = GUI.skin.buttonLeft();//GUI.skin.FindStyle("ButtonLeft");
var comments= GUI.skin.buttonMid();//new GUIStyle(GUI.skin.FindStyle("ButtonMid"));
var graphs = PreviewSupported() ?
GUI.skin.buttonMid() : //GUI.skin.FindStyle("ButtonMid") :
GUI.skin.buttonRight();//GUI.skin.FindStyle("ButtonRight");
GUI.skin.buttonRight();
var selectedOption = OptionsSelection.None;
GUILayout.BeginHorizontal();
if (GUILayout.Button(new GUIContent("File","Save, Load, And Export features."),file))
selectedOption = OptionsSelection.File;
if (_showComments) {
comments = GUI.skin.buttonMidOn();
}
if (GUILayout.Button(new GUIContent("Comments","Enable ot disable the display of comments"),comments))
selectedOption = OptionsSelection.Comments;
if (GUILayout.Button(new GUIContent("Graphs","Change the active subgraph"),graphs))
selectedOption = OptionsSelection.Graphs;
if (PreviewSupported()) {
if (GUILayout.Button(new GUIContent("Preview","Call forth the preview window"),graphs))
selectedOption = OptionsSelection.Preview;
}
GUILayout.EndHorizontal();
/*if( PreviewSupported() )
{
selectedOption = (OptionsSelection)GUILayout.Toolbar( (int)selectedOption,
new [] { OptionsSelection.File.ToString(), OptionsSelection.Comments.ToString(), OptionsSelection.Graphs.ToString() ,OptionsSelection.Preview.ToString() } );
}
else
{
selectedOption = (OptionsSelection)GUILayout.Toolbar( (int)selectedOption,
new [] { OptionsSelection.File.ToString(), OptionsSelection.Comments.ToString() } );
}*/
switch( selectedOption )
{
case OptionsSelection.File:
{
var menu = new GenericMenu();
menu.AddItem( new GUIContent( "New Graph..." ), false, FileMenuSelect, FileMenuOptions.NewGraph );
menu.AddItem( new GUIContent( "Load..." ), false, FileMenuSelect,FileMenuOptions.LoadGraph );
if( String.IsNullOrEmpty(_lastGraphPath) )
{
menu.AddDisabledItem( new GUIContent( "Save" ) );
}
else
{
menu.AddItem( new GUIContent( "Save" ), false, FileMenuSelect, FileMenuOptions.SaveGraph );
}
menu.AddItem( new GUIContent( "Save As..." ), false, FileMenuSelect, FileMenuOptions.SaveAsGraph );
if( String.IsNullOrEmpty(_lastExportPath) )
{
menu.AddDisabledItem( new GUIContent( "Export" ) );
}
else
{
menu.AddItem( new GUIContent( "Export" ), false, FileMenuSelect, FileMenuOptions.ExportGraph );
}
menu.AddItem( new GUIContent( "Export As..." ), false, FileMenuSelect, FileMenuOptions.ExportAsGraph );
menu.ShowAsContext();
break;
}
case OptionsSelection.Graphs:
{
var menu = new GenericMenu();
menu.AddItem( new GUIContent( "Pixel" ), false, SubGraphSelect, SubGraphType.Pixel );
menu.AddItem( new GUIContent( "Vertex" ), false, SubGraphSelect, SubGraphType.Vertex );
menu.AddItem( new GUIContent( "Lighting" ), false, SubGraphSelect, SubGraphType.SimpleLighting );
menu.ShowAsContext();
break;
}
case OptionsSelection.Comments:
{
_showComments = !_showComments;
break;
}
case OptionsSelection.Preview:
{
_shouldOpenPreviewWindow = true;
break;
}
}
GUILayout.EndHorizontal();
GUILayout.EndArea();
}
private Rect GetSelectionArea()
{
float left = _selectBoxStart.x < _currentMousePosition.x ? _selectBoxStart.x : _currentMousePosition.x;
float right = _selectBoxStart.x > _currentMousePosition.x ? _selectBoxStart.x : _currentMousePosition.x;
float top = _selectBoxStart.y < _currentMousePosition.y ? _selectBoxStart.y : _currentMousePosition.y;
float bottom = _selectBoxStart.y > _currentMousePosition.y ? _selectBoxStart.y : _currentMousePosition.y;
return new Rect( left, top, right - left, bottom - top );
}
private bool _updateSelection;
private bool _middleMouseDrag;
private void HandleEvents() // Texel added parent input for drag and drop
{
switch( Event.current.type )
{
case EventType.DragUpdated:
case EventType.DragPerform :
{
if (position.Contains(_currentMousePosition)) {
var path = DragAndDrop.paths[0];
if (path.EndsWith("sgraph"))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
if (Event.current.type == EventType.dragPerform)
{
_shouldLoadGraph = true;
_overrideLoadPath = path;
_lastGraphPath = path;
_markDirtyOnLoad = true;
}
Event.current.Use();
}
}
break;
}
case EventType.MouseDown:
{
if (Event.current.button == 0 )
{
if( LeftMouseDown() )
{
Event.current.Use();
return;
}
}
break;
}
case EventType.ContextClick:
{
if( RightMouseDown() )
{
Event.current.Use();
return;
}
break;
}
//Handle drag
case EventType.MouseDrag:
{
_currentMousePosition.x = Event.current.mousePosition.x;
_currentMousePosition.y = Event.current.mousePosition.y;
//If Left click drag...
if (Event.current.button == 0 )
{
if( LeftMouseDragged() )
{
Event.current.Use();
}
}
if( Event.current.button == 2 )
{
_middleMouseDrag = true;
_selectedGraph.CurrentSubGraph.DrawOffset += Event.current.delta;
Event.current.Use();
}
break;
}
case EventType.MouseUp:
{
//Mouse button released, unmark hot
_selectedGraph.UnmarkSelectedHot();
if( _focusChanged )
{
_focusChangedUpdate = true;
_focusChanged = false;
}
//Selection box
if( _doingSelectBox )
{
_doingSelectBox = false;
if( _selectedGraph.Select( GetSelectionArea(), Event.current.modifiers == EventModifiers.Shift ) )
{
NextSelectedNode = _selectedGraph.FirstSelected;
_updateSelection = true;
MarkDirty();
}
Event.current.Use();
}
if( _movingNodes )
{
_movingNodes = false;
MarkDirty();
Event.current.Use();
}
if( _middleMouseDrag )
{
_middleMouseDrag = false;
MarkDirty();
Event.current.Use();
}
break;
}
case EventType.Layout:
{
if (_nextGraph != null && _nextGraph != _selectedGraph)
{
_selectedGraph = _nextGraph;
if( _markDirtyOnLoad )
{
MarkDirty();
_markDirtyOnLoad = false;
}
_selectedNode = null;
}
if( _selectedGraph.CurrentSubGraphType != _currentSubGraphType )
{
_selectedGraph.CurrentSubGraphType = _currentSubGraphType;
_selectedGraph.Deselect();
MarkDirty();
_selectedNode = null;
}
if( _updateSelection )
{
_focusChanged = true;
_selectedNode = NextSelectedNode;
_updateSelection = false;
}
break;
}
case EventType.ValidateCommand:
{
if( Event.current.commandName == "Copy"
|| Event.current.commandName == "Paste"
|| Event.current.commandName == "Duplicate"
|| Event.current.commandName == "SelectAll")
{
Event.current.Use();
}
break;
}
case EventType.ExecuteCommand:
{
if( Event.current.commandName == "Copy" )
{
CopySelectedNodes();
Event.current.Use();
}
if( Event.current.commandName == "Paste" )
{
PasteNodes();
Event.current.Use();
}
if( Event.current.commandName == "Duplicate" )
{
CopySelectedNodes();
PasteNodes();
MarkDirty();
Event.current.Use();
}
if( Event.current.commandName == "SelectAll" )
{
_selectedGraph.SelectAll();
NextSelectedNode = _selectedGraph.FirstSelected;
_updateSelection = true;
MarkDirty();
Event.current.Use();
}
break;
}
}
return;
}
private void UpdateIOChannels()
{
//Update channel selection state
if (SelectedInputChannel != null && SelectedOutputChannel != null)
{
var inputChannel = _selectedGraph.CurrentSubGraph.GetInputChannel(SelectedInputChannel);
var outputChannel = _selectedGraph.CurrentSubGraph.GetOutputChannel(SelectedOutputChannel);
if (SelectedInputChannel.NodeIdentifier != SelectedOutputChannel.NodeIdentifier
&& inputChannel.ChannelType == outputChannel.ChannelType)
{
inputChannel.IncomingConnection = SelectedOutputChannel;
}
SelectedInputChannel = null;
SelectedOutputChannel = null;
_graphNeedsUpdate = true;
MarkDirty();
}
}
private enum SelectedSettings
{
Node,
Inputs,
Settings,
Nodes
}
private SelectedSettings _currentSettings = SelectedSettings.Node;
private Vector2 _optionsScrollPosition = Vector2.zero;
private void DrawSettings()
{
GUI.Box( _detailsBox, "");
GUILayout.BeginArea( new Rect( _detailsBox.x + 5, _detailsBox.y + 5, _detailsBox.width - 10, 25) );
var setContent = new[]
{ new GUIContent(SelectedSettings.Node.ToString(),"Settings for the active selected node"),
new GUIContent(SelectedSettings.Inputs.ToString(),"Input manager to add/remove/rename inputs for the graph"),
new GUIContent(SelectedSettings.Settings.ToString(),"Settings for the shader itself"),
new GUIContent(SelectedSettings.Nodes.ToString(),"Searchable, tooltipped list of nodes.") };
// Texel fun time
/*if (_selectedGraph.IsGraphValid()) {
currentSettings = (SelectedSettings)GUILayout.Toolbar( (int)currentSettings,
new [] { SelectedSettings.Node.ToString(),
SelectedSettings.Inputs.ToString(),
SelectedSettings.Settings.ToString(),
SelectedSettings.Nodes.ToString() } );
} else */ { // Settings are not valid, time to draw a custom view
// Custom style time!
/* // Too Small
var node = new GUIStyle(GUI.skin.FindStyle("minibuttonleft"));
var inputs = new GUIStyle(GUI.skin.FindStyle("minibuttonmid"));
var settings = new GUIStyle(GUI.skin.FindStyle("minibuttonmid"));
var nodes = new GUIStyle(GUI.skin.FindStyle("minibuttonright")); */
/* // Too Big
var node = GUI.skin.FindStyle("LargeButtonLeft");
var inputs = GUI.skin.FindStyle("LargeButtonMid");
var settings = GUI.skin.FindStyle("LargeButtonMid");
var nodes= GUI.skin.FindStyle("LargeButtonRight");
*/
var node = GUI.skin.buttonLeft();//new GUIStyle(GUI.skin.FindStyle("ButtonLeft"));
var inputs = GUI.skin.buttonMid();//new GUIStyle(GUI.skin.FindStyle("ButtonMid"));
var settings = GUI.skin.buttonMid();//new GUIStyle(GUI.skin.FindStyle("ButtonMid"));
var nodes = GUI.skin.buttonMid();//new GUIStyle(GUI.skin.FindStyle("ButtonRight"));
// Reflect active button settings (since we will emulate using Button)
/*switch (currentSettings) {
case SelectedSettings.Node:
node.normal = node.onNormal;
node.hover = node.onHover;
node.active = node.onActive;
break;
case SelectedSettings.Inputs:
inputs.normal = inputs.onNormal;
inputs.hover = inputs.onHover;
inputs.active = inputs.onActive;
break;
case SelectedSettings.Settings:
settings.normal = settings.onNormal;
settings.hover = settings.onHover;
settings.active = settings.onActive;
break;
case SelectedSettings.Nodes:
nodes.normal = nodes.onNormal;
nodes.hover = nodes.onHover;
nodes.active = nodes.onActive;
break;
}*/
switch (_currentSettings) {
case SelectedSettings.Node:
node = GUI.skin.buttonLeftOn();
break;
case SelectedSettings.Inputs:
inputs = GUI.skin.buttonMidOn();
break;
case SelectedSettings.Settings:
settings = GUI.skin.buttonMidOn();
break;
case SelectedSettings.Nodes:
nodes = GUI.skin.buttonRightOn();
break;
}
var oldColor = GUI.color;
GUILayout.BeginHorizontal(); // Begin our virtual toolbar
if (_selectedNode != null)
if(_selectedNode.CurrentState == NodeState.Error)
GUI.color = Color.red;
if (GUILayout.Button(setContent[0],node))
_currentSettings = SelectedSettings.Node;
GUI.color = oldColor;
if (!_selectedGraph.IsInputsValid())
GUI.color = Color.red;
if (GUILayout.Button(setContent[1],inputs))
_currentSettings = SelectedSettings.Inputs;
GUI.color = oldColor;
if (!_selectedGraph.IsSettingsValid())
GUI.color = Color.red;
if (GUILayout.Button(setContent[2],settings))
_currentSettings = SelectedSettings.Settings;
GUI.color = oldColor;
if (GUILayout.Button(setContent[3],nodes))
_currentSettings = SelectedSettings.Nodes;
GUILayout.EndHorizontal();
}
GUILayout.EndArea();
GUILayout.BeginArea( new Rect( _detailsBox.x, _detailsBox.y + 25, _detailsBox.width, _detailsBox.height - 30 ) );
_optionsScrollPosition = GUILayout.BeginScrollView(_optionsScrollPosition, GUILayout.Width(_detailsBox.width), GUILayout.Height(_detailsBox.height - 30));
switch( _currentSettings )
{
case SelectedSettings.Node:
if ( _selectedNode != null)
{
GUI.changed = false;
_selectedNode.DrawProperties();
_selectedNode.DrawCommentField();
// Texel - Good place to remind users of errors aswell, now that we have more space.
var errors = _selectedNode.ErrorMessages.Aggregate("", (current, error) => current + (error + "\n"));
if (errors != "")
errors = "ERROR: " + errors;
var oldColor = GUI.color;
GUI.color = Color.red;
GUILayout.Label(new GUIContent(errors,"Better fix this."));
GUI.color = oldColor;
//Potential change to node name ect... need to force update of error states
if( GUI.changed )
{
//Do not do full mark dirty on simple GUI change
_selectedGraph.MarkDirty();
}
GUILayout.FlexibleSpace();
}
else
{
GUILayout.Label( "Select a node to edit" );
}
break;
case SelectedSettings.Inputs:
_selectedGraph.DrawInput();
break;
case SelectedSettings.Settings:
_selectedGraph.DrawSettings();
break;
case SelectedSettings.Nodes:
_popupMenu.GuiPaneDraw( new Vector2( _detailsBox.x, _detailsBox.y ) );
break;
}
GUILayout.EndScrollView();
GUILayout.EndArea();
}
private readonly List<Rect> _reservedArea = new List<Rect>();
private bool InsideReservedArea( Vector2 thePosition )
{
if( _reservedArea.Any( x => x.Contains( thePosition ) ) )
{
return true;
}
return false;
}
private Vector2 _selectBoxStart = Vector2.zero;
private bool _doingSelectBox;
private bool LeftMouseDown()
{
if( InsideReservedArea( _currentMousePosition ) )
{
return false;
}
if( Event.current.modifiers == EventModifiers.Alt || Event.current.modifiers == EventModifiers.Command )
{
return true;
}
//We have clicked on an already selected node...
var clickedNode = _selectedGraph.NodeAt( _currentMousePosition );
if( clickedNode != null && _selectedGraph.IsSelected( clickedNode ) )
{
//If shift is held down deselect that node
if( Event.current.modifiers == EventModifiers.Shift )
{
_selectedGraph.Deselect( clickedNode );
MarkDirty();
return true;
}
//just mark hot
_selectedGraph.MarkSelectedHot();
return true;
}
if( _selectedGraph.Select( _currentMousePosition, Event.current.modifiers == EventModifiers.Shift ) )
{
_selectedGraph.MarkSelectedHot();
NextSelectedNode = _selectedGraph.FirstSelected;
_updateSelection = true;
MarkDirty();
return true;
}
if( _selectedGraph.ButtonAt( _currentMousePosition ) )
{
return false;
}
if( Event.current.modifiers != EventModifiers.Shift )
{
_selectedGraph.Deselect();
NextSelectedNode = null;
MarkDirty();
_updateSelection = true;
}
//Nothing is selected... start a drag
_doingSelectBox = true;
_selectBoxStart = Event.current.mousePosition;
return false;
}
private bool _movingNodes;
private bool LeftMouseDragged()
{
if( Event.current.modifiers == EventModifiers.Alt )
{
_middleMouseDrag = true;
_selectedGraph.CurrentSubGraph.DrawOffset += Event.current.delta;
return true;
}
if( Event.current.modifiers == EventModifiers.Command )
{
_selectedGraph.CurrentSubGraph.DrawScale += Event.current.delta.y;
return true;
}
_movingNodes = _selectedGraph.DragSelectedNodes( Event.current.delta );
return _movingNodes;
}
private bool RightMouseDown()
{
if( InsideReservedArea( _currentMousePosition ) )
{
return false;
}
//First right click clears any lines that are currenly being drawn
if (SelectedInputChannel != null || SelectedOutputChannel != null)
{
SelectedInputChannel = null;
SelectedOutputChannel = null;
return false;
}
var didDelete = false; // Were we over another node on RMB? - Texel
//If we clicked on a bezier curve... delete the link!
foreach (var node in _selectedGraph.CurrentSubGraph.Nodes)
{
foreach (var inputChannel in node.GetInputChannels())
{
if (inputChannel.IncomingConnection != null)
{
var startPos = NodeDrawer.GetAbsoluteInputChannelPosition(node, inputChannel.ChannelId);
var endNode = _selectedGraph.CurrentSubGraph.GetNode(inputChannel.IncomingConnection.NodeIdentifier);
var endPos = NodeDrawer.GetAbsoluteOutputChannelPosition(endNode, inputChannel.IncomingConnection.ChannelId);
var distanceBetweenNodes = Mathf.Abs(startPos.x - endPos.x);
var distance = HandleUtility.DistancePointBezier(_currentMousePosition,
new Vector3(startPos.x, startPos.y, 0.0f),
new Vector3(endPos.x, endPos.y, 0.0f),
new Vector3(startPos.x + distanceBetweenNodes / 3.0f, startPos.y, 0.0f),
new Vector3(endPos.x - distanceBetweenNodes / 3.0f, endPos.y, 0.0f));
if (distance < 5.0f)
{
inputChannel.IncomingConnection = null;
_graphNeedsUpdate = true;
MarkDirty();
didDelete = true;
}
}
}
}
if( !didDelete )
{
_popupMenu.Show( _currentMousePosition, _currentSubGraphType );
}
return true;
}
private Texture2D _bezierTexture;
private void DrawIOLines( Rect viewArea )
{
Handles.BeginGUI( );
Handles.color = Color.black;
_bezierTexture =_bezierTexture ?? Resources.Load("Internal/1x2AA", typeof(Texture2D)) as Texture2D;
foreach (var node in _selectedGraph.CurrentSubGraph.Nodes)
{
foreach (var inputChannel in node.GetInputChannels())
{
if (inputChannel.IncomingConnection != null)
{
var startPos = NodeDrawer.GetAbsoluteInputChannelPosition(node, inputChannel.ChannelId);
var endNode = _selectedGraph.CurrentSubGraph.GetNode(inputChannel.IncomingConnection.NodeIdentifier);
var endPos = NodeDrawer.GetAbsoluteOutputChannelPosition(endNode, inputChannel.IncomingConnection.ChannelId);
//Make a compound box
float left = startPos.x < endPos.x ? startPos.x : endPos.x;
float right = startPos.x > endPos.x ? startPos.x : endPos.x;
float top = startPos.y < endPos.y ? startPos.y : endPos.y;
float bottom = startPos.y > endPos.y ? startPos.y : endPos.y;
var channelBounds = new Rect( left, top, right - left, bottom - top );
if( channelBounds.xMin > viewArea.xMax
|| channelBounds.xMax < viewArea.xMin
|| channelBounds.yMin > viewArea.yMax
|| channelBounds.yMax < viewArea.yMin )
{
continue;
}
var distanceBetweenNodes = Mathf.Abs(startPos.x - endPos.x);
Handles.DrawBezier(new Vector3(startPos.x, startPos.y),
new Vector3(endPos.x, endPos.y),
new Vector3(startPos.x + distanceBetweenNodes / 3.0f, startPos.y),
new Vector3(endPos.x - distanceBetweenNodes / 3.0f, endPos.y),
Color.black,
_bezierTexture,
1.25f);
}
}
}
//Draw IO for selected
if (SelectedInputChannel != null || SelectedOutputChannel != null)
{
Vector3 start;
if (SelectedInputChannel != null)
{
var channelPosition = NodeDrawer.GetAbsoluteInputChannelPosition(_selectedGraph.CurrentSubGraph.GetNode(SelectedInputChannel.NodeIdentifier), SelectedInputChannel.ChannelId);
start = new Vector3(channelPosition.x, channelPosition.y, 0f);
}
else
{
var channelPosition = NodeDrawer.GetAbsoluteOutputChannelPosition(_selectedGraph.CurrentSubGraph.GetNode(SelectedOutputChannel.NodeIdentifier), SelectedOutputChannel.ChannelId);
start = new Vector3(channelPosition.x, channelPosition.y, 0f);
}
var mouseDrawPos = _currentMousePosition + new Vector3(_editorFieldOffset.x, _editorFieldOffset.y, 0f);
var startPos = start;
var endPos = mouseDrawPos;
if (startPos.x > endPos.x) {
startPos = mouseDrawPos;
endPos = start;
}
var distanceBetweenNodes = Mathf.Abs(startPos.x - endPos.x);
Handles.DrawBezier(
new Vector3(startPos.x, startPos.y),
new Vector3(endPos.x, endPos.y),
new Vector3(startPos.x + distanceBetweenNodes / 3.0f, startPos.y),
new Vector3(endPos.x - distanceBetweenNodes / 3.0f, endPos.y),
Color.black,
_bezierTexture,
1.25f);
}
Handles.EndGUI();
}
/**
* Copy / paste for nodes
*/
private class SerializedNodeList
{
private readonly List<Node> _nodes = new List<Node> ();
private readonly List<Type> _serializableTypes = new List<Type>();
public SerializedNodeList( IEnumerable<Node> nodes, List<Type> serializableTypes )
{
_serializableTypes = serializableTypes;
foreach (var node in nodes.Where(node => !(node is RootNode)))
{
_nodes.Add( node );
}
}
public IEnumerable<Node> CopiedNodes
{
get
{
//Save the nodes into a memory stream
var ser = new DataContractSerializer(typeof(List<Node>), _serializableTypes, int.MaxValue, false, false, null);
var stream = new MemoryStream();
ser.WriteObject(stream, _nodes);
stream.Flush();
stream.Position = 0;
//Reload them back out...
var reader = XmlDictionaryReader.CreateTextReader(stream, new XmlDictionaryReaderQuotas());
var loaded = ser.ReadObject(reader, true) as List<Node>;
return loaded;
}
}
}
private SerializedNodeList _copiedNodes;
private void CopySelectedNodes()
{
_copiedNodes = new SerializedNodeList( _selectedGraph.CurrentSubGraph.SelectedNodes, _serializableTypes);
}
private void PasteNodes()
{
if( _copiedNodes == null )
{
return;
}
var copied = _copiedNodes.CopiedNodes;
if( copied == null )
{
return;
}
//Add the nodes into the new graph
var nameMap = new Dictionary<string, string>();
foreach( var node in copied )
{
var oldName = node.UniqueNodeIdentifier;
_selectedGraph.CurrentSubGraph.AddNode(node);
node.Initialize();
var newName = node.UniqueNodeIdentifier;
nameMap.Add( oldName, newName );
}
//Patch up the channel references...
foreach( var node in copied )
{
foreach( var channel in node.GetInputChannels() )
{
if( channel.IncomingConnection != null && nameMap.ContainsKey( channel.IncomingConnection.NodeIdentifier ) )
{
channel.IncomingConnection.NodeIdentifier = nameMap[channel.IncomingConnection.NodeIdentifier];
}
else
{
channel.IncomingConnection = null;
}
}
}
//Mark these nodes as selected
_selectedGraph.Deselect();
foreach( var node in copied )
{
_selectedGraph.Select( node, true );
}
NextSelectedNode = _selectedGraph.FirstSelected;
_updateSelection = true;
MarkDirty();
}
private class GraphHistory
{
private readonly Stack<MemoryStream> _undoStack;
private readonly Stack<MemoryStream> _redoStack;
private MemoryStream _currentState;
private readonly DataContractSerializer _serializer;
public GraphHistory( IEnumerable<Type> serializableTypes )
{
_undoStack = new Stack<MemoryStream>();
_redoStack = new Stack<MemoryStream>();
_serializer = new DataContractSerializer(typeof(ShaderGraph), serializableTypes, int.MaxValue, false, false, null);
}
public void AddUndoLevel( ShaderGraph graph )
{
var stream = new MemoryStream();
_serializer.WriteObject(stream, graph);
stream.Flush();
if( _currentState != null )
{
_undoStack.Push( _currentState );
}
_currentState = stream;
_redoStack.Clear();
}
private ShaderGraph Deserialize( Stream graphStream )
{
graphStream.Position = 0;
var reader = XmlDictionaryReader.CreateTextReader(graphStream, new XmlDictionaryReaderQuotas());
return _serializer.ReadObject(reader, true) as ShaderGraph;
}
public ShaderGraph Undo()
{
if( _undoStack.Count == 0 )
{
return null;
}
_redoStack.Push( _currentState );
_currentState = _undoStack.Pop();
return Deserialize( _currentState );
}
public ShaderGraph Redo()
{
if( _redoStack.Count == 0 )
{
return null;
}
_undoStack.Push( _currentState );
_currentState = _redoStack.Pop();
return Deserialize( _currentState );
}
}
}
}
| |
// ==++==
//
// Copyright(c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
namespace System.Reflection
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
[Serializable]
[ClassInterface(ClassInterfaceType.None)]
[ComDefaultInterface(typeof(_PropertyInfo))]
#pragma warning disable 618
[PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")]
#pragma warning restore 618
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class PropertyInfo : MemberInfo, _PropertyInfo
{
#region Constructor
protected PropertyInfo() { }
#endregion
#if !FEATURE_CORECLR
public static bool operator ==(PropertyInfo left, PropertyInfo right)
{
if (ReferenceEquals(left, right))
return true;
if ((object)left == null || (object)right == null ||
left is RuntimePropertyInfo || right is RuntimePropertyInfo)
{
return false;
}
return left.Equals(right);
}
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool operator !=(PropertyInfo left, PropertyInfo right)
{
return !(left == right);
}
#endif // !FEATURE_CORECLR
#if FEATURE_NETCORE || !FEATURE_CORECLR
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
#endif //FEATURE_NETCORE || !FEATURE_CORECLR
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Property; } }
#endregion
#region Public Abstract\Virtual Members
public virtual object GetConstantValue()
{
throw new NotImplementedException();
}
public virtual object GetRawConstantValue()
{
throw new NotImplementedException();
}
public abstract Type PropertyType { get; }
public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
public abstract MethodInfo[] GetAccessors(bool nonPublic);
public abstract MethodInfo GetGetMethod(bool nonPublic);
public abstract MethodInfo GetSetMethod(bool nonPublic);
public abstract ParameterInfo[] GetIndexParameters();
public abstract PropertyAttributes Attributes { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public Object GetValue(Object obj)
{
return GetValue(obj, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Default, null, index, null);
}
public abstract Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture);
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public void SetValue(Object obj, Object value)
{
SetValue(obj, value, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public virtual void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj, value, BindingFlags.Default, null, index, null);
}
#endregion
#region Public Members
public virtual Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; }
public virtual Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; }
public MethodInfo[] GetAccessors() { return GetAccessors(false); }
public virtual MethodInfo GetMethod
{
get
{
return GetGetMethod(true);
}
}
public virtual MethodInfo SetMethod
{
get
{
return GetSetMethod(true);
}
}
public MethodInfo GetGetMethod() { return GetGetMethod(false); }
public MethodInfo GetSetMethod() { return GetSetMethod(false); }
public bool IsSpecialName { get { return(Attributes & PropertyAttributes.SpecialName) != 0; } }
#endregion
Type _PropertyInfo.GetType()
{
return base.GetType();
}
void _PropertyInfo.GetTypeInfoCount(out uint pcTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
throw new NotImplementedException();
}
void _PropertyInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
throw new NotImplementedException();
}
// If you implement this method, make sure to include _PropertyInfo.Invoke in VM\DangerousAPIs.h and
// include _PropertyInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp.
void _PropertyInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
throw new NotImplementedException();
}
}
[Serializable]
internal unsafe sealed class RuntimePropertyInfo : PropertyInfo, ISerializable
{
#region Private Data Members
private int m_token;
private string m_name;
[System.Security.SecurityCritical]
private void* m_utf8name;
private PropertyAttributes m_flags;
private RuntimeTypeCache m_reflectedTypeCache;
private RuntimeMethodInfo m_getterMethod;
private RuntimeMethodInfo m_setterMethod;
private MethodInfo[] m_otherMethod;
private RuntimeType m_declaringType;
private BindingFlags m_bindingFlags;
private Signature m_signature;
private ParameterInfo[] m_parameters;
#endregion
#region Constructor
[System.Security.SecurityCritical] // auto-generated
internal RuntimePropertyInfo(
int tkProperty, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate)
{
Contract.Requires(declaredType != null);
Contract.Requires(reflectedTypeCache != null);
Contract.Assert(!reflectedTypeCache.IsGlobal);
MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport;
m_token = tkProperty;
m_reflectedTypeCache = reflectedTypeCache;
m_declaringType = declaredType;
ConstArray sig;
scope.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out sig);
RuntimeMethodInfo dummy;
Associates.AssignAssociates(scope, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(),
out dummy, out dummy, out dummy,
out m_getterMethod, out m_setterMethod, out m_otherMethod,
out isPrivate, out m_bindingFlags);
}
#endregion
#region Internal Members
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal override bool CacheEquals(object o)
{
RuntimePropertyInfo m = o as RuntimePropertyInfo;
if ((object)m == null)
return false;
return m.m_token == m_token &&
RuntimeTypeHandle.GetModule(m_declaringType).Equals(
RuntimeTypeHandle.GetModule(m.m_declaringType));
}
internal Signature Signature
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_signature == null)
{
PropertyAttributes flags;
ConstArray sig;
void* name;
GetRuntimeModule().MetadataImport.GetPropertyProps(
m_token, out name, out flags, out sig);
m_signature = new Signature(sig.Signature.ToPointer(), (int)sig.Length, m_declaringType);
}
return m_signature;
}
}
internal bool EqualsSig(RuntimePropertyInfo target)
{
//@Asymmetry - Legacy policy is to remove duplicate properties, including hidden properties.
// The comparison is done by name and by sig. The EqualsSig comparison is expensive
// but forutnetly it is only called when an inherited property is hidden by name or
// when an interfaces declare properies with the same signature.
// Note that we intentionally don't resolve generic arguments so that we don't treat
// signatures that only match in certain instantiations as duplicates. This has the
// down side of treating overriding and overriden properties as different properties
// in some cases. But PopulateProperties in rttype.cs should have taken care of that
// by comparing VTable slots.
//
// Class C1(Of T, Y)
// Property Prop1(ByVal t1 As T) As Integer
// Get
// ... ...
// End Get
// End Property
// Property Prop1(ByVal y1 As Y) As Integer
// Get
// ... ...
// End Get
// End Property
// End Class
//
Contract.Requires(Name.Equals(target.Name));
Contract.Requires(this != target);
Contract.Requires(this.ReflectedType == target.ReflectedType);
#if FEATURE_LEGACYNETCF
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)
return Signature.CompareSigForAppCompat(this.Signature, this.m_declaringType,
target.Signature, target.m_declaringType);
#endif
return Signature.CompareSig(this.Signature, target.Signature);
}
internal BindingFlags BindingFlags { get { return m_bindingFlags; } }
#endregion
#if FEATURE_LEGACYNETCF
// BEGIN helper methods for Dev11 466969 quirk
internal bool HasMatchingAccessibility(RuntimePropertyInfo target)
{
Contract.Assert(CompatibilitySwitches.IsAppEarlierThanWindowsPhone8);
bool match = true;
if (!IsMatchingAccessibility(this.GetGetMethod(true), target.GetGetMethod(true)))
{
match = false;
}
else if (!IsMatchingAccessibility(this.GetSetMethod(true), target.GetSetMethod(true)))
{
match = false;
}
return match;
}
private bool IsMatchingAccessibility(MethodInfo lhsInfo, MethodInfo rhsInfo)
{
if (lhsInfo != null && rhsInfo != null)
{
return lhsInfo.IsPublic == rhsInfo.IsPublic;
}
else
{
// don't be tempted to return false here! we only want to introduce
// the quirk behavior when we know that the accessibility is different.
// in all other cases return true so the code works as before.
return true;
}
}
// END helper methods for Dev11 466969 quirk
#endif
#region Object Overrides
public override String ToString()
{
return FormatNameAndSig(false);
}
private string FormatNameAndSig(bool serialization)
{
StringBuilder sbName = new StringBuilder(PropertyType.FormatTypeName(serialization));
sbName.Append(" ");
sbName.Append(Name);
RuntimeType[] arguments = Signature.Arguments;
if (arguments.Length > 0)
{
sbName.Append(" [");
sbName.Append(MethodBase.ConstructParameters(arguments, Signature.CallingConvention, serialization));
sbName.Append("]");
}
return sbName.ToString();
}
#endregion
#region ICustomAttributeProvider
public override Object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException("attributeType");
Contract.EndContractBlock();
RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType");
return CustomAttribute.IsDefined(this, attributeRuntimeType);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
public override String Name
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if (m_name == null)
m_name = new Utf8String(m_utf8name).ToString();
return m_name;
}
}
[System.Security.SecuritySafeCritical]
internal override String GetFullNameForEtw()
{
if (m_name == null)
return new Utf8String(m_utf8name).ToString();
return m_name;
}
public override Type DeclaringType
{
get
{
return m_declaringType;
}
}
public override Type ReflectedType
{
get
{
return ReflectedTypeInternal;
}
}
private RuntimeType ReflectedTypeInternal
{
get
{
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override int MetadataToken { get { return m_token; } }
public override Module Module { get { return GetRuntimeModule(); } }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
#endregion
#region PropertyInfo Overrides
#region Non Dynamic
public override Type[] GetRequiredCustomModifiers()
{
return Signature.GetCustomModifiers(0, true);
}
public override Type[] GetOptionalCustomModifiers()
{
return Signature.GetCustomModifiers(0, false);
}
[System.Security.SecuritySafeCritical] // auto-generated
internal object GetConstantValue(bool raw)
{
Object defaultValue = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw);
if (defaultValue == DBNull.Value)
// Arg_EnumLitValueNotFound -> "Literal value was not found."
throw new InvalidOperationException(Environment.GetResourceString("Arg_EnumLitValueNotFound"));
return defaultValue;
}
public override object GetConstantValue() { return GetConstantValue(false); }
public override object GetRawConstantValue() { return GetConstantValue(true); }
public override MethodInfo[] GetAccessors(bool nonPublic)
{
List<MethodInfo> accessorList = new List<MethodInfo>();
if (Associates.IncludeAccessor(m_getterMethod, nonPublic))
accessorList.Add(m_getterMethod);
if (Associates.IncludeAccessor(m_setterMethod, nonPublic))
accessorList.Add(m_setterMethod);
if ((object)m_otherMethod != null)
{
for(int i = 0; i < m_otherMethod.Length; i ++)
{
if (Associates.IncludeAccessor(m_otherMethod[i] as MethodInfo, nonPublic))
accessorList.Add(m_otherMethod[i]);
}
}
return accessorList.ToArray();
}
public override Type PropertyType
{
get { return Signature.ReturnType; }
}
public override MethodInfo GetGetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_getterMethod, nonPublic))
return null;
return m_getterMethod;
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override MethodInfo GetSetMethod(bool nonPublic)
{
if (!Associates.IncludeAccessor(m_setterMethod, nonPublic))
return null;
return m_setterMethod;
}
public override ParameterInfo[] GetIndexParameters()
{
ParameterInfo[] indexParams = GetIndexParametersNoCopy();
int numParams = indexParams.Length;
if (numParams == 0)
return indexParams;
ParameterInfo[] ret = new ParameterInfo[numParams];
Array.Copy(indexParams, ret, numParams);
return ret;
}
internal ParameterInfo[] GetIndexParametersNoCopy()
{
// @History - Logic ported from RTM
// No need to lock because we don't guarantee the uniqueness of ParameterInfo objects
if (m_parameters == null)
{
int numParams = 0;
ParameterInfo[] methParams = null;
// First try to get the Get method.
MethodInfo m = GetGetMethod(true);
if (m != null)
{
// There is a Get method so use it.
methParams = m.GetParametersNoCopy();
numParams = methParams.Length;
}
else
{
// If there is no Get method then use the Set method.
m = GetSetMethod(true);
if (m != null)
{
methParams = m.GetParametersNoCopy();
numParams = methParams.Length - 1;
}
}
// Now copy over the parameter info's and change their
// owning member info to the current property info.
ParameterInfo[] propParams = new ParameterInfo[numParams];
for (int i = 0; i < numParams; i++)
propParams[i] = new RuntimeParameterInfo((RuntimeParameterInfo)methParams[i], this);
m_parameters = propParams;
}
return m_parameters;
}
public override PropertyAttributes Attributes
{
get
{
return m_flags;
}
}
public override bool CanRead
{
get
{
return m_getterMethod != null;
}
}
public override bool CanWrite
{
get
{
return m_setterMethod != null;
}
}
#endregion
#region Dynamic
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override Object GetValue(Object obj,Object[] index)
{
return GetValue(obj, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override Object GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetGetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_GetMethNotFnd"));
return m.Invoke(obj, invokeAttr, binder, index, null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public override void SetValue(Object obj, Object value, Object[] index)
{
SetValue(obj,
value,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static,
null,
index,
null);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
{
MethodInfo m = GetSetMethod(true);
if (m == null)
throw new ArgumentException(System.Environment.GetResourceString("Arg_SetMethNotFnd"));
Object[] args = null;
if (index != null)
{
args = new Object[index.Length + 1];
for(int i=0;i<index.Length;i++)
args[i] = index[i];
args[index.Length] = value;
}
else
{
args = new Object[1];
args[0] = value;
}
m.Invoke(obj, invokeAttr, binder, args, culture);
}
#endregion
#endregion
#region ISerializable Implementation
[System.Security.SecurityCritical] // auto-generated
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
MemberInfoSerializationHolder.GetSerializationInfo(
info,
Name,
ReflectedTypeInternal,
ToString(),
SerializationToString(),
MemberTypes.Property,
null);
}
internal string SerializationToString()
{
return FormatNameAndSig(true);
}
#endregion
}
}
| |
using System;
using System.Numerics;
namespace NatiMath
{
/// <summary>
/// Class for operating with numeric fractions.
/// </summary>
public class Fraction
{
/// <summary>
/// Value of the numerator part of the fraction.
/// </summary>
public BigInteger Numerator { get; private set; }
/// <summary>
/// Value of the denominator part of the fraction.
/// </summary>
public BigInteger Denominator { get; private set; }
/// <summary>
/// Constructs a fraction object using the provided numerator and denominator.
/// </summary>
/// <param name="numerator">Value of the fraction's numerator.</param>
/// <param name="denominator">Value of the fraction's denominator.</param>
public Fraction(BigInteger numerator, BigInteger denominator)
{
// Copy the values
Numerator = numerator;
Denominator = denominator;
// Simplify the fraction
Simplify();
}
/// <summary>
/// Constructs a fraction object from a whole number.
/// When representing a whole number as a fraction, the numerator is equal to
/// the value of the number and denominator is always equal to zero.
/// </summary>
/// <param name="number">A whole number to be represented by the fraction.</param>
public Fraction(BigInteger number) : this(number, 1)
{
}
/// <summary>
/// An overload of the default constructor that uses standard integers instead of big integers.
/// </summary>
/// <param name="numerator">Numerator value of the fraction.</param>
/// <param name="denominator">Denominator value of the fraction. Set to 1 be default (when representing whole numbers).</param>
public Fraction(int numerator, int denominator = 1)
{
// Convert the integer values into big integers and copy them
Numerator = numerator;
Denominator = denominator;
// Simplify the fraction
Simplify();
}
/// <summary>
/// Constructs the fraction object from a double precision floating point value.
/// </summary>
/// <param name="value">Double precision floating point value to construct the fraction from.</param>
public Fraction(double value)
{
// Example:
// input value = 1.25
// generated fraction = 125/100
// simplified fraction = 5/4
// Get the currently used decimal separator
string decimalSeparator = System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Get a string representation of the input double value
string strValue = value.ToString();
// Get the numerator by removing the decimal separator from the string representation
// of the double value and treating the remainder of the string as a whole number
if (BigInteger.TryParse(strValue.Replace(decimalSeparator, string.Empty), out BigInteger numerator))
{
// Copy the numerator
Numerator = numerator;
}
// The parsing has failed
else
{
// Throw an exception
throw new ArgumentException();
}
// Get index of the decimal separator
int decimalSeparatorIdx = strValue.IndexOf(decimalSeparator);
// Calculate the number of decimal digits
int decimalDigits = 0;
// If the index of the decimal separator is below zero, there are no decimal digits
if (decimalSeparatorIdx >= 0)
{
// The number of decimal digits is equal to the index of the last digit minus the index of the decimal separator
decimalDigits = strValue.Length - 1 - decimalSeparatorIdx;
}
// Calculate the denominator
Denominator = BigInteger.Pow(10, decimalDigits);
// Simplify the fraction
Simplify();
}
/// <summary>
/// Simplifies the fraction as much as possible without losing precision.
/// Also checks for the denominator being zero, which could result in a division by zero.
/// This method should be called after each numeric modification of the fraction.
/// </summary>
private void Simplify()
{
// Make sure the denominator is never equal to zero
if (Denominator == 0)
{
// If the denominator is equal to zero, throw a division-by-zero exception
throw new DivideByZeroException("Denominator of a fraction must not be equal to zero!");
}
// In a fraction with a negative value, the numerator part should be negative rather than the denominator part
// If the denominator is negative
if (Denominator.Sign < 0)
{
// Negate both parts of the fraction
Numerator = -Numerator;
Denominator = -Denominator;
}
// Get the greatest common divisor of the numerator and the denominator
BigInteger gcd = BigInteger.GreatestCommonDivisor(Numerator, Denominator);
// Divide both parts of the fraction by the GCD
Numerator /= gcd;
Denominator /= gcd;
}
private static BigInteger LeastCommonDenominator(Fraction a, Fraction b, out BigInteger numeratorA, out BigInteger numeratorB)
{
// Get the GCD of the input denominators
BigInteger denomGcd = BigInteger.GreatestCommonDivisor(a.Denominator, b.Denominator);
// Calculate by how much will each part of each of the fractions have to be multiplied
BigInteger multA = (b.Denominator / denomGcd);
BigInteger multB = (a.Denominator / denomGcd);
// Calcuate the new numerators
numeratorA = a.Numerator * multA;
numeratorB = b.Numerator * multA;
// Calculate the least common multiply of the denominators and return it
return multA * multB;
}
/// <summary>
/// Compares this fraction object to another object of an unknown type.
/// </summary>
/// <param name="obj">Object to compare with.</param>
/// <returns>Returns true if the input object is a fraction with the same value.</returns>
public override bool Equals(object obj)
{
if (obj != null && obj is Fraction)
{
Fraction f = obj as Fraction;
return f.Numerator == Numerator && f.Denominator == Denominator;
}
else
{
return false;
}
}
/// <summary>
/// Calculates the hash code of this fraction.
/// </summary>
/// <returns>Returns the hash code of this fraction.</returns>
public override int GetHashCode()
{
return (int)Numerator ^ (int)Denominator;
}
/// <summary>
/// Convert the fraction to a string.
/// The denominator may be omitted based on its value and the value of the input argument.
/// </summary>
/// <param name="forceFractionForm">Determines if the denominator should be included even if its value is 1.</param>
/// <returns>Returns a string representation of the fraction.</returns>
public string ToString(bool forceFractionForm)
{
// If the demoniator is not equal to 1 or the input argument explicitly requires a fraction form
if (Denominator != 1 || forceFractionForm)
{
// Convert the value of the fraction to its string representation in a fraction form
return string.Format("{0}/{1}", Numerator, Denominator);
}
// Otherwise, if the denominator is equal to 1 and the fraction form is not required
else
{
// Return a string representing the value of the fraction in the form of a whole number
return Numerator.ToString();
}
}
/// <summary>
/// Converts the fraction to a string.
/// Omits the denominator if its value is 1.
/// </summary>
/// <returns>Returns a string representation of the fraction.</returns>
public override string ToString()
{
return ToString(false);
}
/// <summary>
/// Coverts the fraction to a double precision floating point value.
/// </summary>
/// <returns>Returns the value of the fraction represented as a double precision floating point value.</returns>
public double ToDouble()
{
// If the denominator is 1 - if the fraction represents a whole number
if (Denominator == 1)
{
// Return the value of the numerator as a double
return (double)Numerator;
}
// Otherwise, if the fraction doesn't represent a whole number
else
{
// Divide the numerator by the denominator, both represented as floating point values, and return the result
return (double)Numerator / (double)Denominator;
}
}
/// <summary>
/// Equality operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the input fractions are equal, false otherwise.</returns>
public static bool operator ==(Fraction a, Fraction b) => a.Equals(b);
/// <summary>
/// Inequality operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the input fractions are not equal, false if they are equal.</returns>
public static bool operator !=(Fraction a, Fraction b) => !(a == b);
/// <summary>
/// Less than operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the value of the first fraction is less than the value of the second fraction.</returns>
public static bool operator <(Fraction a, Fraction b)
{
// Get the numerator values when converted to a common denominator
LeastCommonDenominator(a, b, out BigInteger numerA, out BigInteger numerB);
return numerA < numerB;
}
/// <summary>
/// Greater than operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the value of the first fraction is greater than the value of the second fraction.</returns>
public static bool operator >(Fraction a, Fraction b)
{
// Get the numerator values when converted to a common denominator
LeastCommonDenominator(a, b, out BigInteger numerA, out BigInteger numerB);
return numerA > numerB;
}
/// <summary>
/// Less than or equal operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the value of the first fraction is less than the value of the second fraction or if their values are equal.</returns>
public static bool operator <=(Fraction a, Fraction b)
{
// Return true if the fractions are equal
if (a == b)
{
return true;
}
// If the fractions are not equal
else
{
// Perform a "less than" comparison
return a < b;
}
}
/// <summary>
/// Greater than or equal operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns true if the value of the first fraction is greater than the value of the second fraction or if their values are equal.</returns>
public static bool operator >=(Fraction a, Fraction b)
{
// Return true if the fractions are equal
if (a == b)
{
return true;
}
// If the fractions are not equal
else
{
// Perform a "greater than" comparison
return a > b;
}
}
/// <summary>
/// Negation (officially unary subtraction) operator overload.
/// </summary>
/// <param name="a">Input fraction.</param>
/// <returns>Returns a fraction with a negated value of the input fraction.</returns>
public static Fraction operator -(Fraction a)
{
return new Fraction(-a.Numerator, a.Denominator);
}
/// <summary>
/// Inversion (officially bitwise complement) operator overload.
/// </summary>
/// <param name="a">Input fraction.</param>
/// <returns>Returns an inverted fraction to the input fraction.</returns>
public static Fraction operator ~(Fraction a)
{
return new Fraction(a.Denominator, a.Numerator);
}
/// <summary>
/// Addition operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns a fraction with the value equal to the added values of the input fractions.</returns>
public static Fraction operator +(Fraction a, Fraction b)
{
// Get the least common denominator and the new numerator values
BigInteger commonDenom = LeastCommonDenominator(a, b, out BigInteger numerA, out BigInteger numerB);
// Create the result fraction by adding the numerators and using the common denominator
return new Fraction(numerA + numerB, commonDenom);
}
/// <summary>
/// Subtraction operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns a fraction with the value equal to the difference of the input fractions.</returns>
public static Fraction operator -(Fraction a, Fraction b)
{
// Get the least common denominator and the new numerator values
BigInteger commonDenom = LeastCommonDenominator(a, b, out BigInteger numerA, out BigInteger numerB);
// Create the result fraction by subtracting the second numerator from the first numerator and using the common denominator
return new Fraction(numerA - numerB, commonDenom);
}
/// <summary>
/// Multiplication operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns a fraction with the value equal to the multiplied values of the input fractions.</returns>
public static Fraction operator *(Fraction a, Fraction b)
{
// (k/l)*(m/n) = (k*m)/(l*n)
return new Fraction(a.Numerator * b.Numerator, a.Denominator * b.Denominator);
}
/// <summary>
/// Division operator overload.
/// </summary>
/// <param name="a">First fraction.</param>
/// <param name="b">Second fraction.</param>
/// <returns>Returns a fraction with the value equal to the value of the first fraction divided by the value of the second fraction.</returns>
public static Fraction operator /(Fraction a, Fraction b)
{
// (k/l)/(m/n) = (k/l)*(n/m) = (k*n)/(l*m)
return new Fraction(a.Numerator * b.Denominator, a.Denominator * b.Numerator);
}
/// <summary>
/// Exponent / power (officially XOR) operator overload.
/// </summary>
/// <param name="a">The input fraction to raise to the exponent power.</param>
/// <param name="exponent">The exponent to raise the fraction by.</param>
/// <returns></returns>
public static Fraction operator ^(Fraction a, int exponent)
{
// The exponent is higher than or equal to zero
if (exponent >= 0)
{
// (a/b)^n = (a^n)/(b^n)
return new Fraction(BigInteger.Pow(a.Numerator, exponent), BigInteger.Pow(a.Denominator, exponent));
}
// The exponent is a negative number
else
{
// (a/b)^(-n) = (b^n)/(a^n)
return new Fraction(BigInteger.Pow(a.Denominator, -exponent), BigInteger.Pow(a.Numerator, -exponent));
}
}
/// <summary>
/// Implicit type conversion from BigInteger to Fraction.
/// </summary>
/// <param name="value">Input value.</param>
public static implicit operator Fraction(BigInteger value)
{
return new Fraction(value);
}
/// <summary>
/// Implicit type conversion from int to Fraction.
/// </summary>
/// <param name="value">Input value.</param>
public static implicit operator Fraction(int value)
{
return new Fraction(value);
}
/// <summary>
/// Implicit type conversion from double to Fraction.
/// </summary>
/// <param name="value">Input value.</param>
public static implicit operator Fraction(double value)
{
return new Fraction(value);
}
/// <summary>
/// Implicit type conversion from float to Fraction.
/// </summary>
/// <param name="value">Input value.</param>
public static implicit operator Fraction(float value)
{
return new Fraction(value);
}
/// <summary>
/// Explicit type conversion from Fraction to double.
/// </summary>
/// <param name="value">Returns a double precision floating point value representing the value of the input fraction.</param>
public static explicit operator double(Fraction value)
{
return value.ToDouble();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.InteropServices;
public struct ValX1<T> {}
public struct ValX2<T,U> {}
public struct ValX3<T,U,V>{}
public class RefX1<T> {}
public class RefX2<T,U> {}
public class RefX3<T,U,V>{}
[StructLayout(LayoutKind.Sequential)]
public class GenBase<T>
{
public T Fld10;
public int _int0 = 0;
public double _double0 = 0;
public string _string0 = "string0";
public Guid _Guid0 = new Guid();
public T Fld11;
public int _int1 = int.MaxValue;
public double _double1 = double.MaxValue;
public string _string1 = "string1";
public Guid _Guid1 = new Guid(1,2,3,4,5,6,7,8,9,10,11);
public T Fld12;
}
[StructLayout(LayoutKind.Sequential)]
public class GenInt : GenBase<int>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenDouble: GenBase<double>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenString : GenBase<String>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenObject : GenBase<object>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenGuid : GenBase<Guid>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenConstructedReference : GenBase<RefX1<int>>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenConstructedValue: GenBase<ValX1<string>>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenInt1DArray : GenBase<int[]>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenString2DArray : GenBase<string[,]>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
[StructLayout(LayoutKind.Sequential)]
public class GenIntJaggedArray : GenBase<int[][]>
{
public void VerifyLayout()
{
Test.Eval(_int0 == 0);
Test.Eval(_int1 == int.MaxValue) ;
Test.Eval(_double0 == 0) ;
Test.Eval(_double1 == double.MaxValue) ;
Test.Eval(base._string0.Equals("string0"));
Test.Eval(base._string1.Equals("string1"));
Test.Eval(_Guid0 == new Guid());
Test.Eval(_Guid1 == new Guid(1,2,3,4,5,6,7,8,9,10,11));
}
}
public class Test
{
public static int counter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
new GenInt().VerifyLayout();
new GenDouble().VerifyLayout();
new GenString().VerifyLayout();
new GenObject().VerifyLayout();
new GenGuid().VerifyLayout();
new GenConstructedReference().VerifyLayout();
new GenConstructedValue().VerifyLayout();
new GenInt1DArray().VerifyLayout();
new GenString2DArray().VerifyLayout();
new GenIntJaggedArray().VerifyLayout();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
/* Copyright 2019 Sannel Software, L.L.C.
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 Microsoft.AspNetCore.Mvc;
using Moq;
using Sannel.House.Base.Models;
using Sannel.House.Devices.Controllers;
using Sannel.House.Devices.Interfaces;
using Sannel.House.Devices.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Sannel.House.Devices.Tests.Controllers
{
public class AlternateIdControllerTest : BaseTests
{
[Fact]
public void ConstructorArgumentsTest()
{
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
Assert.Throws<ArgumentNullException>("service",
() => new AlternateIdController(null, null));
Assert.Throws<ArgumentNullException>("logger",
() => new AlternateIdController(new Mock<IDeviceService>().Object, null));
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
}
[Fact]
public async Task GetAlternateIdsTest()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Get(-1);
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("deviceId", err.Key);
Assert.Equal(HttpStatusCode.BadRequest, error.StatusCode);
Assert.Equal("Device Id must be greater then or equal to 0", err.Value.First());
repo.Setup(i => i.GetAlternateIdsForDeviceAsync(1)).ReturnsAsync(() => new List<AlternateDeviceId>());
result = await controller.Get(1);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
Assert.Equal(HttpStatusCode.NotFound, error.StatusCode);
err = error.Errors.First();
Assert.Equal("device", err.Key);
Assert.Equal("Device not found", err.Value.First());
repo.Setup(i => i.GetAlternateIdsForDeviceAsync(1)).ReturnsAsync(() =>
new List<AlternateDeviceId>()
{
}
);
result = await controller.Get(1);
nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
var deviceResponse =
Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(deviceResponse);
var altId1 = new AlternateDeviceId()
{
DeviceId = 2,
Uuid = Guid.NewGuid(),
MacAddress = 2,
DateCreated = DateTime.UtcNow
};
var altId2 = new AlternateDeviceId
{
DeviceId = 2,
Uuid = Guid.NewGuid(),
MacAddress = 3,
DateCreated = DateTime.UtcNow
};
repo.Setup(i => i.GetAlternateIdsForDeviceAsync(2)).ReturnsAsync(() =>
new List<AlternateDeviceId>()
{
altId1,
altId2
}
);
result = await controller.Get(2);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var devices =
Assert.IsAssignableFrom<ResponseModel<IEnumerable<AlternateDeviceId>>>(okor.Value);
Assert.NotNull(devices);
Assert.Equal(2, devices.Data.Count());
var alt = devices.Data.ElementAt(0);
Assert.Equal(altId1.DeviceId, alt.DeviceId);
Assert.Equal(altId1.Uuid, alt.Uuid);
Assert.Equal(altId1.MacAddress, alt.MacAddress);
Assert.Equal(altId1.DateCreated, alt.DateCreated);
alt = devices.Data.ElementAt(1);
Assert.Equal(altId2.DeviceId, alt.DeviceId);
Assert.Equal(altId2.Uuid, alt.Uuid);
Assert.Equal(altId2.MacAddress, alt.MacAddress);
Assert.Equal(altId2.DateCreated, alt.DateCreated);
}
[Fact]
public async Task PostMacAddressTest()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Post(-1, -1);
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("macAddress", err.Key);
Assert.Equal("Invalid MacAddress it must be greater then 0", err.Value.First());
result = await controller.Post(0xD5A6E4539A1F, -1);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("deviceId", err.Key);
Assert.Equal("Device Id must be greater then 0", err.Value.First());
repo.Setup(i => i.AddAlternateMacAddressAsync(20, 0xD5A6E4539A1F)).ThrowsAsync(new AlternateDeviceIdException("Device already connected"));
result = await controller.Post(0xD5A6E4539A1F, 20);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("macAddress", err.Key);
Assert.Equal("That mac address is already connected to a device", err.Value.First());
repo.Setup(i => i.AddAlternateMacAddressAsync(20, 0xD5A6E4539A1F)).ReturnsAsync((Device?)null);
result = await controller.Post(0xD5A6E4539A1F, 20);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("notFound", err.Key);
Assert.Equal("No device found with that id", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.AddAlternateMacAddressAsync(20, 0xD5A6E4539A1F)).ReturnsAsync(device1);
result = await controller.Post(0xD5A6E4539A1F, 20);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
[Fact]
public async Task PostUuidTest()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Post(Guid.Empty, -1);
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("uuid", err.Key);
Assert.Equal("Uuid must be a valid Guid and not Guid.Empty", err.Value.First());
result = await controller.Post(Guid.NewGuid(), -1);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("deviceId", err.Key);
Assert.Equal("Device Id must be greater then or equal to 0", err.Value.First());
var id = Guid.NewGuid();
repo.Setup(i => i.AddAlternateUuidAsync(20, id)).ThrowsAsync(new AlternateDeviceIdException("Device already connected"));
result = await controller.Post(id, 20);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("uuid", err.Key);
Assert.Equal("That Uuid is already connected to a device", err.Value.First());
repo.Setup(i => i.AddAlternateUuidAsync(20, id)).ReturnsAsync((Device?)null);
result = await controller.Post(id, 20);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("notFound", err.Key);
Assert.Equal("No device found with that id", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.AddAlternateUuidAsync(20, id)).ReturnsAsync(device1);
result = await controller.Post(id, 20);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
[Fact]
public async Task PostManufactureIdTest()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
var result = await controller.Post("", null, -1);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("manufacture", err.Key);
Assert.Equal("manufacture must not be null or whitespace", err.Value.First());
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
result = await controller.Post("Particle", null, -1);
#pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type.
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("manufactureId", err.Key);
Assert.Equal("manufactureId must not be null or whitespace", err.Value.First());
result = await controller.Post("Particle", "Tinker", -1);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("deviceId", err.Key);
Assert.Equal("Device Id must be greater then or equal to 0", err.Value.First());
var manufacture = "Particle";
var manufactureId = "Photon";
repo.Setup(i => i.AddAlternateManufactureIdAsync(20, manufacture, manufactureId)).ThrowsAsync(new AlternateDeviceIdException("Device already connected"));
result = await controller.Post(manufacture, manufactureId, 20);
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("manufactureId", err.Key);
Assert.Equal("That Manufacture and ManufactureId is already connected to a device", err.Value.First());
repo.Setup(i => i.AddAlternateManufactureIdAsync(20, manufacture, manufactureId)).ReturnsAsync((Device?)null);
result = await controller.Post(manufacture, manufactureId, 20);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("notFound", err.Key);
Assert.Equal("No device found with that id", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.AddAlternateManufactureIdAsync(20, manufacture, manufactureId)).ReturnsAsync(device1);
result = await controller.Post(manufacture, manufactureId, 20);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
[Fact]
public async Task DeleteMacAddressAsync()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Delete(-1);
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("macAddress", err.Key);
Assert.Equal("Invalid MacAddress it must be greater then or equal to 0", err.Value.First());
repo.Setup(i => i.RemoveAlternateMacAddressAsync(0xD5A6E4539A1F)).ReturnsAsync((Device?)null);
result = await controller.Delete(0xD5A6E4539A1F);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("macAddress", err.Key);
Assert.Equal("Mac Address not found", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.RemoveAlternateMacAddressAsync(0xD5A6E4539A1F)).ReturnsAsync(device1);
result = await controller.Delete(0xD5A6E4539A1F);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
[Fact]
public async Task DeleteUuidAsync()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Delete(Guid.Empty);
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("uuid", err.Key);
Assert.Equal("Uuid must be a valid Guid and not Guid.Empty", err.Value.First());
var id = Guid.NewGuid();
repo.Setup(i => i.RemoveAlternateUuidAsync(id)).ReturnsAsync((Device?)null);
result = await controller.Delete(id);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("uuid", err.Key);
Assert.Equal("Uuid not found", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.RemoveAlternateUuidAsync(id)).ReturnsAsync(device1);
result = await controller.Delete(id);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
[Fact]
public async Task DeleteManufactureIdAsync()
{
var repo = new Mock<IDeviceService>();
using var controller = new AlternateIdController(repo.Object, CreateLogger<AlternateIdController>());
var result = await controller.Delete("", "Photon");
var bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
var error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
var err = error.Errors.First();
Assert.Equal("manufacture", err.Key);
Assert.Equal("Manufacture must not be null or whitespace", err.Value.First());
result = await controller.Delete("Particle", "");
bror = Assert.IsAssignableFrom<BadRequestObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(bror.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("manufactureId", err.Key);
Assert.Equal("ManufactureId must not be null or whitespace", err.Value.First());
var manufacture = "Particle";
var manufactureId = "Photon";
repo.Setup(i => i.RemoveAlternateManufactureIdAsync(manufacture, manufactureId)).ReturnsAsync((Device?)null);
result = await controller.Delete(manufacture, manufactureId);
var nfor = Assert.IsAssignableFrom<NotFoundObjectResult>(result.Result);
error = Assert.IsAssignableFrom<ErrorResponseModel>(nfor.Value);
Assert.NotNull(error);
Assert.Single(error.Errors);
err = error.Errors.First();
Assert.Equal("manufactureid", err.Key);
Assert.Equal("Manufacture/ManufactureId not found", err.Value.First());
var device1 = new Device()
{
DeviceId = 20,
Name = "Test Name",
IsReadOnly = true,
Description = "Dest Description",
DateCreated = DateTime.UtcNow,
DisplayOrder = 2
};
repo.Setup(i => i.RemoveAlternateManufactureIdAsync(manufacture, manufactureId)).ReturnsAsync(device1);
result = await controller.Delete(manufacture, manufactureId);
var okor = Assert.IsAssignableFrom<OkObjectResult>(result.Result);
var device = Assert.IsAssignableFrom<ResponseModel<Device>>(okor.Value);
AssertEqual(device1, device.Data);
}
}
}
| |
// 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.Buffers;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using System.Diagnostics;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace System
{
/// <summary>
/// ReadOnlyMemory represents a contiguous region of arbitrary similar to ReadOnlySpan.
/// Unlike ReadOnlySpan, it is not a byref-like type.
/// </summary>
public struct ReadOnlyMemory<T>
{
// The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
// if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
// else, object _arrayOrOwnedMemory is a T[]
private readonly object _arrayOrOwnedMemory;
private readonly int _index;
private readonly int _length;
private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
_arrayOrOwnedMemory = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
/// reference (Nothing in Visual Basic).</exception>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[] array, int start, int length)
{
if (array == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_arrayOrOwnedMemory = array;
_index = start;
_length = length;
}
// Constructor for internal use only.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(OwnedMemory<T> owner, int index, int length)
{
if (owner == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
if (index < 0 || length < 0)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
_arrayOrOwnedMemory = owner;
_index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
/// <summary>
/// Returns an empty <see cref="Memory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty { get; } =
#if !netstandard11
Array.Empty<T>();
#else
new T[0];
#endif
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
if (_index < 0)
return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >=Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
if (_index < 0)
return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (_index < 0)
return ((OwnedMemory<T>)_arrayOrOwnedMemory).AsSpan().Slice(_index & RemoveOwnedFlagBitMask, _length);
return new ReadOnlySpan<T>((T[])_arrayOrOwnedMemory, _index, _length);
}
}
/// <summary>
/// Returns a handle for the array.
/// <param name="pin">If pin is true, the GC will not move the array and hence its address can be taken</param>
/// </summary>
public unsafe MemoryHandle Retain(bool pin = false)
{
MemoryHandle memoryHandle;
if (pin)
{
if (_index < 0)
{
memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
}
else
{
var array = (T[])_arrayOrOwnedMemory;
var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>((void*)handle.AddrOfPinnedObject(), _index);
memoryHandle = new MemoryHandle(null, pointer, handle);
}
}
else
{
if (_index < 0)
{
((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
}
else
{
memoryHandle = new MemoryHandle(null);
}
}
return memoryHandle;
}
/// <summary>
/// Get an array segment from the underlying memory.
/// If unable to get the array segment, return false with a default array segment.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public bool DangerousTryGetArray(out ArraySegment<T> arraySegment)
{
if (_index < 0)
{
if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
{
arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
return true;
}
}
else
{
arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
return true;
}
arraySegment = default(ArraySegment<T>);
return false;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
_index == other._index &&
_length == other._length;
}
/// <summary>
/// Serves as the default hash function.
/// </summary>
[EditorBrowsable( EditorBrowsableState.Never)]
public override int GetHashCode()
{
return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
}
private static int CombineHashCodes(int left, int right)
{
return ((left << 5) + left) ^ right;
}
private static int CombineHashCodes(int h1, int h2, int h3)
{
return CombineHashCodes(CombineHashCodes(h1, h2), h3);
}
}
}
| |
// 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.Security.Permissions {
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
#if FEATURE_CAS_POLICY
using SecurityElement = System.Security.SecurityElement;
#endif // FEATURE_CAS_POLICY
using System.Security.AccessControl;
using System.Security.Util;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileIOPermissionAccess
{
NoAccess = 0x00,
Read = 0x01,
Write = 0x02,
Append = 0x04,
PathDiscovery = 0x08,
AllAccess = 0x0F,
}
[System.Runtime.InteropServices.ComVisible(true)]
[Serializable]
sealed public class FileIOPermission : CodeAccessPermission, IUnrestrictedPermission, IBuiltInPermission
{
private FileIOAccess m_read;
private FileIOAccess m_write;
private FileIOAccess m_append;
private FileIOAccess m_pathDiscovery;
[OptionalField(VersionAdded = 2)]
private FileIOAccess m_viewAcl;
[OptionalField(VersionAdded = 2)]
private FileIOAccess m_changeAcl;
private bool m_unrestricted;
public FileIOPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
m_unrestricted = true;
}
else if (state == PermissionState.None)
{
m_unrestricted = false;
}
else
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState"));
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String path )
{
VerifyAccess( access );
String[] pathList = new String[] { path };
AddPathList( access, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, String[] pathList )
{
VerifyAccess( access );
AddPathList( access, pathList, false, true, false );
}
#if FEATURE_MACL
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String path )
{
VerifyAccess( access );
String[] pathList = new String[] { path };
AddPathList( access, control, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList )
: this( access, control, pathList, true, true )
{
}
#endif
[System.Security.SecurityCritical] // auto-generated
internal FileIOPermission( FileIOPermissionAccess access, String[] pathList, bool checkForDuplicates, bool needFullPath )
{
VerifyAccess( access );
AddPathList( access, pathList, checkForDuplicates, needFullPath, true );
}
#if FEATURE_MACL
[System.Security.SecurityCritical] // auto-generated
internal FileIOPermission( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates, bool needFullPath )
{
VerifyAccess( access );
AddPathList( access, control, pathList, checkForDuplicates, needFullPath, true );
}
#endif
public void SetPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
if(path == null)
pathList = new String[] {};
else
pathList = new String[] { path };
SetPathList( access, pathList, false );
}
public void SetPathList( FileIOPermissionAccess access, String[] pathList )
{
SetPathList( access, pathList, true );
}
internal void SetPathList( FileIOPermissionAccess access,
String[] pathList, bool checkForDuplicates )
{
SetPathList( access, AccessControlActions.None, pathList, checkForDuplicates );
}
[System.Security.SecuritySafeCritical] // auto-generated
internal void SetPathList( FileIOPermissionAccess access, AccessControlActions control, String[] pathList, bool checkForDuplicates )
{
VerifyAccess( access );
if ((access & FileIOPermissionAccess.Read) != 0)
m_read = null;
if ((access & FileIOPermissionAccess.Write) != 0)
m_write = null;
if ((access & FileIOPermissionAccess.Append) != 0)
m_append = null;
if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
m_pathDiscovery = null;
#if FEATURE_MACL
if ((control & AccessControlActions.View) != 0)
m_viewAcl = null;
if ((control & AccessControlActions.Change) != 0)
m_changeAcl = null;
#else
m_viewAcl = null;
m_changeAcl = null;
#endif
m_unrestricted = false;
#if FEATURE_MACL
AddPathList( access, control, pathList, checkForDuplicates, true, true );
#else
AddPathList( access, pathList, checkForDuplicates, true, true );
#endif
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String path )
{
String[] pathList;
if(path == null)
pathList = new String[] {};
else
pathList = new String[] { path };
AddPathList( access, pathList, false, true, false );
}
[System.Security.SecuritySafeCritical] // auto-generated
public void AddPathList( FileIOPermissionAccess access, String[] pathList )
{
AddPathList( access, pathList, true, true, true );
}
[System.Security.SecurityCritical] // auto-generated
internal void AddPathList( FileIOPermissionAccess access, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList )
{
AddPathList( access, AccessControlActions.None, pathListOrig, checkForDuplicates, needFullPath, copyPathList );
}
[System.Security.SecurityCritical] // auto-generated
internal void AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, bool checkForDuplicates, bool needFullPath, bool copyPathList)
{
if (pathListOrig == null)
{
throw new ArgumentNullException( "pathList" );
}
if (pathListOrig.Length == 0)
{
throw new ArgumentException( Environment.GetResourceString("Argument_EmptyPath" ));
}
Contract.EndContractBlock();
VerifyAccess(access);
if (m_unrestricted)
return;
String[] pathList = pathListOrig;
if(copyPathList)
{
// Make a copy of pathList (in case its value changes after we check for illegal chars)
pathList = new String[pathListOrig.Length];
Array.Copy(pathListOrig, pathList, pathListOrig.Length);
}
CheckIllegalCharacters( pathList );
ArrayList pathArrayList = StringExpressionSet.CreateListFromExpressions(pathList, needFullPath);
if ((access & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
{
m_read = new FileIOAccess();
}
m_read.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
{
m_write = new FileIOAccess();
}
m_write.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
{
m_append = new FileIOAccess();
}
m_append.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((access & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
{
m_pathDiscovery = new FileIOAccess( true );
}
m_pathDiscovery.AddExpressions( pathArrayList, checkForDuplicates);
}
#if FEATURE_MACL
if ((control & AccessControlActions.View) != 0)
{
if (m_viewAcl == null)
{
m_viewAcl = new FileIOAccess();
}
m_viewAcl.AddExpressions( pathArrayList, checkForDuplicates);
}
if ((control & AccessControlActions.Change) != 0)
{
if (m_changeAcl == null)
{
m_changeAcl = new FileIOAccess();
}
m_changeAcl.AddExpressions( pathArrayList, checkForDuplicates);
}
#endif
}
[SecuritySafeCritical]
public String[] GetPathList( FileIOPermissionAccess access )
{
VerifyAccess( access );
ExclusiveAccess( access );
if (AccessIsSet( access, FileIOPermissionAccess.Read ))
{
if (m_read == null)
{
return null;
}
return m_read.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.Write ))
{
if (m_write == null)
{
return null;
}
return m_write.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.Append ))
{
if (m_append == null)
{
return null;
}
return m_append.ToStringArray();
}
if (AccessIsSet( access, FileIOPermissionAccess.PathDiscovery ))
{
if (m_pathDiscovery == null)
{
return null;
}
return m_pathDiscovery.ToStringArray();
}
// not reached
return null;
}
public FileIOPermissionAccess AllLocalFiles
{
get
{
if (m_unrestricted)
return FileIOPermissionAccess.AllAccess;
FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
if (m_read != null && m_read.AllLocalFiles)
{
access |= FileIOPermissionAccess.Read;
}
if (m_write != null && m_write.AllLocalFiles)
{
access |= FileIOPermissionAccess.Write;
}
if (m_append != null && m_append.AllLocalFiles)
{
access |= FileIOPermissionAccess.Append;
}
if (m_pathDiscovery != null && m_pathDiscovery.AllLocalFiles)
{
access |= FileIOPermissionAccess.PathDiscovery;
}
return access;
}
set
{
if ((value & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
m_read = new FileIOAccess();
m_read.AllLocalFiles = true;
}
else
{
if (m_read != null)
m_read.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
m_write = new FileIOAccess();
m_write.AllLocalFiles = true;
}
else
{
if (m_write != null)
m_write.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
m_append = new FileIOAccess();
m_append.AllLocalFiles = true;
}
else
{
if (m_append != null)
m_append.AllLocalFiles = false;
}
if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
m_pathDiscovery = new FileIOAccess( true );
m_pathDiscovery.AllLocalFiles = true;
}
else
{
if (m_pathDiscovery != null)
m_pathDiscovery.AllLocalFiles = false;
}
}
}
public FileIOPermissionAccess AllFiles
{
get
{
if (m_unrestricted)
return FileIOPermissionAccess.AllAccess;
FileIOPermissionAccess access = FileIOPermissionAccess.NoAccess;
if (m_read != null && m_read.AllFiles)
{
access |= FileIOPermissionAccess.Read;
}
if (m_write != null && m_write.AllFiles)
{
access |= FileIOPermissionAccess.Write;
}
if (m_append != null && m_append.AllFiles)
{
access |= FileIOPermissionAccess.Append;
}
if (m_pathDiscovery != null && m_pathDiscovery.AllFiles)
{
access |= FileIOPermissionAccess.PathDiscovery;
}
return access;
}
set
{
if (value == FileIOPermissionAccess.AllAccess)
{
m_unrestricted = true;
return;
}
if ((value & FileIOPermissionAccess.Read) != 0)
{
if (m_read == null)
m_read = new FileIOAccess();
m_read.AllFiles = true;
}
else
{
if (m_read != null)
m_read.AllFiles = false;
}
if ((value & FileIOPermissionAccess.Write) != 0)
{
if (m_write == null)
m_write = new FileIOAccess();
m_write.AllFiles = true;
}
else
{
if (m_write != null)
m_write.AllFiles = false;
}
if ((value & FileIOPermissionAccess.Append) != 0)
{
if (m_append == null)
m_append = new FileIOAccess();
m_append.AllFiles = true;
}
else
{
if (m_append != null)
m_append.AllFiles = false;
}
if ((value & FileIOPermissionAccess.PathDiscovery) != 0)
{
if (m_pathDiscovery == null)
m_pathDiscovery = new FileIOAccess( true );
m_pathDiscovery.AllFiles = true;
}
else
{
if (m_pathDiscovery != null)
m_pathDiscovery.AllFiles = false;
}
}
}
[Pure]
private static void VerifyAccess( FileIOPermissionAccess access )
{
if ((access & ~FileIOPermissionAccess.AllAccess) != 0)
throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", (int)access));
}
[Pure]
private static void ExclusiveAccess( FileIOPermissionAccess access )
{
if (access == FileIOPermissionAccess.NoAccess)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
if (((int) access & ((int)access-1)) != 0)
{
throw new ArgumentException( Environment.GetResourceString("Arg_EnumNotSingleFlag") );
}
}
private static void CheckIllegalCharacters( String[] str )
{
for (int i = 0; i < str.Length; ++i)
{
Path.CheckInvalidPathChars(str[i], true);
}
}
private static bool AccessIsSet( FileIOPermissionAccess access, FileIOPermissionAccess question )
{
return (access & question) != 0;
}
private bool IsEmpty()
{
return (!m_unrestricted &&
(this.m_read == null || this.m_read.IsEmpty()) &&
(this.m_write == null || this.m_write.IsEmpty()) &&
(this.m_append == null || this.m_append.IsEmpty()) &&
(this.m_pathDiscovery == null || this.m_pathDiscovery.IsEmpty()) &&
(this.m_viewAcl == null || this.m_viewAcl.IsEmpty()) &&
(this.m_changeAcl == null || this.m_changeAcl.IsEmpty()));
}
//------------------------------------------------------
//
// CODEACCESSPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public bool IsUnrestricted()
{
return m_unrestricted;
}
//------------------------------------------------------
//
// IPERMISSION IMPLEMENTATION
//
//------------------------------------------------------
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return this.IsEmpty();
}
FileIOPermission operand = target as FileIOPermission;
if (operand == null)
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
if (operand.IsUnrestricted())
return true;
else if (this.IsUnrestricted())
return false;
else
return ((this.m_read == null || this.m_read.IsSubsetOf( operand.m_read )) &&
(this.m_write == null || this.m_write.IsSubsetOf( operand.m_write )) &&
(this.m_append == null || this.m_append.IsSubsetOf( operand.m_append )) &&
(this.m_pathDiscovery == null || this.m_pathDiscovery.IsSubsetOf( operand.m_pathDiscovery )) &&
(this.m_viewAcl == null || this.m_viewAcl.IsSubsetOf( operand.m_viewAcl )) &&
(this.m_changeAcl == null || this.m_changeAcl.IsSubsetOf( operand.m_changeAcl )));
}
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
FileIOPermission operand = target as FileIOPermission;
if (operand == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
}
else if (this.IsUnrestricted())
{
return target.Copy();
}
if (operand.IsUnrestricted())
{
return this.Copy();
}
FileIOAccess intersectRead = this.m_read == null ? null : this.m_read.Intersect( operand.m_read );
FileIOAccess intersectWrite = this.m_write == null ? null : this.m_write.Intersect( operand.m_write );
FileIOAccess intersectAppend = this.m_append == null ? null : this.m_append.Intersect( operand.m_append );
FileIOAccess intersectPathDiscovery = this.m_pathDiscovery == null ? null : this.m_pathDiscovery.Intersect( operand.m_pathDiscovery );
FileIOAccess intersectViewAcl = this.m_viewAcl == null ? null : this.m_viewAcl.Intersect( operand.m_viewAcl );
FileIOAccess intersectChangeAcl = this.m_changeAcl == null ? null : this.m_changeAcl.Intersect( operand.m_changeAcl );
if ((intersectRead == null || intersectRead.IsEmpty()) &&
(intersectWrite == null || intersectWrite.IsEmpty()) &&
(intersectAppend == null || intersectAppend.IsEmpty()) &&
(intersectPathDiscovery == null || intersectPathDiscovery.IsEmpty()) &&
(intersectViewAcl == null || intersectViewAcl.IsEmpty()) &&
(intersectChangeAcl == null || intersectChangeAcl.IsEmpty()))
{
return null;
}
FileIOPermission intersectPermission = new FileIOPermission(PermissionState.None);
intersectPermission.m_unrestricted = false;
intersectPermission.m_read = intersectRead;
intersectPermission.m_write = intersectWrite;
intersectPermission.m_append = intersectAppend;
intersectPermission.m_pathDiscovery = intersectPathDiscovery;
intersectPermission.m_viewAcl = intersectViewAcl;
intersectPermission.m_changeAcl = intersectChangeAcl;
return intersectPermission;
}
public override IPermission Union(IPermission other)
{
if (other == null)
{
return this.Copy();
}
FileIOPermission operand = other as FileIOPermission;
if (operand == null)
{
throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName));
}
if (this.IsUnrestricted() || operand.IsUnrestricted())
{
return new FileIOPermission( PermissionState.Unrestricted );
}
FileIOAccess unionRead = this.m_read == null ? operand.m_read : this.m_read.Union( operand.m_read );
FileIOAccess unionWrite = this.m_write == null ? operand.m_write : this.m_write.Union( operand.m_write );
FileIOAccess unionAppend = this.m_append == null ? operand.m_append : this.m_append.Union( operand.m_append );
FileIOAccess unionPathDiscovery = this.m_pathDiscovery == null ? operand.m_pathDiscovery : this.m_pathDiscovery.Union( operand.m_pathDiscovery );
FileIOAccess unionViewAcl = this.m_viewAcl == null ? operand.m_viewAcl : this.m_viewAcl.Union( operand.m_viewAcl );
FileIOAccess unionChangeAcl = this.m_changeAcl == null ? operand.m_changeAcl : this.m_changeAcl.Union( operand.m_changeAcl );
if ((unionRead == null || unionRead.IsEmpty()) &&
(unionWrite == null || unionWrite.IsEmpty()) &&
(unionAppend == null || unionAppend.IsEmpty()) &&
(unionPathDiscovery == null || unionPathDiscovery.IsEmpty()) &&
(unionViewAcl == null || unionViewAcl.IsEmpty()) &&
(unionChangeAcl == null || unionChangeAcl.IsEmpty()))
{
return null;
}
FileIOPermission unionPermission = new FileIOPermission(PermissionState.None);
unionPermission.m_unrestricted = false;
unionPermission.m_read = unionRead;
unionPermission.m_write = unionWrite;
unionPermission.m_append = unionAppend;
unionPermission.m_pathDiscovery = unionPathDiscovery;
unionPermission.m_viewAcl = unionViewAcl;
unionPermission.m_changeAcl = unionChangeAcl;
return unionPermission;
}
public override IPermission Copy()
{
FileIOPermission copy = new FileIOPermission(PermissionState.None);
if (this.m_unrestricted)
{
copy.m_unrestricted = true;
}
else
{
copy.m_unrestricted = false;
if (this.m_read != null)
{
copy.m_read = this.m_read.Copy();
}
if (this.m_write != null)
{
copy.m_write = this.m_write.Copy();
}
if (this.m_append != null)
{
copy.m_append = this.m_append.Copy();
}
if (this.m_pathDiscovery != null)
{
copy.m_pathDiscovery = this.m_pathDiscovery.Copy();
}
if (this.m_viewAcl != null)
{
copy.m_viewAcl = this.m_viewAcl.Copy();
}
if (this.m_changeAcl != null)
{
copy.m_changeAcl = this.m_changeAcl.Copy();
}
}
return copy;
}
#if FEATURE_CAS_POLICY
public override SecurityElement ToXml()
{
SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.FileIOPermission" );
if (!IsUnrestricted())
{
if (this.m_read != null && !this.m_read.IsEmpty())
{
esd.AddAttribute( "Read", SecurityElement.Escape( m_read.ToString() ) );
}
if (this.m_write != null && !this.m_write.IsEmpty())
{
esd.AddAttribute( "Write", SecurityElement.Escape( m_write.ToString() ) );
}
if (this.m_append != null && !this.m_append.IsEmpty())
{
esd.AddAttribute( "Append", SecurityElement.Escape( m_append.ToString() ) );
}
if (this.m_pathDiscovery != null && !this.m_pathDiscovery.IsEmpty())
{
esd.AddAttribute( "PathDiscovery", SecurityElement.Escape( m_pathDiscovery.ToString() ) );
}
if (this.m_viewAcl != null && !this.m_viewAcl.IsEmpty())
{
esd.AddAttribute( "ViewAcl", SecurityElement.Escape( m_viewAcl.ToString() ) );
}
if (this.m_changeAcl != null && !this.m_changeAcl.IsEmpty())
{
esd.AddAttribute( "ChangeAcl", SecurityElement.Escape( m_changeAcl.ToString() ) );
}
}
else
{
esd.AddAttribute( "Unrestricted", "true" );
}
return esd;
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void FromXml(SecurityElement esd)
{
CodeAccessPermission.ValidateElement( esd, this );
String et;
if (XMLUtil.IsUnrestricted(esd))
{
m_unrestricted = true;
return;
}
m_unrestricted = false;
et = esd.Attribute( "Read" );
if (et != null)
{
m_read = new FileIOAccess( et );
}
else
{
m_read = null;
}
et = esd.Attribute( "Write" );
if (et != null)
{
m_write = new FileIOAccess( et );
}
else
{
m_write = null;
}
et = esd.Attribute( "Append" );
if (et != null)
{
m_append = new FileIOAccess( et );
}
else
{
m_append = null;
}
et = esd.Attribute( "PathDiscovery" );
if (et != null)
{
m_pathDiscovery = new FileIOAccess( et );
m_pathDiscovery.PathDiscovery = true;
}
else
{
m_pathDiscovery = null;
}
et = esd.Attribute( "ViewAcl" );
if (et != null)
{
m_viewAcl = new FileIOAccess( et );
}
else
{
m_viewAcl = null;
}
et = esd.Attribute( "ChangeAcl" );
if (et != null)
{
m_changeAcl = new FileIOAccess( et );
}
else
{
m_changeAcl = null;
}
}
#endif // FEATURE_CAS_POLICY
/// <internalonly/>
int IBuiltInPermission.GetTokenIndex()
{
return FileIOPermission.GetTokenIndex();
}
internal static int GetTokenIndex()
{
return BuiltInPermissionIndex.FileIOPermissionIndex;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override bool Equals(Object obj)
{
FileIOPermission perm = obj as FileIOPermission;
if(perm == null)
return false;
if(m_unrestricted && perm.m_unrestricted)
return true;
if(m_unrestricted != perm.m_unrestricted)
return false;
if(m_read == null)
{
if(perm.m_read != null && !perm.m_read.IsEmpty())
return false;
}
else if(!m_read.Equals(perm.m_read))
return false;
if(m_write == null)
{
if(perm.m_write != null && !perm.m_write.IsEmpty())
return false;
}
else if(!m_write.Equals(perm.m_write))
return false;
if(m_append == null)
{
if(perm.m_append != null && !perm.m_append.IsEmpty())
return false;
}
else if(!m_append.Equals(perm.m_append))
return false;
if(m_pathDiscovery == null)
{
if(perm.m_pathDiscovery != null && !perm.m_pathDiscovery.IsEmpty())
return false;
}
else if(!m_pathDiscovery.Equals(perm.m_pathDiscovery))
return false;
if(m_viewAcl == null)
{
if(perm.m_viewAcl != null && !perm.m_viewAcl.IsEmpty())
return false;
}
else if(!m_viewAcl.Equals(perm.m_viewAcl))
return false;
if(m_changeAcl == null)
{
if(perm.m_changeAcl != null && !perm.m_changeAcl.IsEmpty())
return false;
}
else if(!m_changeAcl.Equals(perm.m_changeAcl))
return false;
return true;
}
[System.Runtime.InteropServices.ComVisible(false)]
public override int GetHashCode()
{
// This implementation is only to silence a compiler warning.
return base.GetHashCode();
}
/// <summary>
/// Call this method if you don't need a the FileIOPermission for anything other than calling Demand() once.
///
/// This method tries to verify full access before allocating a FileIOPermission object.
/// If full access is there, then we still have to emulate the checks that creating the
/// FileIOPermission object would have performed.
///
/// IMPORTANT: This method should only be used after calling GetFullPath on the path to verify
///
/// </summary>
/// <param name="access"></param>
/// <param name="path"></param>
/// <param name="checkForDuplicates"></param>
/// <param name="needFullPath"></param>
[System.Security.SecuritySafeCritical]
internal static void QuickDemand(FileIOPermissionAccess access, string fullPath, bool checkForDuplicates, bool needFullPath)
{
#if FEATURE_CAS_POLICY
if (!CodeAccessSecurityEngine.QuickCheckForAllDemands())
{
new FileIOPermission(access, new string[] { fullPath }, checkForDuplicates, needFullPath).Demand();
}
else
#endif
{
//Emulate FileIOPermission checks
Path.CheckInvalidPathChars(fullPath, true);
if (fullPath.Length > 2 && fullPath.IndexOf(':', 2) != -1)
{
throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
}
}
}
}
[Serializable]
internal sealed class FileIOAccess
{
#if !FEATURE_CASE_SENSITIVE_FILESYSTEM
private bool m_ignoreCase = true;
#else
private bool m_ignoreCase = false;
#endif // !FEATURE_CASE_SENSITIVE_FILESYSTEM
private StringExpressionSet m_set;
private bool m_allFiles;
private bool m_allLocalFiles;
private bool m_pathDiscovery;
private const String m_strAllFiles = "*AllFiles*";
private const String m_strAllLocalFiles = "*AllLocalFiles*";
public FileIOAccess()
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
m_pathDiscovery = false;
}
public FileIOAccess( bool pathDiscovery )
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
m_pathDiscovery = pathDiscovery;
}
[System.Security.SecurityCritical] // auto-generated
public FileIOAccess( String value )
{
if (value == null)
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = false;
m_allLocalFiles = false;
}
else if (value.Length >= m_strAllFiles.Length && String.Compare( m_strAllFiles, value, StringComparison.Ordinal) == 0)
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = true;
m_allLocalFiles = false;
}
else if (value.Length >= m_strAllLocalFiles.Length && String.Compare( m_strAllLocalFiles, 0, value, 0, m_strAllLocalFiles.Length, StringComparison.Ordinal) == 0)
{
m_set = new StringExpressionSet( m_ignoreCase, value.Substring( m_strAllLocalFiles.Length ), true );
m_allFiles = false;
m_allLocalFiles = true;
}
else
{
m_set = new StringExpressionSet( m_ignoreCase, value, true );
m_allFiles = false;
m_allLocalFiles = false;
}
m_pathDiscovery = false;
}
public FileIOAccess( bool allFiles, bool allLocalFiles, bool pathDiscovery )
{
m_set = new StringExpressionSet( m_ignoreCase, true );
m_allFiles = allFiles;
m_allLocalFiles = allLocalFiles;
m_pathDiscovery = pathDiscovery;
}
public FileIOAccess( StringExpressionSet set, bool allFiles, bool allLocalFiles, bool pathDiscovery )
{
m_set = set;
m_set.SetThrowOnRelative( true );
m_allFiles = allFiles;
m_allLocalFiles = allLocalFiles;
m_pathDiscovery = pathDiscovery;
}
private FileIOAccess( FileIOAccess operand )
{
m_set = operand.m_set.Copy();
m_allFiles = operand.m_allFiles;
m_allLocalFiles = operand.m_allLocalFiles;
m_pathDiscovery = operand.m_pathDiscovery;
}
[System.Security.SecurityCritical] // auto-generated
public void AddExpressions(ArrayList values, bool checkForDuplicates)
{
m_allFiles = false;
m_set.AddExpressions(values, checkForDuplicates);
}
public bool AllFiles
{
get
{
return m_allFiles;
}
set
{
m_allFiles = value;
}
}
public bool AllLocalFiles
{
get
{
return m_allLocalFiles;
}
set
{
m_allLocalFiles = value;
}
}
public bool PathDiscovery
{
set
{
m_pathDiscovery = value;
}
}
public bool IsEmpty()
{
return !m_allFiles && !m_allLocalFiles && (m_set == null || m_set.IsEmpty());
}
public FileIOAccess Copy()
{
return new FileIOAccess( this );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Union( FileIOAccess operand )
{
if (operand == null)
{
return this.IsEmpty() ? null : this.Copy();
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles || operand.m_allFiles)
{
return new FileIOAccess( true, false, this.m_pathDiscovery );
}
return new FileIOAccess( this.m_set.Union( operand.m_set ), false, this.m_allLocalFiles || operand.m_allLocalFiles, this.m_pathDiscovery );
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileIOAccess Intersect( FileIOAccess operand )
{
if (operand == null)
{
return null;
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (this.m_allFiles)
{
if (operand.m_allFiles)
{
return new FileIOAccess( true, false, this.m_pathDiscovery );
}
else
{
return new FileIOAccess( operand.m_set.Copy(), false, operand.m_allLocalFiles, this.m_pathDiscovery );
}
}
else if (operand.m_allFiles)
{
return new FileIOAccess( this.m_set.Copy(), false, this.m_allLocalFiles, this.m_pathDiscovery );
}
StringExpressionSet intersectionSet = new StringExpressionSet( m_ignoreCase, true );
if (this.m_allLocalFiles)
{
String[] expressions = operand.m_set.UnsafeToStringArray();
if (expressions != null)
{
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root != null && IsLocalDrive( GetRoot( root ) ) )
{
intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
}
}
}
}
if (operand.m_allLocalFiles)
{
String[] expressions = this.m_set.UnsafeToStringArray();
if (expressions != null)
{
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root != null && IsLocalDrive(GetRoot(root)))
{
intersectionSet.AddExpressions( new String[] { expressions[i] }, true, false );
}
}
}
}
String[] regularIntersection = this.m_set.Intersect( operand.m_set ).UnsafeToStringArray();
if (regularIntersection != null)
intersectionSet.AddExpressions( regularIntersection, !intersectionSet.IsEmpty(), false );
return new FileIOAccess( intersectionSet, false, this.m_allLocalFiles && operand.m_allLocalFiles, this.m_pathDiscovery );
}
[System.Security.SecuritySafeCritical] // auto-generated
public bool IsSubsetOf( FileIOAccess operand )
{
if (operand == null)
{
return this.IsEmpty();
}
if (operand.m_allFiles)
{
return true;
}
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if (!((m_pathDiscovery && this.m_set.IsSubsetOfPathDiscovery( operand.m_set )) || this.m_set.IsSubsetOf( operand.m_set )))
{
if (operand.m_allLocalFiles)
{
String[] expressions = m_set.UnsafeToStringArray();
for (int i = 0; i < expressions.Length; ++i)
{
String root = GetRoot( expressions[i] );
if (root == null || !IsLocalDrive(GetRoot(root)))
{
return false;
}
}
}
else
{
return false;
}
}
return true;
}
private static String GetRoot( String path )
{
#if !PLATFORM_UNIX
String str = path.Substring( 0, 3 );
if (str.EndsWith( ":\\", StringComparison.Ordinal))
#else
String str = path.Substring( 0, 1 );
if(str == "/")
#endif // !PLATFORM_UNIX
{
return str;
}
else
{
return null;
}
}
[SecuritySafeCritical]
public override String ToString()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
// we're only exposing out the same paths that we took as input.
if (m_allFiles)
{
return m_strAllFiles;
}
else
{
if (m_allLocalFiles)
{
String retstr = m_strAllLocalFiles;
String tempStr = m_set.UnsafeToString();
if (tempStr != null && tempStr.Length > 0)
retstr += ";" + tempStr;
return retstr;
}
else
{
return m_set.UnsafeToString();
}
}
}
[SecuritySafeCritical]
public String[] ToStringArray()
{
// SafeCritical: all string expression sets are constructed with the throwOnRelative bit set, so
// we're only exposing out the same paths that we took as input.
return m_set.UnsafeToStringArray();
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern bool IsLocalDrive(String path);
[System.Security.SecuritySafeCritical] // auto-generated
public override bool Equals(Object obj)
{
FileIOAccess operand = obj as FileIOAccess;
if(operand == null)
return (IsEmpty() && obj == null);
Contract.Assert( this.m_pathDiscovery == operand.m_pathDiscovery, "Path discovery settings must match" );
if(m_pathDiscovery)
{
if(this.m_allFiles && operand.m_allFiles)
return true;
if(this.m_allLocalFiles == operand.m_allLocalFiles &&
m_set.IsSubsetOf(operand.m_set) &&
operand.m_set.IsSubsetOf(m_set)) // Watch Out: This calls StringExpressionSet.IsSubsetOf, unlike below
return true;
return false;
}
else
{
if(!this.IsSubsetOf(operand)) // Watch Out: This calls FileIOAccess.IsSubsetOf, unlike above
return false;
if(!operand.IsSubsetOf(this))
return false;
return true;
}
}
public override int GetHashCode()
{
// This implementation is only to silence a compiler warning.
return base.GetHashCode();
}
}
}
| |
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Globalization;
using System.Xml;
using ServiceStack.Text.Json;
namespace ServiceStack.Text.Common
{
public static class DateTimeSerializer
{
public const string ShortDateTimeFormat = "yyyy-MM-dd"; //11
public const string DefaultDateTimeFormat = "dd/MM/yyyy HH:mm:ss"; //20
public const string DefaultDateTimeFormatWithFraction = "dd/MM/yyyy HH:mm:ss.fff"; //24
public const string XsdDateTimeFormat = "yyyy-MM-ddTHH:mm:ss.fffffffZ"; //29
public const string XsdDateTimeFormat3F = "yyyy-MM-ddTHH:mm:ss.fffZ"; //25
public const string XsdDateTimeFormatSeconds = "yyyy-MM-ddTHH:mm:ssZ"; //21
public const string EscapedWcfJsonPrefix = "\\/Date(";
public const string EscapedWcfJsonSuffix = ")\\/";
public const string WcfJsonPrefix = "/Date(";
public const char WcfJsonSuffix = ')';
/// <summary>
/// If AlwaysUseUtc is set to true then convert all DateTime to UTC.
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
private static DateTime Prepare(this DateTime dateTime)
{
if (JsConfig.AlwaysUseUtc && dateTime.Kind != DateTimeKind.Utc)
return dateTime.ToStableUniversalTime();
else
return dateTime;
}
public static DateTime? ParseShortestNullableXsdDateTime(string dateTimeStr)
{
if (dateTimeStr == null)
return null;
return ParseShortestXsdDateTime(dateTimeStr);
}
public static DateTime ParseShortestXsdDateTime(string dateTimeStr)
{
if (string.IsNullOrEmpty(dateTimeStr))
return DateTime.MinValue;
if (dateTimeStr.StartsWith(EscapedWcfJsonPrefix) || dateTimeStr.StartsWith(WcfJsonPrefix))
return ParseWcfJsonDate(dateTimeStr).Prepare();
if (dateTimeStr.Length == DefaultDateTimeFormat.Length
|| dateTimeStr.Length == DefaultDateTimeFormatWithFraction.Length)
{
return DateTime.Parse(dateTimeStr, CultureInfo.InvariantCulture).Prepare();
}
if (dateTimeStr.Length == XsdDateTimeFormatSeconds.Length)
return DateTime.ParseExact(dateTimeStr, XsdDateTimeFormatSeconds, null,
DateTimeStyles.AdjustToUniversal);
if (dateTimeStr.Length >= XsdDateTimeFormat3F.Length
&& dateTimeStr.Length <= XsdDateTimeFormat.Length)
{
var dateTimeType = JsConfig.DateHandler != JsonDateHandler.ISO8601
? XmlDateTimeSerializationMode.Local
: XmlDateTimeSerializationMode.RoundtripKind;
return XmlConvert.ToDateTime(dateTimeStr, dateTimeType).Prepare();
}
return DateTime.Parse(dateTimeStr, null, DateTimeStyles.AssumeLocal).Prepare();
}
public static string ToDateTimeString(DateTime dateTime)
{
return dateTime.ToStableUniversalTime().ToString(XsdDateTimeFormat);
}
public static DateTime ParseDateTime(string dateTimeStr)
{
return DateTime.ParseExact(dateTimeStr, XsdDateTimeFormat, null);
}
public static DateTimeOffset ParseDateTimeOffset(string dateTimeOffsetStr)
{
if (string.IsNullOrEmpty(dateTimeOffsetStr)) return default(DateTimeOffset);
// for interop, do not assume format based on config
// format: prefer TimestampOffset, DCJSCompatible
if (dateTimeOffsetStr.StartsWith(EscapedWcfJsonPrefix) ||
dateTimeOffsetStr.StartsWith(WcfJsonPrefix))
{
return ParseWcfJsonDateOffset(dateTimeOffsetStr);
}
// format: next preference ISO8601
// assume utc when no offset specified
if (dateTimeOffsetStr.LastIndexOfAny(TimeZoneChars) < 10)
{
if (!dateTimeOffsetStr.EndsWith("Z")) dateTimeOffsetStr += "Z";
#if __MonoCS__
// Without that Mono uses a Local timezone))
dateTimeOffsetStr = dateTimeOffsetStr.Substring(0, dateTimeOffsetStr.Length - 1) + "+00:00";
#endif
}
return DateTimeOffset.Parse(dateTimeOffsetStr, CultureInfo.InvariantCulture);
}
public static string ToXsdDateTimeString(DateTime dateTime)
{
return XmlConvert.ToString(dateTime.ToStableUniversalTime(), XmlDateTimeSerializationMode.Utc);
}
public static string ToXsdTimeSpanString(TimeSpan timeSpan)
{
var r = XmlConvert.ToString(timeSpan);
#if __MonoCS__
// Mono returns DT even if time is 00:00:00
if (r.EndsWith("DT")) return r.Substring(0, r.Length - 1);
#endif
return r;
}
public static string ToXsdTimeSpanString(TimeSpan? timeSpan)
{
return (timeSpan != null) ? ToXsdTimeSpanString(timeSpan.Value) : null;
}
public static DateTime ParseXsdDateTime(string dateTimeStr)
{
return XmlConvert.ToDateTime(dateTimeStr, XmlDateTimeSerializationMode.Utc);
}
public static TimeSpan ParseTimeSpan(string dateTimeStr)
{
return dateTimeStr.StartsWith("P") || dateTimeStr.StartsWith("-P")
? ParseXsdTimeSpan(dateTimeStr)
: TimeSpan.Parse(dateTimeStr);
}
public static TimeSpan ParseXsdTimeSpan(string dateTimeStr)
{
return XmlConvert.ToTimeSpan(dateTimeStr);
}
public static TimeSpan? ParseNullableTimeSpan(string dateTimeStr)
{
return string.IsNullOrEmpty(dateTimeStr)
? (TimeSpan?) null
: ParseTimeSpan(dateTimeStr);
}
public static TimeSpan? ParseXsdNullableTimeSpan(string dateTimeStr)
{
return String.IsNullOrEmpty(dateTimeStr) ?
null :
new TimeSpan?(XmlConvert.ToTimeSpan(dateTimeStr));
}
public static string ToShortestXsdDateTimeString(DateTime dateTime)
{
var timeOfDay = dateTime.TimeOfDay;
if (timeOfDay.Ticks == 0)
return dateTime.ToString(ShortDateTimeFormat);
if (timeOfDay.Milliseconds == 0)
return dateTime.ToStableUniversalTime().ToString(XsdDateTimeFormatSeconds);
return ToXsdDateTimeString(dateTime);
}
static readonly char[] TimeZoneChars = new[] { '+', '-' };
/// <summary>
/// WCF Json format: /Date(unixts+0000)/
/// </summary>
/// <param name="wcfJsonDate"></param>
/// <returns></returns>
public static DateTimeOffset ParseWcfJsonDateOffset(string wcfJsonDate)
{
if (wcfJsonDate[0] == '\\')
{
wcfJsonDate = wcfJsonDate.Substring(1);
}
var suffixPos = wcfJsonDate.IndexOf(WcfJsonSuffix);
var timeString = (suffixPos < 0) ? wcfJsonDate : wcfJsonDate.Substring(WcfJsonPrefix.Length, suffixPos - WcfJsonPrefix.Length);
// for interop, do not assume format based on config
if (!wcfJsonDate.StartsWith(WcfJsonPrefix))
{
return DateTimeOffset.Parse(timeString, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
}
var timeZonePos = timeString.LastIndexOfAny(TimeZoneChars);
var timeZone = timeZonePos <= 0 ? string.Empty : timeString.Substring(timeZonePos);
var unixTimeString = timeString.Substring(0, timeString.Length - timeZone.Length);
var unixTime = long.Parse(unixTimeString);
if (timeZone == string.Empty)
{
// when no timezone offset is supplied, then treat the time as UTC
return unixTime.FromUnixTimeMs();
}
if (JsConfig.DateHandler == JsonDateHandler.DCJSCompatible)
{
// DCJS ignores the offset and considers it local time if any offset exists
// REVIEW: DCJS shoves offset in a separate field 'offsetMinutes', we have the offset in the format, so shouldn't we use it?
return unixTime.FromUnixTimeMs().ToLocalTime();
}
var offset = timeZone.FromTimeOffsetString();
var date = unixTime.FromUnixTimeMs();
return new DateTimeOffset(date.Ticks, offset);
}
/// <summary>
/// WCF Json format: /Date(unixts+0000)/
/// </summary>
/// <param name="wcfJsonDate"></param>
/// <returns></returns>
public static DateTime ParseWcfJsonDate(string wcfJsonDate)
{
if (wcfJsonDate[0] == JsonUtils.EscapeChar)
{
wcfJsonDate = wcfJsonDate.Substring(1);
}
var suffixPos = wcfJsonDate.IndexOf(WcfJsonSuffix);
var timeString = wcfJsonDate.Substring(WcfJsonPrefix.Length, suffixPos - WcfJsonPrefix.Length);
// for interop, do not assume format based on config
if (!wcfJsonDate.StartsWith(WcfJsonPrefix))
{
return DateTime.Parse(timeString, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
}
var timeZonePos = timeString.LastIndexOfAny(TimeZoneChars);
var timeZone = timeZonePos <= 0 ? string.Empty : timeString.Substring(timeZonePos);
var unixTimeString = timeString.Substring(0, timeString.Length - timeZone.Length);
var unixTime = long.Parse(unixTimeString);
if (timeZone == string.Empty)
{
// when no timezone offset is supplied, then treat the time as UTC
return unixTime.FromUnixTimeMs();
}
if (JsConfig.DateHandler == JsonDateHandler.DCJSCompatible)
{
// DCJS ignores the offset and considers it local time if any offset exists
return unixTime.FromUnixTimeMs().ToLocalTime();
}
var offset = timeZone.FromTimeOffsetString();
var date = unixTime.FromUnixTimeMs(offset);
return new DateTimeOffset(date, offset).DateTime;
}
public static string ToWcfJsonDate(DateTime dateTime)
{
if (JsConfig.DateHandler == JsonDateHandler.ISO8601)
{
return dateTime.ToString("o", CultureInfo.InvariantCulture);
}
var timestamp = dateTime.ToUnixTimeMs();
var offset = dateTime.Kind == DateTimeKind.Utc
? string.Empty
: TimeZoneInfo.Local.GetUtcOffset(dateTime).ToTimeOffsetString();
return EscapedWcfJsonPrefix + timestamp + offset + EscapedWcfJsonSuffix;
}
public static string ToWcfJsonDateTimeOffset(DateTimeOffset dateTimeOffset)
{
if (JsConfig.DateHandler == JsonDateHandler.ISO8601)
{
return dateTimeOffset.ToString("o", CultureInfo.InvariantCulture);
}
var timestamp = dateTimeOffset.Ticks.ToUnixTimeMs();
var offset = dateTimeOffset.Offset == TimeSpan.Zero
? string.Empty
: dateTimeOffset.Offset.ToTimeOffsetString();
return EscapedWcfJsonPrefix + timestamp + offset + EscapedWcfJsonSuffix;
}
}
}
| |
using System;
using System.Collections.Generic;
using ModestTree;
namespace Zenject
{
public abstract class SignalHandlerBinder
{
readonly BindFinalizerWrapper _finalizerWrapper;
readonly Type _signalType;
readonly DiContainer _container;
public SignalHandlerBinder(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
{
_container = container;
_signalType = signalType;
_finalizerWrapper = finalizerWrapper;
}
protected object Identifier
{
get;
set;
}
public SignalFromBinder<THandler> To<THandler>(Action<THandler> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodWithInstanceSignalHandler<THandler>>().AsCached()
.WithArguments(method, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public SignalFromBinder<THandler> To<THandler>(Func<THandler, Action> methodGetter)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<InstanceMethodSignalHandler<THandler>>().AsCached()
.WithArguments(methodGetter, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public void To(Action method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodSignalHandler>().AsCached()
.WithArguments(method, new BindingId(_signalType, Identifier));
}
}
public class SignalHandlerBinderWithId : SignalHandlerBinder
{
public SignalHandlerBinderWithId(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
: base(container, signalType, finalizerWrapper)
{
}
public SignalHandlerBinder WithId(object identifier)
{
Identifier = identifier;
return this;
}
}
public abstract class SignalHandlerBinder<TParam1>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
#endif
{
readonly BindFinalizerWrapper _finalizerWrapper;
readonly Type _signalType;
readonly DiContainer _container;
public SignalHandlerBinder(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
{
_container = container;
_signalType = signalType;
_finalizerWrapper = finalizerWrapper;
}
protected object Identifier
{
get;
set;
}
public SignalFromBinder<THandler> To<THandler>(Action<THandler, TParam1> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodWithInstanceSignalHandler<TParam1, THandler>>().AsCached()
.WithArguments(method, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public SignalFromBinder<THandler> To<THandler>(Func<THandler, Action<TParam1>> methodGetter)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<InstanceMethodSignalHandler<TParam1, THandler>>().AsCached()
.WithArguments(methodGetter, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public void To(Action<TParam1> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodSignalHandler<TParam1>>().AsCached()
.WithArguments(method, new BindingId(_signalType, Identifier));
}
}
public class SignalHandlerBinderWithId<TParam1> : SignalHandlerBinder<TParam1>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
#endif
{
public SignalHandlerBinderWithId(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
: base(container, signalType, finalizerWrapper)
{
}
public SignalHandlerBinder<TParam1> WithId(object identifier)
{
Identifier = identifier;
return this;
}
}
public abstract class SignalHandlerBinder<TParam1, TParam2>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
#endif
{
readonly BindFinalizerWrapper _finalizerWrapper;
readonly Type _signalType;
readonly DiContainer _container;
public SignalHandlerBinder(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
{
_container = container;
_signalType = signalType;
_finalizerWrapper = finalizerWrapper;
}
protected object Identifier
{
get;
set;
}
public SignalFromBinder<THandler> To<THandler>(Action<THandler, TParam1, TParam2> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodWithInstanceSignalHandler<TParam1, TParam2, THandler>>().AsCached()
.WithArguments(method, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public SignalFromBinder<THandler> To<THandler>(Func<THandler, Action<TParam1, TParam2>> methodGetter)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<InstanceMethodSignalHandler<TParam1, TParam2, THandler>>().AsCached()
.WithArguments(methodGetter, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public void To(Action<TParam1, TParam2> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodSignalHandler<TParam1, TParam2>>().AsCached()
.WithArguments(method, new BindingId(_signalType, Identifier));
}
}
public class SignalHandlerBinderWithId<TParam1, TParam2> : SignalHandlerBinder<TParam1, TParam2>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
#endif
{
public SignalHandlerBinderWithId(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
: base(container, signalType, finalizerWrapper)
{
}
public SignalHandlerBinderWithId<TParam1, TParam2> WithId(object identifier)
{
Identifier = identifier;
return this;
}
}
public abstract class SignalHandlerBinder<TParam1, TParam2, TParam3>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
#endif
{
readonly BindFinalizerWrapper _finalizerWrapper;
readonly Type _signalType;
readonly DiContainer _container;
public SignalHandlerBinder(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
{
_container = container;
_signalType = signalType;
_finalizerWrapper = finalizerWrapper;
}
protected object Identifier
{
get;
set;
}
public SignalFromBinder<THandler> To<THandler>(Action<THandler, TParam1, TParam2, TParam3> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodWithInstanceSignalHandler<TParam1, TParam2, TParam3, THandler>>().AsCached()
.WithArguments(method, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public SignalFromBinder<THandler> To<THandler>(Func<THandler, Action<TParam1, TParam2, TParam3>> methodGetter)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<InstanceMethodSignalHandler<TParam1, TParam2, TParam3, THandler>>().AsCached()
.WithArguments(methodGetter, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public void To(Action<TParam1, TParam2, TParam3> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodSignalHandler<TParam1, TParam2, TParam3>>().AsCached()
.WithArguments(method, new BindingId(_signalType, Identifier));
}
}
public class SignalHandlerBinderWithId<TParam1, TParam2, TParam3> : SignalHandlerBinder<TParam1, TParam2, TParam3>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
#endif
{
public SignalHandlerBinderWithId(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
: base(container, signalType, finalizerWrapper)
{
}
public SignalHandlerBinderWithId<TParam1, TParam2, TParam3> WithId(object identifier)
{
Identifier = identifier;
return this;
}
}
public abstract class SignalHandlerBinder<TParam1, TParam2, TParam3, TParam4>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
where TParam4 : class
#endif
{
readonly BindFinalizerWrapper _finalizerWrapper;
readonly Type _signalType;
readonly DiContainer _container;
public SignalHandlerBinder(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
{
_container = container;
_signalType = signalType;
_finalizerWrapper = finalizerWrapper;
}
protected object Identifier
{
get;
set;
}
public SignalFromBinder<THandler> To<THandler>(ModestTree.Util.Action<THandler, TParam1, TParam2, TParam3, TParam4> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodWithInstanceSignalHandler<TParam1, TParam2, TParam3, TParam4, THandler>>().AsCached()
.WithArguments(method, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public SignalFromBinder<THandler> To<THandler>(Func<THandler, Action<TParam1, TParam2, TParam3, TParam4>> methodGetter)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
var lookupId = Guid.NewGuid();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<InstanceMethodSignalHandler<TParam1, TParam2, TParam3, TParam4, THandler>>().AsCached()
.WithArguments(methodGetter, new InjectContext(_container, typeof(THandler), lookupId), new BindingId(_signalType, Identifier));
var info = new BindInfo(typeof(THandler));
return new SignalFromBinder<THandler>(
info, _container.Bind<THandler>(info).WithId(lookupId).To<THandler>());
}
public void To(Action<TParam1, TParam2, TParam3, TParam4> method)
{
// This is just to ensure they don't stop at BindSignal
_finalizerWrapper.SubFinalizer = new NullBindingFinalizer();
_container.Bind(typeof(IInitializable), typeof(IDisposable)).To<StaticMethodSignalHandler<TParam1, TParam2, TParam3, TParam4>>().AsCached()
.WithArguments(method, new BindingId(_signalType, Identifier));
}
}
public class SignalHandlerBinderWithId<TParam1, TParam2, TParam3, TParam4> : SignalHandlerBinder<TParam1, TParam2, TParam3, TParam4>
#if ENABLE_IL2CPP
// See discussion here for why we do this: https://github.com/modesttree/Zenject/issues/219#issuecomment-284751679
where TParam1 : class
where TParam2 : class
where TParam3 : class
where TParam4 : class
#endif
{
public SignalHandlerBinderWithId(
DiContainer container, Type signalType, BindFinalizerWrapper finalizerWrapper)
: base(container, signalType, finalizerWrapper)
{
}
public SignalHandlerBinderWithId<TParam1, TParam2, TParam3, TParam4> WithId(object identifier)
{
Identifier = identifier;
return this;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
** Purpose: This is the value class representing a Unicode character
** Char methods until we create this functionality.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics.Contracts;
namespace System
{
[System.Runtime.InteropServices.ComVisible(true)]
[StructLayout(LayoutKind.Sequential)]
public struct Char : IComparable, IComparable<Char>, IEquatable<Char>, IConvertible
{
//
// Member Variables
//
internal char m_value;
//
// Public Constants
//
// The maximum character value.
public const char MaxValue = (char)0xFFFF;
// The minimum character value.
public const char MinValue = (char)0x00;
internal const char HIGH_SURROGATE_START_CHAR = '\ud800';
internal const char HIGH_SURROGATE_END_CHAR = '\udbff';
internal const char LOW_SURROGATE_START_CHAR = '\udc00';
internal const char LOW_SURROGATE_END_CHAR = '\udfff';
// Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space.
private readonly static byte[] s_categoryForLatin1 = {
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027
(byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
(byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F
(byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097
(byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F
(byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
(byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
(byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7
(byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7
(byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
};
// Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
private static bool IsLatin1(char ch)
{
return (ch <= '\x00ff');
}
// Return true for all characters below or equal U+007f, which is ASCII.
private static bool IsAscii(char ch)
{
return (ch <= '\x007f');
}
// Return the Unicode category for Unicode character <= 0x00ff.
private static UnicodeCategory GetLatin1UnicodeCategory(char ch)
{
Contract.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
return (UnicodeCategory)(s_categoryForLatin1[(int)ch]);
}
//
// Private Constants
//
//
// Overriden Instance Methods
//
// Calculate a hashcode for a 2 byte Unicode character.
public override int GetHashCode()
{
return (int)m_value | ((int)m_value << 16);
}
// Used for comparing two boxed Char objects.
//
public override bool Equals(Object obj)
{
if (!(obj is Char))
{
return false;
}
return (m_value == ((Char)obj).m_value);
}
public bool Equals(Char obj)
{
return m_value == obj;
}
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type Char, this method throws an ArgumentException.
//
[Pure]
int IComparable.CompareTo(Object value)
{
if (value == null)
{
return 1;
}
if (!(value is Char))
{
throw new ArgumentException(SR.Arg_MustBeChar);
}
return (m_value - ((Char)value).m_value);
}
[Pure]
public int CompareTo(Char value)
{
return (m_value - value);
}
// Overrides System.Object.ToString.
[Pure]
public override String ToString()
{
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
[Pure]
String IConvertible.ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<String>() != null);
return Char.ToString(m_value);
}
//
// Formatting Methods
//
/*===================================ToString===================================
**This static methods takes a character and returns the String representation of it.
==============================================================================*/
// Provides a string representation of a character.
[Pure]
public static String ToString(char c)
{
Contract.Ensures(Contract.Result<String>() != null);
return new String(c, 1);
}
public static char Parse(String s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
Contract.EndContractBlock();
if (s.Length != 1)
{
throw new FormatException(SR.Format_NeedSingleChar);
}
return s[0];
}
public static bool TryParse(String s, out Char result)
{
result = '\0';
if (s == null)
{
return false;
}
if (s.Length != 1)
{
return false;
}
result = s[0];
return true;
}
//
// Static Methods
//
/*=================================ISDIGIT======================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a digit. **
==============================================================================*/
// Determines whether a character is a digit.
[Pure]
public static bool IsDigit(char c)
{
if (IsLatin1(c))
{
return (c >= '0' && c <= '9');
}
return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber);
}
/*=================================CheckLetter=====================================
** Check if the specified UnicodeCategory belongs to the letter categories.
==============================================================================*/
internal static bool CheckLetter(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.UppercaseLetter):
case (UnicodeCategory.LowercaseLetter):
case (UnicodeCategory.TitlecaseLetter):
case (UnicodeCategory.ModifierLetter):
case (UnicodeCategory.OtherLetter):
return (true);
}
return (false);
}
/*=================================ISLETTER=====================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a letter. **
==============================================================================*/
// Determines whether a character is a letter.
[Pure]
public static bool IsLetter(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
c |= (char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(FormatProvider.GetUnicodeCategory(c)));
}
private static bool IsWhiteSpaceLatin1(char c)
{
// There are characters which belong to UnicodeCategory.Control but are considered as white spaces.
// We use code point comparisons for these characters here as a temporary fix.
// U+0009 = <control> HORIZONTAL TAB
// U+000a = <control> LINE FEED
// U+000b = <control> VERTICAL TAB
// U+000c = <contorl> FORM FEED
// U+000d = <control> CARRIAGE RETURN
// U+0085 = <control> NEXT LINE
// U+00a0 = NO-BREAK SPACE
if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085')
{
return (true);
}
return (false);
}
internal static bool IsUnicodeWhiteSpace(char c)
{
UnicodeCategory uc = FormatProvider.GetUnicodeCategory(c);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
/*===============================ISWHITESPACE===================================
**A wrapper for Char. Returns a boolean indicating whether **
**character c is considered to be a whitespace character. **
==============================================================================*/
// Determines whether a character is whitespace.
[Pure]
public static bool IsWhiteSpace(char c)
{
if (IsLatin1(c))
{
return (IsWhiteSpaceLatin1(c));
}
return IsUnicodeWhiteSpace(c);
}
/*===================================IsUpper====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an uppercase character.
==============================================================================*/
// Determines whether a character is upper-case.
[Pure]
public static bool IsUpper(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
/*===================================IsLower====================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an lowercase character.
==============================================================================*/
// Determines whether a character is lower-case.
[Pure]
public static bool IsLower(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
internal static bool CheckPunctuation(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
case UnicodeCategory.OpenPunctuation:
case UnicodeCategory.ClosePunctuation:
case UnicodeCategory.InitialQuotePunctuation:
case UnicodeCategory.FinalQuotePunctuation:
case UnicodeCategory.OtherPunctuation:
return (true);
}
return (false);
}
/*================================IsPunctuation=================================
**Arguments: c -- the characater to be checked.
**Returns: True if c is an punctuation mark
==============================================================================*/
// Determines whether a character is a punctuation mark.
[Pure]
public static bool IsPunctuation(char c)
{
if (IsLatin1(c))
{
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(FormatProvider.GetUnicodeCategory(c)));
}
/*=================================CheckLetterOrDigit=====================================
** Check if the specified UnicodeCategory belongs to the letter or digit categories.
==============================================================================*/
internal static bool CheckLetterOrDigit(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.TitlecaseLetter:
case UnicodeCategory.ModifierLetter:
case UnicodeCategory.OtherLetter:
case UnicodeCategory.DecimalDigitNumber:
return (true);
}
return (false);
}
// Determines whether a character is a letter or a digit.
[Pure]
public static bool IsLetterOrDigit(char c)
{
if (IsLatin1(c))
{
return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c)));
}
return (CheckLetterOrDigit(FormatProvider.GetUnicodeCategory(c)));
}
/*=================================TOUPPER======================================
**A wrapper for Char.toUpperCase. Converts character c to its **
**uppercase equivalent. If c is already an uppercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to upper-case for the default culture.
//
public static char ToUpper(char c)
{
return FormatProvider.ToUpper(c);
}
// Converts a character to upper-case for invariant culture.
public static char ToUpperInvariant(char c)
{
return FormatProvider.ToUpperInvariant(c);
}
/*=================================TOLOWER======================================
**A wrapper for Char.toLowerCase. Converts character c to its **
**lowercase equivalent. If c is already a lowercase character or is not an **
**alphabetic, nothing happens. **
==============================================================================*/
// Converts a character to lower-case for the default culture.
public static char ToLower(char c)
{
return FormatProvider.ToLower(c);
}
// Converts a character to lower-case for invariant culture.
public static char ToLowerInvariant(char c)
{
return FormatProvider.ToLowerInvariant(c);
}
//
// IConvertible implementation
//
[Pure]
TypeCode IConvertible.GetTypeCode()
{
return TypeCode.Char;
}
/// <internalonly/>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Boolean"));
}
/// <internalonly/>
char IConvertible.ToChar(IFormatProvider provider)
{
return m_value;
}
/// <internalonly/>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
/// <internalonly/>
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
/// <internalonly/>
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
/// <internalonly/>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
/// <internalonly/>
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
/// <internalonly/>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return Convert.ToUInt32(m_value);
}
/// <internalonly/>
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
/// <internalonly/>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
/// <internalonly/>
float IConvertible.ToSingle(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Single"));
}
/// <internalonly/>
double IConvertible.ToDouble(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Double"));
}
/// <internalonly/>
Decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "Decimal"));
}
/// <internalonly/>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "Char", "DateTime"));
}
/// <internalonly/>
Object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
public static bool IsControl(char c)
{
if (IsLatin1(c))
{
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (FormatProvider.GetUnicodeCategory(c) == UnicodeCategory.Control);
}
public static bool IsControl(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
}
return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
}
public static bool IsDigit(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (c >= '0' && c <= '9');
}
return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
}
public static bool IsLetter(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
c |= (char)0x20;
return ((c >= 'a' && c <= 'z'));
}
return (CheckLetter(GetLatin1UnicodeCategory(c)));
}
return (CheckLetter(FormatProvider.GetUnicodeCategory(s, index)));
}
public static bool IsLetterOrDigit(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
}
return CheckLetterOrDigit(FormatProvider.GetUnicodeCategory(s, index));
}
public static bool IsLower(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'a' && c <= 'z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
}
return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
}
/*=================================CheckNumber=====================================
** Check if the specified UnicodeCategory belongs to the number categories.
==============================================================================*/
internal static bool CheckNumber(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.DecimalDigitNumber):
case (UnicodeCategory.LetterNumber):
case (UnicodeCategory.OtherNumber):
return (true);
}
return (false);
}
public static bool IsNumber(char c)
{
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(FormatProvider.GetUnicodeCategory(c)));
}
public static bool IsNumber(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= '0' && c <= '9');
}
return (CheckNumber(GetLatin1UnicodeCategory(c)));
}
return (CheckNumber(FormatProvider.GetUnicodeCategory(s, index)));
}
////////////////////////////////////////////////////////////////////////
//
// IsPunctuation
//
// Determines if the given character is a punctuation character.
//
////////////////////////////////////////////////////////////////////////
public static bool IsPunctuation(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
}
return (CheckPunctuation(FormatProvider.GetUnicodeCategory(s, index)));
}
/*================================= CheckSeparator ============================
** Check if the specified UnicodeCategory belongs to the seprator categories.
==============================================================================*/
internal static bool CheckSeparator(UnicodeCategory uc)
{
switch (uc)
{
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.LineSeparator:
case UnicodeCategory.ParagraphSeparator:
return (true);
}
return (false);
}
private static bool IsSeparatorLatin1(char c)
{
// U+00a0 = NO-BREAK SPACE
// There is no LineSeparator or ParagraphSeparator in Latin 1 range.
return (c == '\x0020' || c == '\x00a0');
}
public static bool IsSeparator(char c)
{
if (IsLatin1(c))
{
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(FormatProvider.GetUnicodeCategory(c)));
}
public static bool IsSeparator(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (IsSeparatorLatin1(c));
}
return (CheckSeparator(FormatProvider.GetUnicodeCategory(s, index)));
}
[Pure]
public static bool IsSurrogate(char c)
{
return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END);
}
[Pure]
public static bool IsSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsSurrogate(s[index]));
}
/*================================= CheckSymbol ============================
** Check if the specified UnicodeCategory belongs to the symbol categories.
==============================================================================*/
internal static bool CheckSymbol(UnicodeCategory uc)
{
switch (uc)
{
case (UnicodeCategory.MathSymbol):
case (UnicodeCategory.CurrencySymbol):
case (UnicodeCategory.ModifierSymbol):
case (UnicodeCategory.OtherSymbol):
return (true);
}
return (false);
}
public static bool IsSymbol(char c)
{
if (IsLatin1(c))
{
return (CheckSymbol(GetLatin1UnicodeCategory(c)));
}
return (CheckSymbol(FormatProvider.GetUnicodeCategory(c)));
}
public static bool IsSymbol(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
return (CheckSymbol(GetLatin1UnicodeCategory(c)));
}
return (CheckSymbol(FormatProvider.GetUnicodeCategory(s, index)));
}
public static bool IsUpper(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
char c = s[index];
if (IsLatin1(c))
{
if (IsAscii(c))
{
return (c >= 'A' && c <= 'Z');
}
return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
}
return (FormatProvider.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
}
internal static bool IsUnicodeWhiteSpace(String s, int index)
{
Contract.Assert(s != null, "s!=null");
Contract.Assert(index >= 0 && index < s.Length, "index >= 0 && index < s.Length");
UnicodeCategory uc = FormatProvider.GetUnicodeCategory(s, index);
// In Unicode 3.0, U+2028 is the only character which is under the category "LineSeparator".
// And U+2029 is th eonly character which is under the category "ParagraphSeparator".
switch (uc)
{
case (UnicodeCategory.SpaceSeparator):
case (UnicodeCategory.LineSeparator):
case (UnicodeCategory.ParagraphSeparator):
return (true);
}
return (false);
}
public static bool IsWhiteSpace(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (IsLatin1(s[index]))
{
return IsWhiteSpaceLatin1(s[index]);
}
return IsUnicodeWhiteSpace(s, index);
}
//public static UnicodeCategory GetUnicodeCategory(char c)
//{
// if (IsLatin1(c)) {
// return (GetLatin1UnicodeCategory(c));
// }
// return FormatProvider.InternalGetUnicodeCategory(c);
//}
//public static UnicodeCategory GetUnicodeCategory(String s, int index)
//{
// if (s==null)
// throw new ArgumentNullException("s");
// if (((uint)index)>=((uint)s.Length)) {
// throw new ArgumentOutOfRangeException("index");
// }
// Contract.EndContractBlock();
// if (IsLatin1(s[index])) {
// return (GetLatin1UnicodeCategory(s[index]));
// }
// return FormatProvider.InternalGetUnicodeCategory(s, index);
//}
public static double GetNumericValue(char c)
{
return FormatProvider.GetNumericValue(c);
}
public static double GetNumericValue(String s, int index)
{
if (s == null)
throw new ArgumentNullException("s");
if (((uint)index) >= ((uint)s.Length))
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return FormatProvider.GetNumericValue(s, index);
}
/*================================= IsHighSurrogate ============================
** Check if a char is a high surrogate.
==============================================================================*/
[Pure]
public static bool IsHighSurrogate(char c)
{
return ((c >= HIGH_SURROGATE_START_CHAR) && (c <= HIGH_SURROGATE_END_CHAR));
}
[Pure]
public static bool IsHighSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsHighSurrogate(s[index]));
}
/*================================= IsLowSurrogate ============================
** Check if a char is a low surrogate.
==============================================================================*/
[Pure]
public static bool IsLowSurrogate(char c)
{
return ((c >= LOW_SURROGATE_START_CHAR) && (c <= LOW_SURROGATE_END_CHAR));
}
[Pure]
public static bool IsLowSurrogate(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
return (IsLowSurrogate(s[index]));
}
/*================================= IsSurrogatePair ============================
** Check if the string specified by the index starts with a surrogate pair.
==============================================================================*/
[Pure]
public static bool IsSurrogatePair(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index");
}
Contract.EndContractBlock();
if (index + 1 < s.Length)
{
return (IsSurrogatePair(s[index], s[index + 1]));
}
return (false);
}
[Pure]
public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate)
{
return ((highSurrogate >= Char.HIGH_SURROGATE_START_CHAR && highSurrogate <= Char.HIGH_SURROGATE_END_CHAR) &&
(lowSurrogate >= Char.LOW_SURROGATE_START_CHAR && lowSurrogate <= Char.LOW_SURROGATE_END_CHAR));
}
internal const int UNICODE_PLANE00_END = 0x00ffff;
// The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
internal const int UNICODE_PLANE01_START = 0x10000;
// The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode.
// Plane 16 contains 0x100000 ~ 0x10ffff.
internal const int UNICODE_PLANE16_END = 0x10ffff;
internal const int HIGH_SURROGATE_START = 0x00d800;
internal const int LOW_SURROGATE_END = 0x00dfff;
/*================================= ConvertFromUtf32 ============================
** Convert an UTF32 value into a surrogate pair.
==============================================================================*/
public static String ConvertFromUtf32(int utf32)
{
// For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
// are considered as irregular code unit sequence, but they are not illegal.
if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END))
{
throw new ArgumentOutOfRangeException("utf32", SR.ArgumentOutOfRange_InvalidUTF32);
}
Contract.EndContractBlock();
if (utf32 < UNICODE_PLANE01_START)
{
// This is a BMP character.
return (Char.ToString((char)utf32));
}
// This is a sumplementary character. Convert it to a surrogate pair in UTF-16.
utf32 -= UNICODE_PLANE01_START;
char[] surrogate = new char[2];
surrogate[0] = (char)((utf32 / 0x400) + (int)Char.HIGH_SURROGATE_START_CHAR);
surrogate[1] = (char)((utf32 % 0x400) + (int)Char.LOW_SURROGATE_START_CHAR);
return (new String(surrogate));
}
/*=============================ConvertToUtf32===================================
** Convert a surrogate pair to UTF32 value
==============================================================================*/
public static int ConvertToUtf32(char highSurrogate, char lowSurrogate)
{
if (!IsHighSurrogate(highSurrogate))
{
throw new ArgumentOutOfRangeException("highSurrogate", SR.ArgumentOutOfRange_InvalidHighSurrogate);
}
if (!IsLowSurrogate(lowSurrogate))
{
throw new ArgumentOutOfRangeException("lowSurrogate", SR.ArgumentOutOfRange_InvalidLowSurrogate);
}
Contract.EndContractBlock();
return (((highSurrogate - Char.HIGH_SURROGATE_START_CHAR) * 0x400) + (lowSurrogate - Char.LOW_SURROGATE_START_CHAR) + UNICODE_PLANE01_START);
}
/*=============================ConvertToUtf32===================================
** Convert a character or a surrogate pair starting at index of the specified string
** to UTF32 value.
** The char pointed by index should be a surrogate pair or a BMP character.
** This method throws if a high-surrogate is not followed by a low surrogate.
** This method throws if a low surrogate is seen without preceding a high-surrogate.
==============================================================================*/
public static int ConvertToUtf32(String s, int index)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
if (index < 0 || index >= s.Length)
{
throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index);
}
Contract.EndContractBlock();
// Check if the character at index is a high surrogate.
int temp1 = (int)s[index] - Char.HIGH_SURROGATE_START_CHAR;
if (temp1 >= 0 && temp1 <= 0x7ff)
{
// Found a surrogate char.
if (temp1 <= 0x3ff)
{
// Found a high surrogate.
if (index < s.Length - 1)
{
int temp2 = (int)s[index + 1] - Char.LOW_SURROGATE_START_CHAR;
if (temp2 >= 0 && temp2 <= 0x3ff)
{
// Found a low surrogate.
return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
}
else
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s");
}
}
else
{
// Found a high surrogate at the end of the string.
throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s");
}
}
else
{
// Find a low surrogate at the character pointed by index.
throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), "s");
}
}
// Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
return ((int)s[index]);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoadSoftDelete.Business.ERCLevel
{
/// <summary>
/// H09_CityColl (editable child list).<br/>
/// This is a generated base class of <see cref="H09_CityColl"/> business object.
/// </summary>
/// <remarks>
/// This class is child of <see cref="H08_Region"/> editable child object.<br/>
/// The items of the collection are <see cref="H10_City"/> objects.
/// </remarks>
[Serializable]
public partial class H09_CityColl : BusinessListBase<H09_CityColl, H10_City>
{
#region Collection Business Methods
/// <summary>
/// Removes a <see cref="H10_City"/> item from the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to be removed.</param>
public void Remove(int city_ID)
{
foreach (var h10_City in this)
{
if (h10_City.City_ID == city_ID)
{
Remove(h10_City);
break;
}
}
}
/// <summary>
/// Determines whether a <see cref="H10_City"/> item is in the collection.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the H10_City is a collection item; otherwise, <c>false</c>.</returns>
public bool Contains(int city_ID)
{
foreach (var h10_City in this)
{
if (h10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether a <see cref="H10_City"/> item is in the collection's DeletedList.
/// </summary>
/// <param name="city_ID">The City_ID of the item to search for.</param>
/// <returns><c>true</c> if the H10_City is a deleted collection item; otherwise, <c>false</c>.</returns>
public bool ContainsDeleted(int city_ID)
{
foreach (var h10_City in DeletedList)
{
if (h10_City.City_ID == city_ID)
{
return true;
}
}
return false;
}
#endregion
#region Find Methods
/// <summary>
/// Finds a <see cref="H10_City"/> item of the <see cref="H09_CityColl"/> collection, based on a given City_ID.
/// </summary>
/// <param name="city_ID">The City_ID.</param>
/// <returns>A <see cref="H10_City"/> object.</returns>
public H10_City FindH10_CityByCity_ID(int city_ID)
{
for (var i = 0; i < this.Count; i++)
{
if (this[i].City_ID.Equals(city_ID))
{
return this[i];
}
}
return null;
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="H09_CityColl"/> collection.
/// </summary>
/// <returns>A reference to the created <see cref="H09_CityColl"/> collection.</returns>
internal static H09_CityColl NewH09_CityColl()
{
return DataPortal.CreateChild<H09_CityColl>();
}
/// <summary>
/// Factory method. Loads a <see cref="H09_CityColl"/> collection, based on given parameters.
/// </summary>
/// <param name="parent_Region_ID">The Parent_Region_ID parameter of the H09_CityColl to fetch.</param>
/// <returns>A reference to the fetched <see cref="H09_CityColl"/> collection.</returns>
internal static H09_CityColl GetH09_CityColl(int parent_Region_ID)
{
return DataPortal.FetchChild<H09_CityColl>(parent_Region_ID);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="H09_CityColl"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public H09_CityColl()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
AllowNew = true;
AllowEdit = true;
AllowRemove = true;
RaiseListChangedEvents = rlce;
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="H09_CityColl"/> collection from the database, based on given criteria.
/// </summary>
/// <param name="parent_Region_ID">The Parent Region ID.</param>
protected void Child_Fetch(int parent_Region_ID)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("GetH09_CityColl", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Parent_Region_ID", parent_Region_ID).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd, parent_Region_ID);
OnFetchPre(args);
LoadCollection(cmd);
OnFetchPost(args);
}
}
foreach (var item in this)
{
item.FetchChildren();
}
}
private void LoadCollection(SqlCommand cmd)
{
using (var dr = new SafeDataReader(cmd.ExecuteReader()))
{
Fetch(dr);
}
}
/// <summary>
/// Loads all <see cref="H09_CityColl"/> collection items from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
var rlce = RaiseListChangedEvents;
RaiseListChangedEvents = false;
while (dr.Read())
{
Add(H10_City.GetH10_City(dr));
}
RaiseListChangedEvents = rlce;
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// ReflectionHelper.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
// (C) 2006 Evaluant RC S.A.
// (C) 2007 Jb Evain
//
// 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.
//
namespace Mono.Cecil {
using System;
using System.Collections;
using SR = System.Reflection;
using System.Text;
internal sealed class ReflectionHelper {
ModuleDefinition m_module;
IDictionary m_asmCache;
IDictionary m_memberRefCache;
bool m_cacheLoaded;
public ReflectionHelper (ModuleDefinition module)
{
m_module = module;
m_asmCache = new Hashtable ();
m_memberRefCache = new Hashtable ();
m_cacheLoaded = false;
}
void ImportCache ()
{
if (m_cacheLoaded)
return;
m_module.FullLoad ();
foreach (AssemblyNameReference ar in m_module.AssemblyReferences)
m_asmCache [ar.FullName] = ar;
foreach (MemberReference member in m_module.MemberReferences)
m_memberRefCache [member.ToString ()] = member;
m_cacheLoaded = true;
}
public AssemblyNameReference ImportAssembly (SR.Assembly asm)
{
ImportCache ();
AssemblyNameReference asmRef = (AssemblyNameReference) m_asmCache [asm.FullName];
if (asmRef != null)
return asmRef;
SR.AssemblyName asmName = asm.GetName ();
asmRef = new AssemblyNameReference (
asmName.Name, asmName.CultureInfo.Name, asmName.Version);
asmRef.PublicKeyToken = asmName.GetPublicKeyToken ();
asmRef.HashAlgorithm = (Mono.Cecil.AssemblyHashAlgorithm) asmName.HashAlgorithm;
asmRef.Culture = asmName.CultureInfo.ToString ();
m_module.AssemblyReferences.Add (asmRef);
m_asmCache [asm.FullName] = asmRef;
return asmRef;
}
public static string GetTypeSignature (Type t)
{
if (t.HasElementType) {
if (t.IsPointer)
return string.Concat (GetTypeSignature (t.GetElementType ()), "*");
else if (t.IsArray) // deal with complex arrays
return string.Concat (GetTypeSignature (t.GetElementType ()), "[]");
else if (t.IsByRef)
return string.Concat (GetTypeSignature (t.GetElementType ()), "&");
}
if (IsGenericTypeSpec (t)) {
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (GetGenericTypeDefinition (t)));
sb.Append ("<");
Type [] genArgs = GetGenericArguments (t);
for (int i = 0; i < genArgs.Length; i++) {
if (i > 0)
sb.Append (",");
sb.Append (GetTypeSignature (genArgs [i]));
}
sb.Append (">");
return sb.ToString ();
}
if (IsGenericParameter (t))
return t.Name;
if (t.DeclaringType != null)
return string.Concat (t.DeclaringType.FullName, "/", t.Name);
if (t.Namespace == null || t.Namespace.Length == 0)
return t.Name;
return string.Concat (t.Namespace, ".", t.Name);
}
static bool GetProperty (object o, string prop)
{
SR.PropertyInfo pi = o.GetType ().GetProperty (prop);
if (pi == null)
return false;
return (bool) pi.GetValue (o, null);
}
public static bool IsGenericType (Type t)
{
return GetProperty (t, "IsGenericType");
}
static bool IsGenericParameter (Type t)
{
return GetProperty (t, "IsGenericParameter");
}
static bool IsGenericTypeDefinition (Type t)
{
return GetProperty (t, "IsGenericTypeDefinition");
}
static bool IsGenericTypeSpec (Type t)
{
return IsGenericType (t) && !IsGenericTypeDefinition (t);
}
static Type GetGenericTypeDefinition (Type t)
{
return (Type) t.GetType ().GetMethod ("GetGenericTypeDefinition").Invoke (t, null);
}
static Type [] GetGenericArguments (Type t)
{
return (Type []) t.GetType ().GetMethod ("GetGenericArguments").Invoke (t, null);
}
GenericInstanceType GetGenericType (Type t, TypeReference element, ImportContext context)
{
GenericInstanceType git = new GenericInstanceType (element);
foreach (Type genArg in GetGenericArguments (t))
git.GenericArguments.Add (ImportSystemType (genArg, context));
return git;
}
static bool GenericParameterOfMethod (Type t)
{
return t.GetType ().GetProperty ("DeclaringMethod").GetValue (t, null) != null;
}
static GenericParameter GetGenericParameter (Type t, ImportContext context)
{
int pos = (int) t.GetType ().GetProperty ("GenericParameterPosition").GetValue (t, null);
if (GenericParameterOfMethod (t))
return context.GenericContext.Method.GenericParameters [pos];
else
return context.GenericContext.Type.GenericParameters [pos];
}
TypeReference GetTypeSpec (Type t, ImportContext context)
{
Stack s = new Stack ();
while (t.HasElementType || IsGenericTypeSpec (t)) {
s.Push (t);
if (t.HasElementType)
t = t.GetElementType ();
else if (IsGenericTypeSpec (t)) {
t = (Type) t.GetType ().GetMethod ("GetGenericTypeDefinition").Invoke (t, null);
break;
}
}
TypeReference elementType = ImportSystemType (t, context);
while (s.Count > 0) {
t = s.Pop () as Type;
if (t.IsPointer)
elementType = new PointerType (elementType);
else if (t.IsArray) // deal with complex arrays
elementType = new ArrayType (elementType);
else if (t.IsByRef)
elementType = new ReferenceType (elementType);
else if (IsGenericTypeSpec (t))
elementType = GetGenericType (t, elementType, context);
else
throw new ReflectionException ("Unknown element type");
}
return elementType;
}
public TypeReference ImportSystemType (Type t, ImportContext context)
{
if (t.HasElementType || IsGenericTypeSpec (t))
return GetTypeSpec (t, context);
if (IsGenericParameter (t))
return GetGenericParameter (t, context);
ImportCache ();
TypeReference type = m_module.TypeReferences [GetTypeSignature (t)];
if (type != null)
return type;
AssemblyNameReference asm = ImportAssembly (t.Assembly);
type = new TypeReference (t.Name, t.Namespace, asm, t.IsValueType);
if (IsGenericTypeDefinition (t))
foreach (Type genParam in GetGenericArguments (t))
type.GenericParameters.Add (new GenericParameter (genParam.Name, type));
context.GenericContext.Type = type;
m_module.TypeReferences.Add (type);
return type;
}
static string GetMethodBaseSignature (SR.MethodBase meth, Type declaringType, Type retType)
{
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (retType));
sb.Append (' ');
sb.Append (GetTypeSignature (declaringType));
sb.Append ("::");
sb.Append (meth.Name);
if (IsGenericMethodSpec (meth)) {
sb.Append ("<");
Type [] genArgs = GetGenericArguments (meth as SR.MethodInfo);
for (int i = 0; i < genArgs.Length; i++) {
if (i > 0)
sb.Append (",");
sb.Append (GetTypeSignature (genArgs [i]));
}
sb.Append (">");
}
sb.Append ("(");
SR.ParameterInfo [] parameters = meth.GetParameters ();
for (int i = 0; i < parameters.Length; i++) {
if (i > 0)
sb.Append (", ");
sb.Append (GetTypeSignature (parameters [i].ParameterType));
}
sb.Append (")");
return sb.ToString ();
}
static bool IsGenericMethod (SR.MethodBase mb)
{
return GetProperty (mb, "IsGenericMethod");
}
static bool IsGenericMethodDefinition (SR.MethodBase mb)
{
return GetProperty (mb, "IsGenericMethodDefinition");
}
static bool IsGenericMethodSpec (SR.MethodBase mb)
{
return IsGenericMethod (mb) && !IsGenericMethodDefinition (mb);
}
static Type [] GetGenericArguments (SR.MethodInfo mi)
{
return (Type []) mi.GetType ().GetMethod ("GetGenericArguments").Invoke (mi, null);
}
static int GetMetadataToken (SR.MethodInfo mi)
{
return (int) mi.GetType ().GetProperty ("MetadataToken").GetValue (mi, null);
}
MethodReference ImportGenericInstanceMethod (SR.MethodInfo mi, ImportContext context)
{
SR.MethodInfo gmd = (SR.MethodInfo) mi.GetType ().GetMethod ("GetGenericMethodDefinition").Invoke (mi, null);
GenericInstanceMethod gim = new GenericInstanceMethod (
ImportMethodBase (gmd, gmd.ReturnType, context));
foreach (Type genArg in GetGenericArguments (mi))
gim.GenericArguments.Add (ImportSystemType (genArg, context));
return gim;
}
MethodReference ImportMethodBase (SR.MethodBase mb, Type retType, ImportContext context)
{
if (IsGenericMethod (mb) && !IsGenericMethodDefinition (mb))
return ImportGenericInstanceMethod ((SR.MethodInfo) mb, context);
ImportCache ();
Type originalDecType = mb.DeclaringType;
Type declaringTypeDef = originalDecType;
while (IsGenericTypeSpec (declaringTypeDef))
declaringTypeDef = GetGenericTypeDefinition (declaringTypeDef);
if (mb.DeclaringType != declaringTypeDef && mb is SR.MethodInfo) {
int mt = GetMetadataToken (mb as SR.MethodInfo);
// hack to get the generic method definition from the constructed method
foreach (SR.MethodInfo mi in declaringTypeDef.GetMethods ()) {
if (GetMetadataToken (mi) == mt) {
mb = mi;
retType = mi.ReturnType;
break;
}
}
}
string sig = GetMethodBaseSignature (mb, originalDecType, retType);
MethodReference meth = m_memberRefCache [sig] as MethodReference;
if (meth != null)
return meth;
meth = new MethodReference (
mb.Name,
(mb.CallingConvention & SR.CallingConventions.HasThis) > 0,
(mb.CallingConvention & SR.CallingConventions.ExplicitThis) > 0,
MethodCallingConvention.Default); // TODO: get the real callconv
meth.DeclaringType = ImportSystemType (originalDecType, context);
if (IsGenericMethod (mb))
foreach (Type genParam in GetGenericArguments (mb as SR.MethodInfo))
meth.GenericParameters.Add (new GenericParameter (genParam.Name, meth));
context.GenericContext.Method = meth;
context.GenericContext.Type = ImportSystemType (declaringTypeDef, context);
meth.ReturnType.ReturnType = ImportSystemType (retType, context);
SR.ParameterInfo [] parameters = mb.GetParameters ();
for (int i = 0; i < parameters.Length; i++)
meth.Parameters.Add (new ParameterDefinition (
ImportSystemType (parameters [i].ParameterType, context)));
m_module.MemberReferences.Add (meth);
m_memberRefCache [sig] = meth;
return meth;
}
public MethodReference ImportConstructorInfo (SR.ConstructorInfo ci, ImportContext context)
{
return ImportMethodBase (ci, typeof (void), context);
}
public MethodReference ImportMethodInfo (SR.MethodInfo mi, ImportContext context)
{
return ImportMethodBase (mi, mi.ReturnType, context);
}
static string GetFieldSignature (SR.FieldInfo field)
{
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (field.FieldType));
sb.Append (' ');
sb.Append (GetTypeSignature (field.DeclaringType));
sb.Append ("::");
sb.Append (field.Name);
return sb.ToString ();
}
public FieldReference ImportFieldInfo (SR.FieldInfo fi, ImportContext context)
{
ImportCache ();
string sig = GetFieldSignature (fi);
FieldReference f = (FieldReference) m_memberRefCache [sig];
if (f != null)
return f;
f = new FieldReference (
fi.Name,
ImportSystemType (fi.DeclaringType, context),
ImportSystemType (fi.FieldType, context));
m_module.MemberReferences.Add (f);
m_memberRefCache [sig] = f;
return f;
}
public AssemblyNameReference ImportAssembly (AssemblyNameReference asm)
{
ImportCache ();
AssemblyNameReference asmRef = (AssemblyNameReference) m_asmCache [asm.FullName];
if (asmRef != null)
return asmRef;
asmRef = new AssemblyNameReference (
asm.Name, asm.Culture, asm.Version);
asmRef.PublicKeyToken = asm.PublicKeyToken;
asmRef.HashAlgorithm = asm.HashAlgorithm;
m_module.AssemblyReferences.Add (asmRef);
m_asmCache [asm.FullName] = asmRef;
return asmRef;
}
TypeReference GetTypeSpec (TypeReference t, ImportContext context)
{
Stack s = new Stack ();
while (t is TypeSpecification) {
s.Push (t);
t = (t as TypeSpecification).ElementType;
}
TypeReference elementType = ImportTypeReference (t, context);
while (s.Count > 0) {
t = s.Pop () as TypeReference;
if (t is PointerType)
elementType = new PointerType (elementType);
else if (t is ArrayType) // deal with complex arrays
elementType = new ArrayType (elementType);
else if (t is ReferenceType)
elementType = new ReferenceType (elementType);
else if (t is GenericInstanceType) {
GenericInstanceType git = t as GenericInstanceType;
GenericInstanceType genElemType = new GenericInstanceType (elementType);
foreach (TypeReference arg in git.GenericArguments)
genElemType.GenericArguments.Add (ImportTypeReference (arg, context));
elementType = genElemType;
} else
throw new ReflectionException ("Unknown element type: {0}", t.GetType ().Name);
}
return elementType;
}
static GenericParameter GetGenericParameter (GenericParameter gp, ImportContext context)
{
GenericParameter p;
if (gp.Owner is TypeReference)
p = context.GenericContext.Type.GenericParameters [gp.Position];
else if (gp.Owner is MethodReference)
p = context.GenericContext.Method.GenericParameters [gp.Position];
else
throw new NotSupportedException ();
return p;
}
public TypeReference ImportTypeReference (TypeReference t, ImportContext context)
{
if (t.Module == m_module)
return t;
ImportCache ();
if (t is TypeSpecification)
return GetTypeSpec (t, context);
if (t is GenericParameter)
return GetGenericParameter (t as GenericParameter, context);
TypeReference type = m_module.TypeReferences [t.FullName];
if (type != null)
return type;
AssemblyNameReference asm;
if (t.Scope is AssemblyNameReference)
asm = ImportAssembly ((AssemblyNameReference) t.Scope);
else if (t.Scope is ModuleDefinition)
asm = ImportAssembly (((ModuleDefinition) t.Scope).Assembly.Name);
else
throw new NotImplementedException ();
type = new TypeReference (t.Name, t.Namespace, asm, t.IsValueType);
context.GenericContext.Type = type;
foreach (GenericParameter gp in t.GenericParameters)
type.GenericParameters.Add (GenericParameter.Clone (gp, context));
m_module.TypeReferences.Add (type);
return type;
}
MethodReference GetMethodSpec (MethodReference meth, ImportContext context)
{
if (!(meth is GenericInstanceMethod))
return null;
GenericInstanceMethod gim = meth as GenericInstanceMethod;
GenericInstanceMethod ngim = new GenericInstanceMethod (
ImportMethodReference (gim.ElementMethod, context));
foreach (TypeReference arg in gim.GenericArguments)
ngim.GenericArguments.Add (ImportTypeReference (arg, context));
return ngim;
}
public MethodReference ImportMethodReference (MethodReference mr, ImportContext context)
{
if (mr.DeclaringType.Module == m_module)
return mr;
ImportCache ();
if (mr is MethodSpecification)
return GetMethodSpec (mr, context);
MethodReference meth = m_memberRefCache [mr.ToString ()] as MethodReference;
if (meth != null)
return meth;
meth = new MethodReference (
mr.Name,
mr.HasThis,
mr.ExplicitThis,
mr.CallingConvention);
meth.DeclaringType = ImportTypeReference (mr.DeclaringType, context);
TypeReference contextType = meth.DeclaringType;
while (contextType is TypeSpecification)
contextType = (contextType as TypeSpecification).ElementType;
context.GenericContext.Method = meth;
context.GenericContext.Type = contextType;
foreach (GenericParameter gp in mr.GenericParameters)
meth.GenericParameters.Add (GenericParameter.Clone (gp, context));
meth.ReturnType.ReturnType = ImportTypeReference (mr.ReturnType.ReturnType, context);
foreach (ParameterDefinition param in mr.Parameters)
meth.Parameters.Add (new ParameterDefinition (
ImportTypeReference (param.ParameterType, context)));
m_module.MemberReferences.Add (meth);
m_memberRefCache [mr.ToString ()] = meth;
return meth;
}
public FieldReference ImportFieldReference (FieldReference field, ImportContext context)
{
if (field.DeclaringType.Module == m_module)
return field;
ImportCache ();
FieldReference f = (FieldReference) m_memberRefCache [field.ToString ()];
if (f != null)
return f;
f = new FieldReference (
field.Name,
ImportTypeReference (field.DeclaringType, context),
ImportTypeReference (field.FieldType, context));
m_module.MemberReferences.Add (f);
m_memberRefCache [field.ToString ()] = f;
return f;
}
public FieldDefinition ImportFieldDefinition (FieldDefinition field, ImportContext context)
{
return FieldDefinition.Clone (field, context);
}
public MethodDefinition ImportMethodDefinition (MethodDefinition meth, ImportContext context)
{
return MethodDefinition.Clone (meth, context);
}
public TypeDefinition ImportTypeDefinition (TypeDefinition type, ImportContext context)
{
return TypeDefinition.Clone (type, context);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Internal.NativeCrypto;
using Internal.Cryptography;
using Internal.Cryptography.Pal.Native;
using FILETIME = Internal.Cryptography.Pal.Native.FILETIME;
using System.Security.Cryptography;
using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal
{
internal sealed partial class CertificatePal : IDisposable, ICertificatePal
{
public static ICertificatePal FromHandle(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Arg_InvalidHandle, "handle");
SafeCertContextHandle safeCertContextHandle = Interop.crypt32.CertDuplicateCertificateContext(handle);
if (safeCertContextHandle.IsInvalid)
throw new CryptographicException(ErrorCode.HRESULT_INVALID_HANDLE);
CRYPTOAPI_BLOB dataBlob;
int cbData = 0;
bool deleteKeyContainer = Interop.crypt32.CertGetCertificateContextProperty(safeCertContextHandle, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, out dataBlob, ref cbData);
return new CertificatePal(safeCertContextHandle, deleteKeyContainer);
}
public IntPtr Handle
{
get { return _certContext.DangerousGetHandle(); }
}
public String Issuer
{
get
{
return GetIssuerOrSubject(issuer: true);
}
}
public String Subject
{
get
{
return GetIssuerOrSubject(issuer: false);
}
}
public byte[] Thumbprint
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, null, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
byte[] thumbprint = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_SHA1_HASH_PROP_ID, thumbprint, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return thumbprint;
}
}
public String KeyAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String keyAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
GC.KeepAlive(this);
return keyAlgorithm;
}
}
}
public byte[] KeyAlgorithmParameters
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String keyAlgorithmOid = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId);
int algId;
if (keyAlgorithmOid == Oids.RsaRsa)
algId = AlgId.CALG_RSA_KEYX; // Fast-path for the most common case.
else
algId = OidInfo.FindOidInfo(CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY, keyAlgorithmOid, OidGroup.PublicKeyAlgorithm, fallBackToAllGroups: true).AlgId;
unsafe
{
byte* NULL_ASN_TAG = (byte*)0x5;
byte[] keyAlgorithmParameters;
if (algId == AlgId.CALG_DSS_SIGN
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.cbData == 0
&& pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.pbData == NULL_ASN_TAG)
{
//
// DSS certificates may not have the DSS parameters in the certificate. In this case, we try to build
// the certificate chain and propagate the parameters down from the certificate chain.
//
keyAlgorithmParameters = PropagateKeyAlgorithmParametersFromChain();
}
else
{
keyAlgorithmParameters = pCertContext->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters.ToByteArray();
}
GC.KeepAlive(this);
return keyAlgorithmParameters;
}
}
}
}
private byte[] PropagateKeyAlgorithmParametersFromChain()
{
unsafe
{
SafeX509ChainHandle certChainContext = null;
try
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
{
CERT_CHAIN_PARA chainPara = new CERT_CHAIN_PARA();
chainPara.cbSize = sizeof(CERT_CHAIN_PARA);
if (!Interop.crypt32.CertGetCertificateChain(ChainEngine.HCCE_CURRENT_USER, _certContext, (FILETIME*)null, SafeCertStoreHandle.InvalidHandle, ref chainPara, CertChainFlags.None, IntPtr.Zero, out certChainContext))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, null, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
}
byte[] keyAlgorithmParameters = new byte[cbData];
if (!Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_PUBKEY_ALG_PARA_PROP_ID, keyAlgorithmParameters, ref cbData))
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return keyAlgorithmParameters;
}
finally
{
if (certChainContext != null)
certChainContext.Dispose();
}
}
}
public byte[] PublicKeyValue
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] publicKey = pCertContext->pCertInfo->SubjectPublicKeyInfo.PublicKey.ToByteArray();
GC.KeepAlive(this);
return publicKey;
}
}
}
public byte[] SerialNumber
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
byte[] serialNumber = pCertContext->pCertInfo->SerialNumber.ToByteArray();
GC.KeepAlive(this);
return serialNumber;
}
}
}
public String SignatureAlgorithm
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
String signatureAlgorithm = Marshal.PtrToStringAnsi(pCertContext->pCertInfo->SignatureAlgorithm.pszObjId);
GC.KeepAlive(this);
return signatureAlgorithm;
}
}
}
public DateTime NotAfter
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notAfter = pCertContext->pCertInfo->NotAfter.ToDateTime();
GC.KeepAlive(this);
return notAfter;
}
}
}
public DateTime NotBefore
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
DateTime notBefore = pCertContext->pCertInfo->NotBefore.ToDateTime();
GC.KeepAlive(this);
return notBefore;
}
}
}
public byte[] RawData
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int count = pCertContext->cbCertEncoded;
byte[] rawData = new byte[count];
Marshal.Copy((IntPtr)(pCertContext->pbCertEncoded), rawData, 0, count);
GC.KeepAlive(this);
return rawData;
}
}
}
public int Version
{
get
{
unsafe
{
CERT_CONTEXT* pCertContext = _certContext.CertContext;
int version = pCertContext->pCertInfo->dwVersion + 1;
GC.KeepAlive(this);
return version;
}
}
}
public bool Archived
{
get
{
int uninteresting = 0;
bool archivePropertyExists = Interop.crypt32.CertGetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, null, ref uninteresting);
return archivePropertyExists;
}
set
{
unsafe
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(0, (byte*)null);
CRYPTOAPI_BLOB* pValue = value ? &blob : (CRYPTOAPI_BLOB*)null;
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_ARCHIVED_PROP_ID, CertSetPropertyFlags.None, pValue))
throw new CryptographicException(Marshal.GetLastWin32Error());
return;
}
}
}
public String FriendlyName
{
get
{
int cbData = 0;
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, null, ref cbData))
return String.Empty;
StringBuilder sb = new StringBuilder((cbData + 1) / 2);
if (!Interop.crypt32.CertGetCertificateContextPropertyString(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, sb, ref cbData))
return String.Empty;
return sb.ToString();
}
set
{
String friendlyName = (value == null) ? String.Empty : value;
unsafe
{
IntPtr pFriendlyName = Marshal.StringToHGlobalUni(friendlyName);
try
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(checked(2 * (friendlyName.Length + 1)), (byte*)pFriendlyName);
if (!Interop.crypt32.CertSetCertificateContextProperty(_certContext, CertContextPropId.CERT_FRIENDLY_NAME_PROP_ID, CertSetPropertyFlags.None, &blob))
throw new CryptographicException(Marshal.GetLastWin32Error());
}
finally
{
Marshal.FreeHGlobal(pFriendlyName);
}
}
return;
}
}
public X500DistinguishedName SubjectName
{
get
{
unsafe
{
byte[] encodedSubjectName = _certContext.CertContext->pCertInfo->Subject.ToByteArray();
X500DistinguishedName subjectName = new X500DistinguishedName(encodedSubjectName);
GC.KeepAlive(this);
return subjectName;
}
}
}
public X500DistinguishedName IssuerName
{
get
{
unsafe
{
byte[] encodedIssuerName = _certContext.CertContext->pCertInfo->Issuer.ToByteArray();
X500DistinguishedName issuerName = new X500DistinguishedName(encodedIssuerName);
GC.KeepAlive(this);
return issuerName;
}
}
}
public IEnumerable<X509Extension> Extensions
{
get
{
unsafe
{
LowLevelListWithIList<X509Extension> extensions = new LowLevelListWithIList<X509Extension>();
CERT_INFO* pCertInfo = _certContext.CertContext->pCertInfo;
int numExtensions = pCertInfo->cExtension;
for (int i = 0; i < numExtensions; i++)
{
CERT_EXTENSION* pCertExtension = pCertInfo->rgExtension + i;
String oidValue = Marshal.PtrToStringAnsi(pCertExtension->pszObjId);
Oid oid = new Oid(oidValue);
bool critical = pCertExtension->fCritical != 0;
byte[] rawData = pCertExtension->Value.ToByteArray();
X509Extension extension = new X509Extension(oid, rawData, critical);
extensions.Add(extension);
}
GC.KeepAlive(this);
return extensions;
}
}
}
public String GetNameInfo(X509NameType nameType, bool forIssuer)
{
CertNameType certNameType = MapNameType(nameType);
CertNameFlags certNameFlags = forIssuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStrTypeAndFlags strType = CertNameStrTypeAndFlags.CERT_X500_NAME_STR | CertNameStrTypeAndFlags.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, null, 0);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetLastWin32Error());
StringBuilder sb = new StringBuilder(cchCount);
if (Interop.crypt32.CertGetNameString(_certContext, certNameType, certNameFlags, ref strType, sb, cchCount) == 0)
throw new CryptographicException(Marshal.GetLastWin32Error());
return sb.ToString();
}
public void AppendPrivateKeyInfo(StringBuilder sb)
{
CspKeyContainerInfo cspKeyContainerInfo = null;
try
{
if (HasPrivateKey)
{
CspParameters parameters = GetPrivateKey();
cspKeyContainerInfo = new CspKeyContainerInfo(parameters);
}
}
// We could not access the key container. Just return.
catch (CryptographicException) { }
if (cspKeyContainerInfo == null)
return;
sb.Append(Environment.NewLine + Environment.NewLine + "[Private Key]");
sb.Append(Environment.NewLine + " Key Store: ");
sb.Append(cspKeyContainerInfo.MachineKeyStore ? "Machine" : "User");
sb.Append(Environment.NewLine + " Provider Name: ");
sb.Append(cspKeyContainerInfo.ProviderName);
sb.Append(Environment.NewLine + " Provider type: ");
sb.Append(cspKeyContainerInfo.ProviderType);
sb.Append(Environment.NewLine + " Key Spec: ");
sb.Append(cspKeyContainerInfo.KeyNumber);
sb.Append(Environment.NewLine + " Key Container Name: ");
sb.Append(cspKeyContainerInfo.KeyContainerName);
try
{
String uniqueKeyContainer = cspKeyContainerInfo.UniqueKeyContainerName;
sb.Append(Environment.NewLine + " Unique Key Container Name: ");
sb.Append(uniqueKeyContainer);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
bool b = false;
try
{
b = cspKeyContainerInfo.HardwareDevice;
sb.Append(Environment.NewLine + " Hardware Device: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Removable;
sb.Append(Environment.NewLine + " Removable: ");
sb.Append(b);
}
catch (CryptographicException) { }
try
{
b = cspKeyContainerInfo.Protected;
sb.Append(Environment.NewLine + " Protected: ");
sb.Append(b);
}
catch (CryptographicException) { }
catch (NotSupportedException) { }
}
public void Dispose()
{
SafeCertContextHandle certContext = _certContext;
_certContext = null;
if (certContext != null && !certContext.IsInvalid)
{
certContext.Dispose();
}
return;
}
internal SafeCertContextHandle CertContext
{
get
{
SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(_certContext.DangerousGetHandle());
GC.KeepAlive(_certContext);
return certContext;
}
}
private static CertNameType MapNameType(X509NameType nameType)
{
switch (nameType)
{
case X509NameType.SimpleName:
return CertNameType.CERT_NAME_SIMPLE_DISPLAY_TYPE;
case X509NameType.EmailName:
return CertNameType.CERT_NAME_EMAIL_TYPE;
case X509NameType.UpnName:
return CertNameType.CERT_NAME_UPN_TYPE;
case X509NameType.DnsName:
case X509NameType.DnsFromAlternativeName:
return CertNameType.CERT_NAME_DNS_TYPE;
case X509NameType.UrlName:
return CertNameType.CERT_NAME_URL_TYPE;
default:
throw new ArgumentException(SR.Argument_InvalidNameType);
}
}
private String GetIssuerOrSubject(bool issuer)
{
CertNameFlags flags = issuer ? CertNameFlags.CERT_NAME_ISSUER_FLAG : CertNameFlags.None;
CertNameStringType stringType = CertNameStringType.CERT_X500_NAME_STR | CertNameStringType.CERT_NAME_STR_REVERSE_FLAG;
int cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, null, 0);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
StringBuilder sb = new StringBuilder(cchCount);
cchCount = Interop.crypt32.CertGetNameString(_certContext, CertNameType.CERT_NAME_RDN_TYPE, flags, ref stringType, sb, cchCount);
if (cchCount == 0)
throw new CryptographicException(Marshal.GetHRForLastWin32Error());
return sb.ToString();
}
private CertificatePal(SafeCertContextHandle certContext, bool deleteKeyContainer)
{
if (deleteKeyContainer)
{
// We need to delete any associated key container upon disposition. Thus, replace the safehandle we got with a safehandle whose
// Release() method performs the key container deletion.
SafeCertContextHandle oldCertContext = certContext;
certContext = Interop.crypt32.CertDuplicateCertificateContextWithKeyContainerDeletion(oldCertContext.DangerousGetHandle());
GC.KeepAlive(oldCertContext);
}
_certContext = certContext;
return;
}
private SafeCertContextHandle _certContext;
}
}
| |
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
// for fxcop
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Net;
using System.Net.NetworkInformation;
using System.Numerics;
using System.Reflection;
using System.Security;
using System.Security.AccessControl;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Xml;
using Microsoft.Management.Infrastructure;
using Microsoft.PowerShell.Commands;
#if !CORECLR
// System.DirectoryServices are not in CoreCLR
using System.DirectoryServices;
using System.Net.Mail;
#endif
namespace System.Management.Automation.Language
{
internal static class TypeResolver
{
// our interface
// internal static Type ConvertTypeNameToType(TypeName typeName, out Exception exception)
// Used by TypeName.GetReflectionType and in TypeResolver
// internal static bool TryResolveType(string typeName, out Type type)
// Used in a bunch of places
// internal static Type ConvertStringToType(string typeName, out Exception exception)
// Used primarily in LanguagePrimitives.ConvertTo
private static Type LookForTypeInSingleAssembly(Assembly assembly, string typename)
{
Type targetType = assembly.GetType(typename, false, true);
if (targetType != null && IsPublic(targetType))
{
return targetType;
}
return null;
}
/// <summary>
/// Inherited from InvalidCastException, because it happens in [string] -> [Type] conversion.
/// </summary>
internal class AmbiguousTypeException : InvalidCastException
{
public string[] Candidates { private set; get; }
public TypeName TypeName { private set; get; }
public AmbiguousTypeException(TypeName typeName, IEnumerable<string> candidates)
{
Candidates = candidates.ToArray();
TypeName = typeName;
Diagnostics.Assert(Candidates.Length > 1, "AmbiguousTypeException can be created only when there are more then 1 candidate.");
}
}
private static Type LookForTypeInAssemblies(TypeName typeName, IEnumerable<Assembly> assemblies, TypeResolutionState typeResolutionState, bool reportAmbiguousException, out Exception exception)
{
exception = null;
string alternateNameToFind = typeResolutionState.GetAlternateTypeName(typeName.Name);
Type foundType = null;
Type foundType2 = null;
foreach (Assembly assembly in assemblies)
{
try
{
Type targetType = LookForTypeInSingleAssembly(assembly, typeName.Name); ;
if (targetType == null && alternateNameToFind != null)
{
targetType = LookForTypeInSingleAssembly(assembly, alternateNameToFind);
}
if (targetType != null)
{
if (!reportAmbiguousException)
{
// accelerator for the common case, when we are not interested in ambiguity exception.
return targetType;
}
// .NET has forward notation for types, when they declared in one assembly and implemented in another one.
// We want to support both scenarios:
// 1) When we pass assembly with declared forwarded type (CoreCLR)
// 2) When we pass assembly with declared forwarded type and assembly with implemented forwarded type (FullCLR)
// In the case (2) we should not report duplicate, hence this check
if (foundType != targetType)
{
if (foundType != null)
{
foundType2 = targetType;
break;
}
else
{
foundType = targetType;
}
}
}
}
catch (Exception e) // Assembly.GetType might throw unadvertised exceptions
{
CommandProcessorBase.CheckForSevereException(e);
}
}
if (foundType2 != null)
{
exception = new AmbiguousTypeException(typeName, new String[] { foundType.AssemblyQualifiedName, foundType2.AssemblyQualifiedName });
return null;
}
return foundType;
}
/// <summary>
/// A type IsPublic if IsPublic or (IsNestedPublic and is nested in public type(s))
/// </summary>
internal static bool IsPublic(Type type)
{
TypeInfo typeInfo = type.GetTypeInfo();
return IsPublic(typeInfo);
}
/// <summary>
/// A typeInfo is public if IsPublic or (IsNestedPublic and is nested in public type(s))
/// </summary>
internal static bool IsPublic(TypeInfo typeInfo)
{
if (typeInfo.IsPublic)
{
return true;
}
if (!typeInfo.IsNestedPublic)
{
return false;
}
Type type;
while ((type = typeInfo.DeclaringType) != null)
{
typeInfo = type.GetTypeInfo();
if (!(typeInfo.IsPublic || typeInfo.IsNestedPublic))
{
return false;
}
}
return true;
}
private static Type ResolveTypeNameWorker(TypeName typeName, SessionStateScope currentScope, IEnumerable<Assembly> loadedAssemblies, TypeResolutionState typeResolutionState, bool reportAmbiguousException, out Exception exception)
{
Type result;
exception = null;
while (currentScope != null)
{
result = currentScope.LookupType(typeName.Name);
if (result != null)
{
return result;
}
currentScope = currentScope.Parent;
}
if (TypeAccelerators.builtinTypeAccelerators.TryGetValue(typeName.Name, out result))
{
return result;
}
exception = null;
result = LookForTypeInAssemblies(typeName, loadedAssemblies, typeResolutionState, reportAmbiguousException, out exception);
if (exception != null)
{
// skip the rest of lookups, if exception reported.
return result;
}
if (result == null)
{
lock (TypeAccelerators.userTypeAccelerators)
{
TypeAccelerators.userTypeAccelerators.TryGetValue(typeName.Name, out result);
}
}
return result;
}
internal static Type ResolveAssemblyQualifiedTypeName(TypeName typeName, out Exception exception)
{
// If an assembly name was specified, we let Type.GetType deal with loading the assembly
// and resolving the type.
exception = null;
try
{
// We shouldn't really bother looking for the type in System namespace, but
// we've always done that. We explicitly are not supporting arbitrary
// 'using namespace' here because there is little value, if you need the assembly
// qualifier, it's best to just fully specify the type.
var result = Type.GetType(typeName.FullName, false, true) ??
Type.GetType("System." + typeName.FullName, false, true);
if (result != null && IsPublic(result))
{
return result;
}
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
exception = e;
}
return null;
}
internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception exception, Assembly[] assemblies, TypeResolutionState typeResolutionState)
{
ExecutionContext context = null;
exception = null;
if (typeResolutionState == null)
{
// Usings from script scope (and if no script scope, fall back to default 'using namespace system')
context = LocalPipeline.GetExecutionContextFromTLS();
typeResolutionState = TypeResolutionState.GetDefaultUsingState(context);
}
// We can do the cache lookup only if we don't define type in the current scope (cache would be invalid in this case).
var result = typeResolutionState.ContainsTypeDefined(typeName.Name)
? null
: TypeCache.Lookup(typeName, typeResolutionState);
if (result != null)
{
return result;
}
if (typeName.AssemblyName != null)
{
result = ResolveAssemblyQualifiedTypeName(typeName, out exception);
TypeCache.Add(typeName, typeResolutionState, result);
return result;
}
// Simple typename (no generics, no arrays, no assembly name)
// We use the following search order, using the specified name (assumed to be fully namespace qualified):
//
// * Search scope table (includes 'using type x = ...' aliases)
// * Built in type accelerators (implicit 'using type x = ...' aliases that are effectively in global scope
// * typeResolutionState.assemblies, which contains:
// - Assemblies with PS types, added by 'using module'
// - Assemblies added by 'using assembly'.
// For this case, we REPORT ambiguity, since user explicitly specifies the set of assemblies.
// * All other loaded assemblies (excluding dynamic assemblies created for PS defined types).
// IGNORE ambiguity. It mimics PS v4. There are two reasons:
// 1) If we report ambiguity, we need to fix our caching logic accordingly.
// Consider this code
// Add-Type 'public class Q {}' # ok
// Add-Type 'public class Q { }' # get error about the same name
// [Q] # we would get error about ambiguous type, because we added assembly with duplicated type
// # before we can report TYPE_ALREADY_EXISTS error.
//
// Add-Type 'public class Q2 {}' # ok
// [Q2] # caching Q2 type
// Add-Type 'public class Q2 { }' # get error about the same name
// [Q2] # we don't get an error about ambiguous type, because it's cached already
// 2) NuGet (VS Package Management console) uses MEF extensibility model.
// Different assemblies includes same interface (i.e. NuGet.VisualStudio.IVsPackageInstallerServices),
// where they include only methods that they are interested in the interface declaration (result interfaces are different!).
// Then, at runtime VS provides an instance. Everything work as far as instance has compatible API.
// So [NuGet.VisualStudio.IVsPackageInstallerServices] can be resolved to several different assemblies and it's ok.
// * User defined type accelerators (rare - interface was never public)
//
// If nothing is found, we search again, this time applying any 'using namespace ...' declarations including the implicit 'using namespace System'.
// We must search all using aliases and REPORT an error if there is an ambiguity.
var assemList = assemblies ?? ClrFacade.GetAssemblies(typeResolutionState, typeName);
if (context == null)
{
context = LocalPipeline.GetExecutionContextFromTLS();
}
SessionStateScope currentScope = null;
if (context != null)
{
currentScope = context.EngineSessionState.CurrentScope;
}
// If this is TypeDefinition we should not cache anything in TypeCache.
if (typeName._typeDefinitionAst != null)
{
return typeName._typeDefinitionAst.Type;
}
result = ResolveTypeNameWorker(typeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbiguousException */ true, out exception);
if (exception == null && result == null)
{
result = ResolveTypeNameWorker(typeName, currentScope, assemList, typeResolutionState, /* reportAmbiguousException */ false, out exception);
}
if (result != null)
{
TypeCache.Add(typeName, typeResolutionState, result);
return result;
}
if (exception == null)
{
foreach (var ns in typeResolutionState.namespaces)
{
var newTypeNameToSearch = ns + "." + typeName.Name;
newTypeNameToSearch = typeResolutionState.GetAlternateTypeName(newTypeNameToSearch) ??
newTypeNameToSearch;
var newTypeName = new TypeName(typeName.Extent, newTypeNameToSearch);
#if CORECLR
if (assemblies == null)
{
// We called 'ClrFacade.GetAssemblies' to get assemblies. That means the assemblies to search from
// are not pre-defined, and thus we have to refetch assembly again based on the new type name.
assemList = ClrFacade.GetAssemblies(typeResolutionState, newTypeName);
}
#endif
var newResult = ResolveTypeNameWorker(newTypeName, currentScope, typeResolutionState.assemblies, typeResolutionState, /* reportAmbiguousException */ true, out exception);
if (exception == null && newResult == null)
{
newResult = ResolveTypeNameWorker(newTypeName, currentScope, assemList, typeResolutionState, /* reportAmbiguousException */ false, out exception);
}
if (exception != null)
{
break;
}
if (newResult != null)
{
if (result == null)
{
result = newResult;
}
else
{
exception = new AmbiguousTypeException(typeName, new string[] { result.FullName, newResult.FullName });
result = null;
break;
}
}
}
}
if (exception != null)
{
// AmbiguousTypeException is for internal representation only.
var ambiguousException = exception as AmbiguousTypeException;
if (ambiguousException != null)
{
exception = new PSInvalidCastException("AmbiguousTypeReference", exception,
ParserStrings.AmbiguousTypeReference, ambiguousException.TypeName.Name,
ambiguousException.Candidates[0], ambiguousException.Candidates[1]);
}
}
if (result != null)
{
TypeCache.Add(typeName, typeResolutionState, result);
}
return result;
}
internal static Type ResolveTypeName(TypeName typeName, out Exception exception)
{
return ResolveTypeNameWithContext(typeName, out exception, null, null);
}
internal static bool TryResolveType(string typeName, out Type type)
{
Exception exception;
type = ResolveType(typeName, out exception);
return (type != null);
}
internal static Type ResolveITypeName(ITypeName iTypeName, out Exception exception)
{
exception = null;
var typeName = iTypeName as TypeName;
if (typeName == null)
{
// The type is something more complicated - generic or array.
try
{
return iTypeName.GetReflectionType();
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
exception = e;
return null;
}
}
return ResolveTypeName(typeName, out exception);
}
/// <summary>
/// This routine converts a string into a Type object using the msh rules.
/// </summary>
/// <param name="strTypeName">A string representing the name of the type to convert</param>
/// <param name="exception">The exception, if one happened, trying to find the type</param>
/// <returns>A type if the conversion was successful, null otherwise.</returns>
internal static Type ResolveType(string strTypeName, out Exception exception)
{
exception = null;
if (String.IsNullOrWhiteSpace(strTypeName))
{
return null;
}
var iTypeName = Parser.ScanType(strTypeName, ignoreErrors: false);
if (iTypeName == null)
{
return null;
}
return ResolveITypeName(iTypeName, out exception);
}
}
/// <summary>
/// The idea behind this class is: I should be able to re-use expensive
/// type resolution operation result in the same context.
/// Hence, this class is a key for TypeCache dictionary.
///
/// Every SessionStateScope has TypeResolutionState.
/// typesDefined contains PowerShell types names defined in the current scope and all scopes above.
/// Same for namespaces.
///
/// If TypeResolutionState doesn't add anything new compare to it's parent, we represent it as null.
/// So, when we do lookup, we need to find first non-null TypeResolutionState.
/// </summary>
internal class TypeResolutionState
{
internal static readonly string[] systemNamespace = { "System" };
internal static readonly Assembly[] emptyAssemblies = Utils.EmptyArray<Assembly>();
internal static readonly TypeResolutionState UsingSystem = new TypeResolutionState();
internal readonly string[] namespaces;
internal readonly Assembly[] assemblies;
private readonly HashSet<string> _typesDefined;
internal readonly int genericArgumentCount;
internal readonly bool attribute;
private TypeResolutionState()
: this(systemNamespace, emptyAssemblies)
{
}
/// <summary>
/// TypeResolutionState can be shared and that's why it should be represented as an immutable object.
/// So, we use this API to alternate TypeResolutionState, but instead of mutating existing one, we clone it.
/// </summary>
/// <param name="types"></param>
/// <returns></returns>
internal TypeResolutionState CloneWithAddTypesDefined(IEnumerable<string> types)
{
var newTypesDefined = new HashSet<string>(_typesDefined, StringComparer.OrdinalIgnoreCase);
foreach (var type in types)
{
newTypesDefined.Add(type);
}
return new TypeResolutionState(this, newTypesDefined);
}
internal bool ContainsTypeDefined(string type)
{
return _typesDefined.Contains(type);
}
internal TypeResolutionState(string[] namespaces, Assembly[] assemblies)
{
this.namespaces = namespaces ?? systemNamespace;
this.assemblies = assemblies ?? emptyAssemblies;
_typesDefined = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
}
internal TypeResolutionState(TypeResolutionState other, int genericArgumentCount, bool attribute)
{
this.namespaces = other.namespaces;
this.assemblies = other.assemblies;
_typesDefined = other._typesDefined;
this.genericArgumentCount = genericArgumentCount;
this.attribute = attribute;
}
private TypeResolutionState(TypeResolutionState other, HashSet<string> typesDefined)
{
this.namespaces = other.namespaces;
this.assemblies = other.assemblies;
_typesDefined = typesDefined;
this.genericArgumentCount = other.genericArgumentCount;
this.attribute = other.attribute;
}
internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context)
{
if (context == null)
{
context = LocalPipeline.GetExecutionContextFromTLS();
}
if (context != null)
{
return context.EngineSessionState.CurrentScope.TypeResolutionState;
}
return TypeResolutionState.UsingSystem;
}
internal string GetAlternateTypeName(string typeName)
{
string alternateName = null;
if (genericArgumentCount > 0 && typeName.IndexOf('`') < 0)
{
alternateName = typeName + "`" + genericArgumentCount;
}
else if (attribute && !typeName.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase))
{
alternateName = typeName + "Attribute";
}
return alternateName;
}
public override bool Equals(object obj)
{
if (object.ReferenceEquals(this, obj))
return true;
var other = obj as TypeResolutionState;
if (other == null)
return false;
if (this.attribute != other.attribute)
return false;
if (this.genericArgumentCount != other.genericArgumentCount)
return false;
if (this.namespaces.Length != other.namespaces.Length)
return false;
if (this.assemblies.Length != other.assemblies.Length)
return false;
for (int i = 0; i < namespaces.Length; i++)
{
if (!this.namespaces[i].Equals(other.namespaces[i], StringComparison.OrdinalIgnoreCase))
return false;
}
for (int i = 0; i < assemblies.Length; i++)
{
if (!this.assemblies[i].Equals(other.assemblies[i]))
return false;
}
if (_typesDefined.Count != other._typesDefined.Count)
return false;
return _typesDefined.SetEquals(other._typesDefined);
}
public override int GetHashCode()
{
var stringComparer = StringComparer.OrdinalIgnoreCase;
int result = Utils.CombineHashCodes(genericArgumentCount.GetHashCode(), attribute.GetHashCode());
for (int i = 0; i < namespaces.Length; i++)
{
result = Utils.CombineHashCodes(result, stringComparer.GetHashCode(namespaces[i]));
}
for (int i = 0; i < assemblies.Length; i++)
{
result = Utils.CombineHashCodes(result, this.assemblies[i].GetHashCode());
}
foreach (var t in _typesDefined)
{
result = Utils.CombineHashCodes(result, t.GetHashCode());
}
return result;
}
}
internal class TypeCache
{
private class KeyComparer : IEqualityComparer<Tuple<ITypeName, TypeResolutionState>>
{
public bool Equals(Tuple<ITypeName, TypeResolutionState> x,
Tuple<ITypeName, TypeResolutionState> y)
{
return x.Item1.Equals(y.Item1) && x.Item2.Equals(y.Item2);
}
public int GetHashCode(Tuple<ITypeName, TypeResolutionState> obj)
{
return obj.GetHashCode();
}
}
private static readonly ConcurrentDictionary<Tuple<ITypeName, TypeResolutionState>, Type> s_cache = new ConcurrentDictionary<Tuple<ITypeName, TypeResolutionState>, Type>(new KeyComparer());
internal static Type Lookup(ITypeName typeName, TypeResolutionState typeResolutionState)
{
Type result;
s_cache.TryGetValue(Tuple.Create(typeName, typeResolutionState), out result);
return result;
}
internal static void Add(ITypeName typeName, TypeResolutionState typeResolutionState, Type type)
{
s_cache.GetOrAdd(Tuple.Create(typeName, typeResolutionState), type);
}
}
}
namespace System.Management.Automation
{
/// <summary>
/// A class to the core types in PowerShell.
/// </summary>
internal static class CoreTypes
{
// A list of the core PowerShell types, and their accelerator.
//
// These types are frequently used in scripting, and for parameter validation in scripts.
//
// When in ConstrainedLanguage mode, all operations on these types are fully supported unlike all other
// types that are assumed to have dangerous constructors or methods.
//
// Do not add types to this pool unless they can be safely exposed to an attacker and will not
// expose the ability to corrupt or escape PowerShell's environment. The following operations must
// be safe: type conversion, all constructors, all methods (instance and static), and
// and properties (instance and static).
internal static Lazy<Dictionary<Type, string[]>> Items = new Lazy<Dictionary<Type, string[]>>(
() =>
new Dictionary<Type, string[]>
{
{ typeof(AliasAttribute), new[] { "Alias" } },
{ typeof(AllowEmptyCollectionAttribute), new[] { "AllowEmptyCollection" } },
{ typeof(AllowEmptyStringAttribute), new[] { "AllowEmptyString" } },
{ typeof(AllowNullAttribute), new[] { "AllowNull" } },
{ typeof(ArgumentCompleterAttribute), new[] { "ArgumentCompleter" } },
{ typeof(Array), new[] { "array" } },
{ typeof(bool), new[] { "bool" } },
{ typeof(byte), new[] { "byte" } },
{ typeof(char), new[] { "char" } },
{ typeof(CmdletBindingAttribute), new[] { "CmdletBinding" } },
{ typeof(DateTime), new[] { "datetime" } },
{ typeof(decimal), new[] { "decimal" } },
{ typeof(double), new[] { "double" } },
{ typeof(DscResourceAttribute), new[] { "DscResource"} },
{ typeof(float), new[] { "float", "single" } },
{ typeof(Guid), new[] { "guid" } },
{ typeof(Hashtable), new[] { "hashtable" } },
{ typeof(int), new[] { "int", "int32" } },
{ typeof(Int16), new[] { "int16" } },
{ typeof(long), new[] { "long", "int64" } },
{ typeof(CimInstance), new[] { "ciminstance" } },
{ typeof(CimClass), new[] { "cimclass" } },
{ typeof(Microsoft.Management.Infrastructure.CimType), new[] { "cimtype" } },
{ typeof(CimConverter), new[] { "cimconverter" } },
{ typeof(ModuleSpecification), null },
{ typeof(IPEndPoint), new[] { "IPEndpoint" } },
{ typeof(NullString), new[] { "NullString" } },
{ typeof(OutputTypeAttribute), new[] { "OutputType" } },
{ typeof(Object[]), null },
{ typeof(ObjectSecurity), new[] { "ObjectSecurity" } },
{ typeof(ParameterAttribute), new[] { "Parameter" } },
{ typeof(PhysicalAddress), new[] { "PhysicalAddress" } },
{ typeof(PSCredential), new[] { "pscredential" } },
{ typeof(PSDefaultValueAttribute), new[] { "PSDefaultValue" } },
{ typeof(PSListModifier), new[] { "pslistmodifier" } },
{ typeof(PSObject), new[] { "psobject", "pscustomobject" } },
{ typeof(PSPrimitiveDictionary), new[] { "psprimitivedictionary" } },
{ typeof(PSReference), new[] { "ref" } },
{ typeof(PSTypeNameAttribute), new[] { "PSTypeNameAttribute" } },
{ typeof(Regex), new[] { "regex" } },
{ typeof(DscPropertyAttribute), new[] { "DscProperty" } },
{ typeof(SByte), new[] { "sbyte" } },
{ typeof(string), new[] { "string" } },
{ typeof(SupportsWildcardsAttribute), new[] { "SupportsWildcards" } },
{ typeof(SwitchParameter), new[] { "switch" } },
{ typeof(CultureInfo), new[] { "cultureinfo" } },
{ typeof(BigInteger), new[] { "bigint" } },
{ typeof(SecureString), new[] { "securestring" } },
{ typeof(TimeSpan), new[] { "timespan" } },
{ typeof(UInt16), new[] { "uint16" } },
{ typeof(UInt32), new[] { "uint32" } },
{ typeof(UInt64), new[] { "uint64" } },
{ typeof(Uri), new[] { "uri" } },
{ typeof(ValidateCountAttribute), new[] { "ValidateCount" } },
{ typeof(ValidateDriveAttribute), new[] { "ValidateDrive" } },
{ typeof(ValidateLengthAttribute), new[] { "ValidateLength" } },
{ typeof(ValidateNotNullAttribute), new[] { "ValidateNotNull" } },
{ typeof(ValidateNotNullOrEmptyAttribute), new[] { "ValidateNotNullOrEmpty" } },
{ typeof(ValidatePatternAttribute), new[] { "ValidatePattern" } },
{ typeof(ValidateRangeAttribute), new[] { "ValidateRange" } },
{ typeof(ValidateScriptAttribute), new[] { "ValidateScript" } },
{ typeof(ValidateSetAttribute), new[] { "ValidateSet" } },
{ typeof(ValidateUserDriveAttribute), new[] { "ValidateUserDrive"} },
{ typeof(Version), new[] { "version" } },
{ typeof(void), new[] { "void" } },
{ typeof(IPAddress), new[] { "ipaddress" } },
{ typeof(DscLocalConfigurationManagerAttribute), new[] {"DscLocalConfigurationManager"}},
{ typeof(WildcardPattern), new[] { "WildcardPattern" } },
{ typeof(X509Certificate), new[] { "X509Certificate" } },
{ typeof(X500DistinguishedName), new[] { "X500DistinguishedName" } },
{ typeof(XmlDocument), new[] { "xml" } },
{ typeof(CimSession), new[] { "CimSession" } },
#if !CORECLR
// Following types not in CoreCLR
{ typeof(DirectoryEntry), new[] { "adsi" } },
{ typeof(DirectorySearcher), new[] { "adsisearcher" } },
{ typeof(ManagementClass), new[] { "wmiclass" } },
{ typeof(ManagementObject), new[] { "wmi" } },
{ typeof(ManagementObjectSearcher), new[] { "wmisearcher" } },
{ typeof(MailAddress), new[] { "mailaddress" } }
#endif
}
);
internal static bool Contains(Type inputType)
{
if (Items.Value.ContainsKey(inputType))
{
return true;
}
var inputTypeInfo = inputType.GetTypeInfo();
if (inputTypeInfo.IsEnum)
{
return true;
}
if (inputTypeInfo.IsGenericType)
{
var genericTypeDefinition = inputTypeInfo.GetGenericTypeDefinition();
return genericTypeDefinition == typeof(Nullable<>) || genericTypeDefinition == typeof(FlagsExpression<>);
}
return (inputType.IsArray && Contains(inputType.GetElementType()));
}
}
/// <summary>
/// A class to view and modify the type accelerators used by the PowerShell engine. Builtin
/// type accelerators are read only, but user defined type accelerators may be added.
/// </summary>
internal static class TypeAccelerators
{
// builtins are not exposed publicly in a direct manner so they can't be changed at all
internal static Dictionary<string, Type> builtinTypeAccelerators = new Dictionary<string, Type>(64, StringComparer.OrdinalIgnoreCase);
// users can add to user added accelerators (but not currently remove any.) Keeping a separate
// list allows us to add removing in the future w/o worrying about breaking the builtins.
internal static Dictionary<string, Type> userTypeAccelerators = new Dictionary<string, Type>(64, StringComparer.OrdinalIgnoreCase);
// We expose this one publicly for programmatic access to our type accelerator table, but it is
// otherwise unused (so changes to this dictionary don't affect internals.)
private static Dictionary<string, Type> s_allTypeAccelerators;
static TypeAccelerators()
{
// Add all the core types
foreach (KeyValuePair<Type, string[]> coreType in CoreTypes.Items.Value)
{
if (coreType.Value != null)
{
foreach (string accelerator in coreType.Value)
{
builtinTypeAccelerators.Add(accelerator, coreType.Key);
}
}
}
// Add additional utility types that are useful as type accelerators, but aren't
// fundamentally "core language", or may be unsafe to expose to untrusted input.
builtinTypeAccelerators.Add("scriptblock", typeof(ScriptBlock));
builtinTypeAccelerators.Add("psvariable", typeof(PSVariable));
builtinTypeAccelerators.Add("type", typeof(Type));
builtinTypeAccelerators.Add("psmoduleinfo", typeof(PSModuleInfo));
builtinTypeAccelerators.Add("powershell", typeof(PowerShell));
builtinTypeAccelerators.Add("runspacefactory", typeof(RunspaceFactory));
builtinTypeAccelerators.Add("runspace", typeof(Runspace));
builtinTypeAccelerators.Add("initialsessionstate", typeof(InitialSessionState));
builtinTypeAccelerators.Add("psscriptmethod", typeof(PSScriptMethod));
builtinTypeAccelerators.Add("psscriptproperty", typeof(PSScriptProperty));
builtinTypeAccelerators.Add("psnoteproperty", typeof(PSNoteProperty));
builtinTypeAccelerators.Add("psaliasproperty", typeof(PSAliasProperty));
builtinTypeAccelerators.Add("psvariableproperty", typeof(PSVariableProperty));
}
internal static string FindBuiltinAccelerator(Type type)
{
foreach (KeyValuePair<string, Type> entry in builtinTypeAccelerators)
{
if (entry.Value == type)
{
return entry.Key;
}
}
return null;
}
/// <summary>
/// Add a type accelerator.
/// </summary>
/// <param name="typeName">The type accelerator name.</param>
/// <param name="type">The type of the type accelerator.</param>
public static void Add(string typeName, Type type)
{
userTypeAccelerators[typeName] = type;
if (s_allTypeAccelerators != null)
{
s_allTypeAccelerators[typeName] = type;
}
}
/// <summary>
/// Remove a type accelerator.
/// </summary>
/// <returns>True if the accelerator was removed, false otherwise.</returns>
/// <param name="typeName">The accelerator to remove.</param>
public static bool Remove(string typeName)
{
userTypeAccelerators.Remove(typeName);
if (s_allTypeAccelerators != null)
{
s_allTypeAccelerators.Remove(typeName);
}
return true;
}
/// <summary>
/// This property is useful to tools that need to know what
/// type accelerators are available (e.g. to allow for autocompletion.)
/// </summary>
/// <remarks>
/// The returned dictionary should be treated as read only. Changes made
/// to the dictionary will not affect PowerShell scripts in any way. Use
/// <see cref="TypeAccelerators.Add"/> and
/// <see cref="TypeAccelerators.Remove"/> to
/// affect the type resolution in PowerShell scripts.
/// </remarks>
public static Dictionary<string, Type> Get
{
get
{
if (s_allTypeAccelerators == null)
{
s_allTypeAccelerators = new Dictionary<string, Type>(StringComparer.OrdinalIgnoreCase);
FillCache(s_allTypeAccelerators);
}
return s_allTypeAccelerators;
}
}
internal static void FillCache(Dictionary<string, Type> cache)
{
foreach (KeyValuePair<string, Type> val in builtinTypeAccelerators)
{
cache.Add(val.Key, val.Value);
}
foreach (KeyValuePair<string, Type> val in userTypeAccelerators)
{
cache.Add(val.Key, val.Value);
}
}
}
}
| |
// <copyright file="PhysicalFileSystem.cs" company="Microsoft Open Technologies, Inc.">
// Copyright 2011-2013 Microsoft Open Technologies, 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>
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Owin.FileSystems
{
/// <summary>
/// Looks up files using the on-disk file system
/// </summary>
public class PhysicalFileSystem : IFileSystem
{
/// <summary>
///
/// </summary>
/// <param name="root">The root directory</param>
public PhysicalFileSystem(string root)
{
Root = GetFullRoot(root);
}
/// <summary>
///
/// </summary>
public string Root { get; private set; }
private static string GetFullRoot(string root)
{
var applicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var fullRoot = Path.GetFullPath(Path.Combine(applicationBase, root));
if (!fullRoot.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
{
// When we do matches in GetFullPath, we want to only match full directory names.
fullRoot += Path.DirectorySeparatorChar;
}
return fullRoot;
}
private string GetFullPath(string path)
{
var fullPath = Path.GetFullPath(Path.Combine(Root, path));
if (!fullPath.StartsWith(Root, StringComparison.OrdinalIgnoreCase))
{
return null;
}
return fullPath;
}
/// <summary>
///
/// </summary>
/// <param name="subpath">A path under the root directory</param>
/// <param name="fileInfo">The discovered file, if any</param>
/// <returns>True if a file was discovered at the given path</returns>
public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
{
try
{
var fullPath = GetFullPath(subpath);
if (fullPath != null)
{
var info = new FileInfo(fullPath);
if (info.Exists)
{
fileInfo = new PhysicalFileInfo(info);
return true;
}
}
}
catch (ArgumentException)
{
}
fileInfo = null;
return false;
}
/// <summary>
///
/// </summary>
/// <param name="subpath">A path under the root directory</param>
/// <param name="contents">The discovered directories, if any</param>
/// <returns>True if a directory was discovered at the given path</returns>
public bool TryGetDirectoryContents(string subpath, out IEnumerable<IFileInfo> contents)
{
try
{
var fullPath = GetFullPath(subpath);
if (fullPath != null)
{
var directoryInfo = new DirectoryInfo(fullPath);
if (!directoryInfo.Exists)
{
contents = null;
return false;
}
FileSystemInfo[] physicalInfos = directoryInfo.GetFileSystemInfos();
var virtualInfos = new IFileInfo[physicalInfos.Length];
for (int index = 0; index != physicalInfos.Length; ++index)
{
var fileInfo = physicalInfos[index] as FileInfo;
if (fileInfo != null)
{
virtualInfos[index] = new PhysicalFileInfo(fileInfo);
}
else
{
virtualInfos[index] = new PhysicalDirectoryInfo((DirectoryInfo)physicalInfos[index]);
}
}
contents = virtualInfos;
return true;
}
}
catch (ArgumentException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
contents = null;
return false;
}
private class PhysicalFileInfo : IFileInfo
{
private readonly FileInfo _info;
public PhysicalFileInfo(FileInfo info)
{
_info = info;
}
public long Length
{
get { return _info.Length; }
}
public string PhysicalPath
{
get { return _info.FullName; }
}
public string Name
{
get { return _info.Name; }
}
public DateTime LastModified
{
get { return _info.LastWriteTime; }
}
public bool IsDirectory
{
get { return false; }
}
public Stream CreateReadStream()
{
return _info.OpenRead();
}
}
private class PhysicalDirectoryInfo : IFileInfo
{
private readonly DirectoryInfo _info;
public PhysicalDirectoryInfo(DirectoryInfo info)
{
_info = info;
}
public long Length
{
get { return -1; }
}
public string PhysicalPath
{
get { return _info.FullName; }
}
public string Name
{
get { return _info.Name; }
}
public DateTime LastModified
{
get { return _info.LastWriteTime; }
}
public bool IsDirectory
{
get { return true; }
}
public Stream CreateReadStream()
{
return null;
}
}
}
}
| |
using System;
using Microsoft.Xna.Framework;
namespace Zunix.ScreensManager
{
/// <summary>
/// Enum describes the screen transition state.
/// </summary>
public enum ScreenState
{
TransitionOn,
Active,
TransitionOff,
Hidden,
}
/// <summary>
/// A screen is a single layer that has update and draw logic, and which
/// can be combined with other layers to build up a complex menu system.
/// For instance the main menu, the options menu, the "are you sure you
/// want to quit" message box, and the main game itself are all implemented
/// as screens.
/// </summary>
public abstract class GameScreen
{
#region Properties
/// <summary>
/// Normally when one screen is brought up over the top of another,
/// the first screen will transition off to make room for the new
/// one. This property indicates whether the screen is only a small
/// popup, in which case screens underneath it do not need to bother
/// transitioning off.
/// </summary>
public bool IsPopup
{
get { return isPopup; }
protected set { isPopup = value; }
}
bool isPopup;
/// <summary>
/// Indicates how long the screen takes to
/// transition on when it is activated.
/// </summary>
public TimeSpan TransitionOnTime
{
get { return transitionOnTime; }
protected set { transitionOnTime = value; }
}
TimeSpan transitionOnTime = TimeSpan.Zero;
/// <summary>
/// Indicates how long the screen takes to
/// transition off when it is deactivated.
/// </summary>
public TimeSpan TransitionOffTime
{
get { return transitionOffTime; }
protected set { transitionOffTime = value; }
}
TimeSpan transitionOffTime = TimeSpan.Zero;
/// <summary>
/// Gets the current position of the screen transition, ranging
/// from zero (fully active, no transition) to one (transitioned
/// fully off to nothing).
/// </summary>
public float TransitionPosition
{
get { return transitionPosition; }
protected set { transitionPosition = value; }
}
float transitionPosition = 1;
/// <summary>
/// Gets the current alpha of the screen transition, ranging
/// from 255 (fully active, no transition) to 0 (transitioned
/// fully off to nothing).
/// </summary>
public byte TransitionAlpha
{
get { return (byte)(255 - TransitionPosition * 255); }
}
/// <summary>
/// Gets the current screen transition state.
/// </summary>
public ScreenState ScreenState
{
get { return screenState; }
protected set { screenState = value; }
}
ScreenState screenState = ScreenState.TransitionOn;
/// <summary>
/// There are two possible reasons why a screen might be transitioning
/// off. It could be temporarily going away to make room for another
/// screen that is on top of it, or it could be going away for good.
/// This property indicates whether the screen is exiting for real:
/// if set, the screen will automatically remove itself as soon as the
/// transition finishes.
/// </summary>
public bool IsExiting
{
get { return isExiting; }
protected internal set { isExiting = value; }
}
bool isExiting;
/// <summary>
/// Checks whether this screen is active and can respond to user input.
/// </summary>
public bool IsActive
{
get
{
return !otherScreenHasFocus &&
(screenState == ScreenState.TransitionOn ||
screenState == ScreenState.Active);
}
}
bool otherScreenHasFocus;
/// <summary>
/// Gets the manager that this screen belongs to.
/// </summary>
public ZuneScreenManager ScreenManager
{
get { return screenManager; }
internal set { screenManager = value; }
}
ZuneScreenManager screenManager;
#endregion
#region Initialization
/// <summary>
/// Load graphics content for the screen.
/// </summary>
public virtual void LoadContent() { }
/// <summary>
/// Unload content for the screen.
/// </summary>
public virtual void UnloadContent() { }
#endregion
#region Update and Draw
/// <summary>
/// Allows the screen to run logic, such as updating the transition position.
/// Unlike HandleInput, this method is called regardless of whether the screen
/// is active, hidden, or in the middle of a transition.
/// </summary>
public virtual void Update(GameTime gameTime, bool otherScreenHasFocus,
bool coveredByOtherScreen)
{
this.otherScreenHasFocus = otherScreenHasFocus;
if (isExiting)
{
// If the screen is going away to kill, it should transition off.
screenState = ScreenState.TransitionOff;
if (!UpdateTransition(gameTime, transitionOffTime, 1))
{
// When the transition finishes, remove the screen.
ScreenManager.RemoveScreen(this);
}
}
else if (coveredByOtherScreen)
{
// If the screen is covered by another, it should transition off.
if (UpdateTransition(gameTime, transitionOffTime, 1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOff;
}
else
{
// Transition finished!
screenState = ScreenState.Hidden;
}
}
else
{
// Otherwise the screen should transition on and become active.
if (UpdateTransition(gameTime, transitionOnTime, -1))
{
// Still busy transitioning.
screenState = ScreenState.TransitionOn;
}
else
{
// Transition finished!
screenState = ScreenState.Active;
}
}
}
/// <summary>
/// Helper for updating the screen transition position.
/// </summary>
bool UpdateTransition(GameTime gameTime, TimeSpan time, int direction)
{
// How much should we move by?
float transitionDelta;
if (time == TimeSpan.Zero)
transitionDelta = 1;
else
transitionDelta = (float)(gameTime.ElapsedGameTime.TotalMilliseconds /
time.TotalMilliseconds);
// Update the transition position.
transitionPosition += transitionDelta * direction;
// Did we reach the end of the transition?
if ((transitionPosition <= 0) || (transitionPosition >= 1))
{
transitionPosition = MathHelper.Clamp(transitionPosition, 0, 1);
return false;
}
// Otherwise we are still busy transitioning.
return true;
}
/// <summary>
/// Allows the screen to handle user input. Unlike Update, this method
/// is only called when the screen is active, and not when some other
/// screen has taken the focus.
/// </summary>
public virtual void HandleInput(InputState input) { }
/// <summary>
/// This is called when the screen should draw itself.
/// </summary>
public virtual void Draw(GameTime gameTime) { }
#endregion
#region Public Methods
/// <summary>
/// Tells the screen to go away. Unlike ScreenManager.RemoveScreen, which
/// instantly kills the screen, this method respects the transition timings
/// and will give the screen a chance to gradually transition off.
/// </summary>
public virtual void ExitScreen()
{
if (TransitionOffTime == TimeSpan.Zero)
{
// If the screen has a zero transition time, remove it immediately.
ScreenManager.RemoveScreen(this);
}
else
{
// Otherwise flag that it should transition off and then exit.
isExiting = true;
}
}
#endregion
}
}
| |
/***************************************************************************
*
* CurlS#arp
*
* Copyright (c) 2013-2017 Dr. Masroor Ehsan (masroore@gmail.com)
* Portions copyright (c) 2004, 2005 Jeff Phillips (jeff@jeffp.net)
*
* This software is licensed as described in the file LICENSE, which you
* should have received as part of this distribution.
*
* You may opt to use, copy, modify, merge, publish, distribute and/or sell
* copies of this Software, and permit persons to whom the Software is
* furnished to do so, under the terms of the LICENSE file.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
* ANY KIND, either express or implied.
*
**************************************************************************/
using System;
using System.Runtime.InteropServices;
namespace CurlSharp
{
/// <summary>
/// This trivial class wraps the internal <c>curl_forms</c> struct.
/// </summary>
public sealed class CurlForms
{
/// <summary>The <see cref="CurlFormOption" />.</summary>
public CurlFormOption Option;
/// <summary>Value for the option.</summary>
public object Value;
}
/// <summary>
/// Wraps a section of multipart form data to be submitted via the
/// <see cref="CurlOption.HttpPost" /> option in the
/// <see cref="CurlEasy.SetOpt" /> member of the <see cref="CurlEasy" /> class.
/// </summary>
public class CurlHttpMultiPartForm : IDisposable
{
// the two curlform pointers
private readonly IntPtr[] _pItems;
/// <summary>
/// Constructor
/// </summary>
/// <exception cref="System.InvalidOperationException">
/// This is thrown
/// if <see cref="Curl" /> hasn't bee properly initialized.
/// </exception>
public CurlHttpMultiPartForm()
{
Curl.EnsureCurl();
_pItems = new IntPtr[2];
_pItems[0] = IntPtr.Zero;
_pItems[1] = IntPtr.Zero;
}
/// <summary>
/// Free unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Destructor
/// </summary>
~CurlHttpMultiPartForm()
{
Dispose(false);
}
// for CurlEasy.SetOpt()
internal IntPtr GetHandle() => _pItems[0];
/// <summary>
/// Add a multi-part form section.
/// </summary>
/// <param name="args">
/// Argument list, as described in the remarks.
/// </param>
/// <returns>
/// A <see cref="CurlFormCode" />, hopefully
/// <c>CurlFormCode.Ok</c>.
/// </returns>
/// <remarks>
/// This is definitely the workhorse method for this class. It
/// should be called in roughly the same manner as
/// <c>curl_formadd()</c>, except you would omit the first two
/// <c>struct curl_httppost**</c> arguments (<c>firstitem</c> and
/// <c>lastitem</c>), which are wrapped in this class. So you should
/// pass arguments in the following sequence:
/// <para>
/// <c>
/// CurlHttpMultiPartForm.AddSection(option1, value1, ..., optionX, valueX,
/// CurlFormOption.End)
/// </c>
/// ;
/// </para>
/// <para>
/// For a complete list of possible options, see the documentation for
/// the <see cref="CurlFormOption" /> enumeration.
/// </para>
/// <note>
/// The pointer options (<c>PtrName</c>, etc.) make an
/// internal copy of the passed <c>byte</c> array. Therefore, any
/// changes you make to the client copy of this array AFTER calling
/// this method, won't be reflected internally with <c>cURL</c>. The
/// purpose of providing the pointer options is to support the
/// posting of non-string binary data.
/// </note>
/// </remarks>
public CurlFormCode AddSection(params object[] args)
{
var nCount = args.Length;
var nRealCount = nCount;
var retCode = CurlFormCode.Ok;
CurlForms[] aForms = null;
// one arg or even number of args is an error
if ((nCount == 1) || (nCount%2 == 0))
return CurlFormCode.Incomplete;
// ensure the last argument is End
var iCode = (CurlFormOption)
Convert.ToInt32(args.GetValue(nCount - 1));
if (iCode != CurlFormOption.End)
return CurlFormCode.Incomplete;
// walk through any passed arrays to get the true number of
// items and ensure the child arrays are properly (and not
// prematurely) terminated with End
for (var i = 0; i < nCount; i += 2)
{
iCode = (CurlFormOption) Convert.ToInt32(args.GetValue(i));
switch (iCode)
{
case CurlFormOption.Array:
{
aForms = args.GetValue(i + 1) as CurlForms[];
if (aForms == null)
return CurlFormCode.Incomplete;
var nFormsCount = aForms.Length;
for (var j = 0; j < nFormsCount; j++)
{
var pcf = aForms.GetValue(j) as CurlForms;
if (pcf == null)
return CurlFormCode.Incomplete;
if (j == nFormsCount - 1)
{
if (pcf.Option != CurlFormOption.End)
return CurlFormCode.Incomplete;
}
else
{
if (pcf.Option == CurlFormOption.End)
return CurlFormCode.Incomplete;
}
}
// -2 accounts for the fact that we're a) not
// including the item with End and b) not
// including Array in what we pass to cURL
nRealCount += 2*(nFormsCount - 2);
break;
}
}
}
// allocate the IntPtr array for the data
var aPointers = new IntPtr[nRealCount];
for (var i = 0; i < nRealCount - 1; i++)
aPointers[i] = IntPtr.Zero;
aPointers[nRealCount - 1] = (IntPtr) CurlFormOption.End;
// now we go through the args
aForms = null;
var formArrayPos = 0;
var argArrayPos = 0;
var ptrArrayPos = 0;
object obj = null;
while ((retCode == CurlFormCode.Ok) &&
(ptrArrayPos < nRealCount))
{
if (aForms != null)
{
var pcf = aForms.GetValue(formArrayPos++)
as CurlForms;
if (pcf == null)
{
retCode = CurlFormCode.UnknownOption;
break;
}
iCode = pcf.Option;
obj = pcf.Value;
}
else
{
iCode = (CurlFormOption) Convert.ToInt32(
args.GetValue(argArrayPos++));
obj = iCode == CurlFormOption.End
? null
: args.GetValue(argArrayPos++);
}
switch (iCode)
{
// handle byte-array pointer-related items
case CurlFormOption.PtrName:
case CurlFormOption.PtrContents:
case CurlFormOption.BufferPtr:
{
var bytes = obj as byte[];
if (bytes == null)
retCode = CurlFormCode.UnknownOption;
else
{
var nLen = bytes.Length;
var ptr = Marshal.AllocHGlobal(nLen);
if (ptr != IntPtr.Zero)
{
aPointers[ptrArrayPos++] = (IntPtr) iCode;
// copy bytes to unmanaged buffer
for (var j = 0; j < nLen; j++)
Marshal.WriteByte(ptr, bytes[j]);
aPointers[ptrArrayPos++] = ptr;
}
else
retCode = CurlFormCode.Memory;
}
break;
}
// length values
case CurlFormOption.NameLength:
case CurlFormOption.ContentsLength:
case CurlFormOption.BufferLength:
aPointers[ptrArrayPos++] = (IntPtr) iCode;
aPointers[ptrArrayPos++] = (IntPtr)
Convert.ToInt32(obj);
break;
// strings
case CurlFormOption.CopyName:
case CurlFormOption.CopyContents:
case CurlFormOption.FileContent:
case CurlFormOption.File:
case CurlFormOption.ContentType:
case CurlFormOption.Filename:
case CurlFormOption.Buffer:
{
aPointers[ptrArrayPos++] = (IntPtr) iCode;
var s = obj as string;
if (s == null)
retCode = CurlFormCode.UnknownOption;
else
{
var p = Marshal.StringToHGlobalAnsi(s);
if (p != IntPtr.Zero)
aPointers[ptrArrayPos++] = p;
else
retCode = CurlFormCode.Memory;
}
break;
}
// array case: already handled
case CurlFormOption.Array:
if (aForms != null)
retCode = CurlFormCode.IllegalArray;
else
{
aForms = obj as CurlForms[];
if (aForms == null)
retCode = CurlFormCode.UnknownOption;
}
break;
// slist
case CurlFormOption.ContentHeader:
{
aPointers[ptrArrayPos++] = (IntPtr) iCode;
var s = obj as CurlSlist;
if (s == null)
retCode = CurlFormCode.UnknownOption;
else
aPointers[ptrArrayPos++] = s.Handle;
break;
}
// erroneous stuff
case CurlFormOption.Nothing:
retCode = CurlFormCode.Incomplete;
break;
// end
case CurlFormOption.End:
if (aForms != null) // end of form
{
aForms = null;
formArrayPos = 0;
}
else
aPointers[ptrArrayPos++] = (IntPtr) iCode;
break;
// default is unknown
default:
retCode = CurlFormCode.UnknownOption;
break;
}
}
// ensure we didn't come up short on parameters
if (ptrArrayPos != nRealCount)
retCode = CurlFormCode.Incomplete;
// if we're OK here, call into curl
if (retCode == CurlFormCode.Ok)
{
#if USE_LIBCURLSHIM
retCode = (CurlFormCode) NativeMethods.curl_shim_formadd(_pItems, aPointers, nRealCount);
#else
retCode = (CurlFormCode) NativeMethods.curl_formadd(ref _pItems[0], ref _pItems[1],
(int) aPointers[0], aPointers[1],
(int) aPointers[2], aPointers[3],
(int) aPointers[4]);
#endif
}
// unmarshal native allocations
for (var i = 0; i < nRealCount - 1; i += 2)
{
iCode = (CurlFormOption) (int) aPointers[i];
switch (iCode)
{
case CurlFormOption.CopyName:
case CurlFormOption.CopyContents:
case CurlFormOption.FileContent:
case CurlFormOption.File:
case CurlFormOption.ContentType:
case CurlFormOption.Filename:
case CurlFormOption.Buffer:
// byte buffer cases
case CurlFormOption.PtrName:
case CurlFormOption.PtrContents:
case CurlFormOption.BufferPtr:
{
if (aPointers[i + 1] != IntPtr.Zero)
Marshal.FreeHGlobal(aPointers[i + 1]);
break;
}
default:
break;
}
}
return retCode;
}
private void Dispose(bool disposing)
{
lock (this)
{
if (disposing)
{
// clean up managed objects
}
// clean up native objects
if (_pItems[0] != IntPtr.Zero)
NativeMethods.curl_formfree(_pItems[0]);
_pItems[0] = IntPtr.Zero;
_pItems[1] = IntPtr.Zero;
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Windows.Media;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
internal class PickMembersDialogViewModel : AbstractNotifyPropertyChanged
{
public List<MemberSymbolViewModel> MemberContainers { get; set; }
public List<OptionViewModel> Options { get; set; }
internal PickMembersDialogViewModel(
IGlyphService glyphService,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options)
{
MemberContainers = members.Select(m => new MemberSymbolViewModel(m, glyphService)).ToList();
Options = options.Select(o => new OptionViewModel(o)).ToList();
}
internal void DeselectAll()
{
foreach (var memberContainer in MemberContainers)
{
memberContainer.IsChecked = false;
}
}
internal void SelectAll()
{
foreach (var memberContainer in MemberContainers)
{
memberContainer.IsChecked = true;
}
}
private int? _selectedIndex;
public int? SelectedIndex
{
get
{
return _selectedIndex;
}
set
{
var newSelectedIndex = value == -1 ? null : value;
if (newSelectedIndex == _selectedIndex)
{
return;
}
_selectedIndex = newSelectedIndex;
NotifyPropertyChanged(nameof(CanMoveUp));
NotifyPropertyChanged(nameof(MoveUpAutomationText));
NotifyPropertyChanged(nameof(CanMoveDown));
NotifyPropertyChanged(nameof(MoveDownAutomationText));
}
}
public string MoveUpAutomationText
{
get
{
if (!CanMoveUp)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_above_1, MemberContainers[SelectedIndex.Value].MemberAutomationText, MemberContainers[SelectedIndex.Value - 1].MemberAutomationText);
}
}
public string MoveDownAutomationText
{
get
{
if (!CanMoveDown)
{
return string.Empty;
}
return string.Format(ServicesVSResources.Move_0_below_1, MemberContainers[SelectedIndex.Value].MemberAutomationText, MemberContainers[SelectedIndex.Value + 1].MemberAutomationText);
}
}
public bool CanMoveUp
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index > 0;
}
}
public bool CanMoveDown
{
get
{
if (!SelectedIndex.HasValue)
{
return false;
}
var index = SelectedIndex.Value;
return index < MemberContainers.Count - 1;
}
}
internal void MoveUp()
{
Debug.Assert(CanMoveUp);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: -1);
}
internal void MoveDown()
{
Debug.Assert(CanMoveDown);
var index = SelectedIndex.Value;
Move(MemberContainers, index, delta: 1);
}
private void Move(List<MemberSymbolViewModel> list, int index, int delta)
{
var param = list[index];
list.RemoveAt(index);
list.Insert(index + delta, param);
SelectedIndex += delta;
}
internal class MemberSymbolViewModel : AbstractNotifyPropertyChanged
{
private readonly IGlyphService _glyphService;
public ISymbol MemberSymbol { get; }
private static SymbolDisplayFormat s_memberDisplayFormat = new SymbolDisplayFormat(
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
memberOptions: SymbolDisplayMemberOptions.IncludeParameters,
parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeOptionalBrackets,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
public MemberSymbolViewModel(ISymbol symbol, IGlyphService glyphService)
{
MemberSymbol = symbol;
_glyphService = glyphService;
_isChecked = true;
}
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set { SetProperty(ref _isChecked, value); }
}
public string MemberName => MemberSymbol.ToDisplayString(s_memberDisplayFormat);
public ImageSource Glyph => MemberSymbol.GetGlyph().GetImageSource(_glyphService);
public string MemberAutomationText => MemberSymbol.Kind + " " + MemberName;
}
internal class OptionViewModel : AbstractNotifyPropertyChanged
{
public PickMembersOption Option { get; }
public string Title { get; }
public OptionViewModel(PickMembersOption option)
{
Option = option;
Title = option.Title;
IsChecked = option.Value;
}
private bool _isChecked;
public bool IsChecked
{
get => _isChecked;
set
{
Option.Value = value;
SetProperty(ref _isChecked, value);
}
}
public string MemberAutomationText => Option.Title;
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="Encoder.cs" company="Dropbox Inc">
// Copyright (c) Dropbox Inc. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace Dropbox.Api.Stone
{
using System;
using System.Collections.Generic;
/// <summary>
/// The factory class for encoders.
/// </summary>
internal static class Encoder
{
/// <summary>
/// Create a list encoder instance.
/// </summary>
/// <typeparam name="T">The list item type.</typeparam>
/// <param name="itemEncoder">The item encoder.</param>
/// <returns>The list encoder.</returns>
public static IEncoder<IList<T>> CreateListEncoder<T>(IEncoder<T> itemEncoder)
{
return new ListEncoder<T>(itemEncoder);
}
}
/// <summary>
/// Encoder for nullable struct.
/// </summary>
/// <typeparam name="T">Type of the struct.</typeparam>
internal sealed class NullableEncoder<T> : IEncoder<T?> where T : struct
{
/// <summary>
/// The encoder.
/// </summary>
private readonly IEncoder<T> encoder;
/// <summary>
/// Initializes a new instance of the <see cref="NullableEncoder{T}"/> class.
/// </summary>
/// <param name="encoder">The encoder.</param>
public NullableEncoder(IEncoder<T> encoder)
{
this.encoder = encoder;
}
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(T? value, IJsonWriter writer)
{
if (value == null)
{
writer.WriteNull();
return;
}
this.encoder.Encode(value.Value, writer);
}
}
/// <summary>
/// Encoder for Int32.
/// </summary>
internal sealed class Int32Encoder : IEncoder<int>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<int> Instance = new Int32Encoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<int?> NullableInstance = new NullableEncoder<int>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(int value, IJsonWriter writer)
{
writer.WriteInt32(value);
}
}
/// <summary>
/// Encoder for Int64.
/// </summary>
internal sealed class Int64Encoder : IEncoder<long>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<long> Instance = new Int64Encoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<long?> NullableInstance = new NullableEncoder<long>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(long value, IJsonWriter writer)
{
writer.WriteInt64(value);
}
}
/// <summary>
/// Encoder for UInt32.
/// </summary>
internal sealed class UInt32Encoder : IEncoder<uint>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<uint> Instance = new UInt32Encoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<uint?> NullableInstance = new NullableEncoder<uint>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(uint value, IJsonWriter writer)
{
writer.WriteUInt32(value);
}
}
/// <summary>
/// Encoder for UInt64.
/// </summary>
internal sealed class UInt64Encoder : IEncoder<ulong>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<ulong> Instance = new UInt64Encoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<ulong?> NullableInstance = new NullableEncoder<ulong>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(ulong value, IJsonWriter writer)
{
writer.WriteUInt64(value);
}
}
/// <summary>
/// Encoder for Float.
/// </summary>
internal sealed class SingleEncoder : IEncoder<float>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<float> Instance = new SingleEncoder();
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(float value, IJsonWriter writer)
{
writer.WriteSingle(value);
}
}
/// <summary>
/// Encoder for double.
/// </summary>
internal sealed class DoubleEncoder : IEncoder<double>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<double> Instance = new DoubleEncoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<double?> NullableInstance = new NullableEncoder<double>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(double value, IJsonWriter writer)
{
writer.WriteDouble(value);
}
}
/// <summary>
/// Encoder for boolean.
/// </summary>
internal sealed class BooleanEncoder : IEncoder<bool>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<bool> Instance = new BooleanEncoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<bool?> NullableInstance = new NullableEncoder<bool>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(bool value, IJsonWriter writer)
{
writer.WriteBoolean(value);
}
}
/// <summary>
/// Encoder for DateTime.
/// </summary>
internal sealed class DateTimeEncoder : IEncoder<DateTime>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<DateTime> Instance = new DateTimeEncoder();
/// <summary>
/// The nullable instance.
/// </summary>
public static readonly IEncoder<DateTime?> NullableInstance = new NullableEncoder<DateTime>(Instance);
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(DateTime value, IJsonWriter writer)
{
writer.WriteDateTime(value);
}
}
/// <summary>
/// Encoder for bytes.
/// </summary>
internal sealed class BytesEncoder : IEncoder<byte[]>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<byte[]> Instance = new BytesEncoder();
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(byte[] value, IJsonWriter writer)
{
writer.WriteBytes(value);
}
}
/// <summary>
/// Encoder for string.
/// </summary>
internal sealed class StringEncoder : IEncoder<string>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<string> Instance = new StringEncoder();
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(string value, IJsonWriter writer)
{
writer.WriteString(value);
}
}
/// <summary>
/// Encoder for empty.
/// </summary>
internal sealed class EmptyEncoder : IEncoder<Empty>
{
/// <summary>
/// The instance.
/// </summary>
public static readonly IEncoder<Empty> Instance = new EmptyEncoder();
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(Empty value, IJsonWriter writer)
{
}
}
/// <summary>
/// Encoder for struct type.
/// </summary>
/// <typeparam name="T">The type.</typeparam>
internal abstract class StructEncoder<T> : IEncoder<T> where T : class
{
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(T value, IJsonWriter writer)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.WriteStartObject();
this.EncodeFields(value, writer);
writer.WriteEndObject();
}
/// <summary>
/// Encode fields of given value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public abstract void EncodeFields(T value, IJsonWriter writer);
/// <summary>
/// Write property of specific type with given encoder.
/// </summary>
/// <typeparam name="TProperty">The property.</typeparam>
/// <param name="propertyName">The property name.</param>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
/// <param name="encoder">The encoder.</param>
protected static void WriteProperty<TProperty>(string propertyName, TProperty value, IJsonWriter writer, IEncoder<TProperty> encoder)
{
writer.WritePropertyName(propertyName);
encoder.Encode(value, writer);
}
/// <summary>
/// Write property of list of specific type with given encoder.
/// </summary>
/// <typeparam name="TProperty">The property.</typeparam>
/// <param name="propertyName">The property name.</param>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
/// <param name="encoder">The encoder.</param>
protected static void WriteListProperty<TProperty>(string propertyName, IList<TProperty> value, IJsonWriter writer, IEncoder<TProperty> encoder)
{
writer.WritePropertyName(propertyName);
ListEncoder<TProperty>.Encode(value, writer, encoder);
}
}
/// <summary>
/// Encoder for list type.
/// </summary>
/// <typeparam name="T">The list item type.</typeparam>
internal sealed class ListEncoder<T> : IEncoder<IList<T>>
{
/// <summary>
/// The item encoder.
/// </summary>
private readonly IEncoder<T> itemEncoder;
/// <summary>
/// Initializes a new instance of the <see cref="ListEncoder{T}"/> class.
/// </summary>
/// <param name="itemEncoder">The item encoder.</param>
public ListEncoder(IEncoder<T> itemEncoder)
{
this.itemEncoder = itemEncoder;
}
/// <summary>
/// Encode given list of specific value with given item encoder.
/// </summary>
/// <param name="value">The list.</param>
/// <param name="writer">The writer.</param>
/// <param name="itemEncoder">The item encoder.</param>
public static void Encode(IList<T> value, IJsonWriter writer, IEncoder<T> itemEncoder)
{
writer.WriteStartArray();
foreach (var item in value)
{
itemEncoder.Encode(item, writer);
}
writer.WriteEndArray();
}
/// <summary>
/// The encode.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="writer">The writer.</param>
public void Encode(IList<T> value, IJsonWriter writer)
{
Encode(value, writer, this.itemEncoder);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.ServiceModel;
abstract class LayeredChannelListener<TChannel>
: ChannelListenerBase<TChannel>
where TChannel : class, IChannel
{
IChannelListener innerChannelListener;
bool sharedInnerListener;
EventHandler onInnerListenerFaulted;
protected LayeredChannelListener(IDefaultCommunicationTimeouts timeouts, IChannelListener innerChannelListener)
: this(false, timeouts, innerChannelListener)
{
}
protected LayeredChannelListener(bool sharedInnerListener)
: this(sharedInnerListener, null, null)
{
}
protected LayeredChannelListener(bool sharedInnerListener, IDefaultCommunicationTimeouts timeouts)
: this(sharedInnerListener, timeouts, null)
{
}
protected LayeredChannelListener(bool sharedInnerListener, IDefaultCommunicationTimeouts timeouts, IChannelListener innerChannelListener)
: base(timeouts)
{
this.sharedInnerListener = sharedInnerListener;
this.innerChannelListener = innerChannelListener;
this.onInnerListenerFaulted = new EventHandler(OnInnerListenerFaulted);
if (this.innerChannelListener != null)
{
this.innerChannelListener.Faulted += onInnerListenerFaulted;
}
}
internal virtual IChannelListener InnerChannelListener
{
get
{
return innerChannelListener;
}
set
{
lock (ThisLock)
{
ThrowIfDisposedOrImmutable();
if (this.innerChannelListener != null)
{
this.innerChannelListener.Faulted -= onInnerListenerFaulted;
}
this.innerChannelListener = value;
if (this.innerChannelListener != null)
{
this.innerChannelListener.Faulted += onInnerListenerFaulted;
}
}
}
}
internal bool SharedInnerListener
{
get { return sharedInnerListener; }
}
public override Uri Uri
{
get { return GetInnerListenerSnapshot().Uri; }
}
public override T GetProperty<T>()
{
T baseProperty = base.GetProperty<T>();
if (baseProperty != null)
{
return baseProperty;
}
IChannelListener channelListener = this.InnerChannelListener;
if (channelListener != null)
{
return channelListener.GetProperty<T>();
}
else
{
return default(T);
}
}
protected override void OnAbort()
{
lock (ThisLock)
{
this.OnCloseOrAbort();
}
IChannelListener channelListener = this.InnerChannelListener;
if (channelListener != null && !sharedInnerListener)
{
channelListener.Abort();
}
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
this.OnCloseOrAbort();
return new CloseAsyncResult(InnerChannelListener, sharedInnerListener, timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
this.OnCloseOrAbort();
if (InnerChannelListener != null && !sharedInnerListener)
{
InnerChannelListener.Close(timeout);
}
}
void OnCloseOrAbort()
{
IChannelListener channelListener = this.InnerChannelListener;
if (channelListener != null)
{
channelListener.Faulted -= onInnerListenerFaulted;
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new OpenAsyncResult(InnerChannelListener, sharedInnerListener, timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OpenAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
if (InnerChannelListener != null && !sharedInnerListener)
InnerChannelListener.Open(timeout);
}
protected override void OnOpening()
{
base.OnOpening();
ThrowIfInnerListenerNotSet();
}
void OnInnerListenerFaulted(object sender, EventArgs e)
{
// if our inner listener faulted, we should fault as well
this.Fault();
}
internal void ThrowIfInnerListenerNotSet()
{
if (this.InnerChannelListener == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InnerListenerFactoryNotSet, this.GetType().ToString())));
}
}
internal IChannelListener GetInnerListenerSnapshot()
{
IChannelListener innerChannelListener = this.InnerChannelListener;
if (innerChannelListener == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.InnerListenerFactoryNotSet, this.GetType().ToString())));
}
return innerChannelListener;
}
class OpenAsyncResult : AsyncResult
{
ICommunicationObject communicationObject;
static AsyncCallback onOpenComplete = Fx.ThunkCallback(new AsyncCallback(OnOpenComplete));
public OpenAsyncResult(ICommunicationObject communicationObject, bool sharedInnerListener, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.communicationObject = communicationObject;
if (this.communicationObject == null || sharedInnerListener)
{
this.Complete(true);
return;
}
IAsyncResult result = this.communicationObject.BeginOpen(timeout, onOpenComplete, this);
if (result.CompletedSynchronously)
{
this.communicationObject.EndOpen(result);
this.Complete(true);
}
}
static void OnOpenComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
OpenAsyncResult thisPtr = (OpenAsyncResult)result.AsyncState;
Exception exception = null;
try
{
thisPtr.communicationObject.EndOpen(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
exception = e;
}
thisPtr.Complete(false, exception);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<OpenAsyncResult>(result);
}
}
class CloseAsyncResult : AsyncResult
{
ICommunicationObject communicationObject;
static AsyncCallback onCloseComplete = Fx.ThunkCallback(new AsyncCallback(OnCloseComplete));
public CloseAsyncResult(ICommunicationObject communicationObject, bool sharedInnerListener, TimeSpan timeout, AsyncCallback callback, object state)
: base(callback, state)
{
this.communicationObject = communicationObject;
if (this.communicationObject == null || sharedInnerListener)
{
this.Complete(true);
return;
}
IAsyncResult result = this.communicationObject.BeginClose(timeout, onCloseComplete, this);
if (result.CompletedSynchronously)
{
this.communicationObject.EndClose(result);
this.Complete(true);
}
}
static void OnCloseComplete(IAsyncResult result)
{
if (result.CompletedSynchronously)
return;
CloseAsyncResult thisPtr = (CloseAsyncResult)result.AsyncState;
Exception exception = null;
try
{
thisPtr.communicationObject.EndClose(result);
}
#pragma warning suppress 56500 // covered by FxCOP
catch (Exception e)
{
if (Fx.IsFatal(e))
throw;
exception = e;
}
thisPtr.Complete(false, exception);
}
public static void End(IAsyncResult result)
{
AsyncResult.End<CloseAsyncResult>(result);
}
}
}
abstract class LayeredChannelAcceptor<TChannel, TInnerChannel> : ChannelAcceptor<TChannel>
where TChannel : class, IChannel
where TInnerChannel : class, IChannel
{
IChannelListener<TInnerChannel> innerListener;
protected LayeredChannelAcceptor(ChannelManagerBase channelManager, IChannelListener<TInnerChannel> innerListener)
: base(channelManager)
{
this.innerListener = innerListener;
}
protected abstract TChannel OnAcceptChannel(TInnerChannel innerChannel);
public override TChannel AcceptChannel(TimeSpan timeout)
{
TInnerChannel innerChannel = this.innerListener.AcceptChannel(timeout);
if (innerChannel == null)
return null;
else
return OnAcceptChannel(innerChannel);
}
public override IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerListener.BeginAcceptChannel(timeout, callback, state);
}
public override TChannel EndAcceptChannel(IAsyncResult result)
{
TInnerChannel innerChannel = this.innerListener.EndAcceptChannel(result);
if (innerChannel == null)
return null;
else
return OnAcceptChannel(innerChannel);
}
public override bool WaitForChannel(TimeSpan timeout)
{
return this.innerListener.WaitForChannel(timeout);
}
public override IAsyncResult BeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state)
{
return this.innerListener.BeginWaitForChannel(timeout, callback, state);
}
public override bool EndWaitForChannel(IAsyncResult result)
{
return this.innerListener.EndWaitForChannel(result);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.WebSecurityScanner.V1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedWebSecurityScannerClientSnippets
{
/// <summary>Snippet for CreateScanConfig</summary>
public void CreateScanConfigRequestObject()
{
// Snippet: CreateScanConfig(CreateScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "",
ScanConfig = new ScanConfig(),
};
// Make the request
ScanConfig response = webSecurityScannerClient.CreateScanConfig(request);
// End snippet
}
/// <summary>Snippet for CreateScanConfigAsync</summary>
public async Task CreateScanConfigRequestObjectAsync()
{
// Snippet: CreateScanConfigAsync(CreateScanConfigRequest, CallSettings)
// Additional: CreateScanConfigAsync(CreateScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
CreateScanConfigRequest request = new CreateScanConfigRequest
{
Parent = "",
ScanConfig = new ScanConfig(),
};
// Make the request
ScanConfig response = await webSecurityScannerClient.CreateScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteScanConfig</summary>
public void DeleteScanConfigRequestObject()
{
// Snippet: DeleteScanConfig(DeleteScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
DeleteScanConfigRequest request = new DeleteScanConfigRequest { Name = "", };
// Make the request
webSecurityScannerClient.DeleteScanConfig(request);
// End snippet
}
/// <summary>Snippet for DeleteScanConfigAsync</summary>
public async Task DeleteScanConfigRequestObjectAsync()
{
// Snippet: DeleteScanConfigAsync(DeleteScanConfigRequest, CallSettings)
// Additional: DeleteScanConfigAsync(DeleteScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
DeleteScanConfigRequest request = new DeleteScanConfigRequest { Name = "", };
// Make the request
await webSecurityScannerClient.DeleteScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for GetScanConfig</summary>
public void GetScanConfigRequestObject()
{
// Snippet: GetScanConfig(GetScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetScanConfigRequest request = new GetScanConfigRequest { Name = "", };
// Make the request
ScanConfig response = webSecurityScannerClient.GetScanConfig(request);
// End snippet
}
/// <summary>Snippet for GetScanConfigAsync</summary>
public async Task GetScanConfigRequestObjectAsync()
{
// Snippet: GetScanConfigAsync(GetScanConfigRequest, CallSettings)
// Additional: GetScanConfigAsync(GetScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetScanConfigRequest request = new GetScanConfigRequest { Name = "", };
// Make the request
ScanConfig response = await webSecurityScannerClient.GetScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for ListScanConfigs</summary>
public void ListScanConfigsRequestObject()
{
// Snippet: ListScanConfigs(ListScanConfigsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListScanConfigsRequest request = new ListScanConfigsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListScanConfigsResponse, ScanConfig> response = webSecurityScannerClient.ListScanConfigs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ScanConfig item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListScanConfigsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanConfig item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ScanConfig> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ScanConfig item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListScanConfigsAsync</summary>
public async Task ListScanConfigsRequestObjectAsync()
{
// Snippet: ListScanConfigsAsync(ListScanConfigsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListScanConfigsRequest request = new ListScanConfigsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListScanConfigsResponse, ScanConfig> response = webSecurityScannerClient.ListScanConfigsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ScanConfig item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListScanConfigsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanConfig item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ScanConfig> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ScanConfig item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateScanConfig</summary>
public void UpdateScanConfigRequestObject()
{
// Snippet: UpdateScanConfig(UpdateScanConfigRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
ScanConfig response = webSecurityScannerClient.UpdateScanConfig(request);
// End snippet
}
/// <summary>Snippet for UpdateScanConfigAsync</summary>
public async Task UpdateScanConfigRequestObjectAsync()
{
// Snippet: UpdateScanConfigAsync(UpdateScanConfigRequest, CallSettings)
// Additional: UpdateScanConfigAsync(UpdateScanConfigRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
UpdateScanConfigRequest request = new UpdateScanConfigRequest
{
ScanConfig = new ScanConfig(),
UpdateMask = new FieldMask(),
};
// Make the request
ScanConfig response = await webSecurityScannerClient.UpdateScanConfigAsync(request);
// End snippet
}
/// <summary>Snippet for StartScanRun</summary>
public void StartScanRunRequestObject()
{
// Snippet: StartScanRun(StartScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
StartScanRunRequest request = new StartScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.StartScanRun(request);
// End snippet
}
/// <summary>Snippet for StartScanRunAsync</summary>
public async Task StartScanRunRequestObjectAsync()
{
// Snippet: StartScanRunAsync(StartScanRunRequest, CallSettings)
// Additional: StartScanRunAsync(StartScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
StartScanRunRequest request = new StartScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.StartScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for GetScanRun</summary>
public void GetScanRunRequestObject()
{
// Snippet: GetScanRun(GetScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetScanRunRequest request = new GetScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.GetScanRun(request);
// End snippet
}
/// <summary>Snippet for GetScanRunAsync</summary>
public async Task GetScanRunRequestObjectAsync()
{
// Snippet: GetScanRunAsync(GetScanRunRequest, CallSettings)
// Additional: GetScanRunAsync(GetScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetScanRunRequest request = new GetScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.GetScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for ListScanRuns</summary>
public void ListScanRunsRequestObject()
{
// Snippet: ListScanRuns(ListScanRunsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListScanRunsRequest request = new ListScanRunsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListScanRunsResponse, ScanRun> response = webSecurityScannerClient.ListScanRuns(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ScanRun item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListScanRunsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanRun item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ScanRun> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ScanRun item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListScanRunsAsync</summary>
public async Task ListScanRunsRequestObjectAsync()
{
// Snippet: ListScanRunsAsync(ListScanRunsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListScanRunsRequest request = new ListScanRunsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListScanRunsResponse, ScanRun> response = webSecurityScannerClient.ListScanRunsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ScanRun item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListScanRunsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ScanRun item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ScanRun> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ScanRun item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for StopScanRun</summary>
public void StopScanRunRequestObject()
{
// Snippet: StopScanRun(StopScanRunRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
StopScanRunRequest request = new StopScanRunRequest { Name = "", };
// Make the request
ScanRun response = webSecurityScannerClient.StopScanRun(request);
// End snippet
}
/// <summary>Snippet for StopScanRunAsync</summary>
public async Task StopScanRunRequestObjectAsync()
{
// Snippet: StopScanRunAsync(StopScanRunRequest, CallSettings)
// Additional: StopScanRunAsync(StopScanRunRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
StopScanRunRequest request = new StopScanRunRequest { Name = "", };
// Make the request
ScanRun response = await webSecurityScannerClient.StopScanRunAsync(request);
// End snippet
}
/// <summary>Snippet for ListCrawledUrls</summary>
public void ListCrawledUrlsRequestObject()
{
// Snippet: ListCrawledUrls(ListCrawledUrlsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListCrawledUrlsRequest request = new ListCrawledUrlsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListCrawledUrlsResponse, CrawledUrl> response = webSecurityScannerClient.ListCrawledUrls(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (CrawledUrl item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCrawledUrlsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CrawledUrl item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CrawledUrl> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CrawledUrl item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCrawledUrlsAsync</summary>
public async Task ListCrawledUrlsRequestObjectAsync()
{
// Snippet: ListCrawledUrlsAsync(ListCrawledUrlsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListCrawledUrlsRequest request = new ListCrawledUrlsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListCrawledUrlsResponse, CrawledUrl> response = webSecurityScannerClient.ListCrawledUrlsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((CrawledUrl item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCrawledUrlsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (CrawledUrl item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<CrawledUrl> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (CrawledUrl item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetFinding</summary>
public void GetFindingRequestObject()
{
// Snippet: GetFinding(GetFindingRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
GetFindingRequest request = new GetFindingRequest { Name = "", };
// Make the request
Finding response = webSecurityScannerClient.GetFinding(request);
// End snippet
}
/// <summary>Snippet for GetFindingAsync</summary>
public async Task GetFindingRequestObjectAsync()
{
// Snippet: GetFindingAsync(GetFindingRequest, CallSettings)
// Additional: GetFindingAsync(GetFindingRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
GetFindingRequest request = new GetFindingRequest { Name = "", };
// Make the request
Finding response = await webSecurityScannerClient.GetFindingAsync(request);
// End snippet
}
/// <summary>Snippet for ListFindings</summary>
public void ListFindingsRequestObject()
{
// Snippet: ListFindings(ListFindingsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListFindingsRequest request = new ListFindingsRequest
{
Parent = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListFindingsResponse, Finding> response = webSecurityScannerClient.ListFindings(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Finding item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListFindingsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Finding item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Finding> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Finding item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFindingsAsync</summary>
public async Task ListFindingsRequestObjectAsync()
{
// Snippet: ListFindingsAsync(ListFindingsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListFindingsRequest request = new ListFindingsRequest
{
Parent = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListFindingsResponse, Finding> response = webSecurityScannerClient.ListFindingsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Finding item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListFindingsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Finding item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Finding> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Finding item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListFindingTypeStats</summary>
public void ListFindingTypeStatsRequestObject()
{
// Snippet: ListFindingTypeStats(ListFindingTypeStatsRequest, CallSettings)
// Create client
WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.Create();
// Initialize request argument(s)
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest { Parent = "", };
// Make the request
ListFindingTypeStatsResponse response = webSecurityScannerClient.ListFindingTypeStats(request);
// End snippet
}
/// <summary>Snippet for ListFindingTypeStatsAsync</summary>
public async Task ListFindingTypeStatsRequestObjectAsync()
{
// Snippet: ListFindingTypeStatsAsync(ListFindingTypeStatsRequest, CallSettings)
// Additional: ListFindingTypeStatsAsync(ListFindingTypeStatsRequest, CancellationToken)
// Create client
WebSecurityScannerClient webSecurityScannerClient = await WebSecurityScannerClient.CreateAsync();
// Initialize request argument(s)
ListFindingTypeStatsRequest request = new ListFindingTypeStatsRequest { Parent = "", };
// Make the request
ListFindingTypeStatsResponse response = await webSecurityScannerClient.ListFindingTypeStatsAsync(request);
// End snippet
}
}
}
| |
// 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.IO;
using System.IO.Compression;
using System.Net.Test.Common;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
public abstract class HttpClientHandler_Decompression_Test : HttpClientHandlerTestBase
{
private readonly ITestOutputHelper _output;
public static readonly object[][] CompressedServers = System.Net.Test.Common.Configuration.Http.CompressedServers;
public HttpClientHandler_Decompression_Test(ITestOutputHelper output)
{
_output = output;
}
public static IEnumerable<object[]> DecompressedResponse_MethodSpecified_DecompressedContentReturned_MemberData()
{
foreach (bool specifyAllMethods in new[] { false, true })
{
yield return new object[]
{
"deflate",
new Func<Stream, Stream>(s => new DeflateStream(s, CompressionLevel.Optimal, leaveOpen: true)),
specifyAllMethods ? DecompressionMethods.Deflate : DecompressionMethods.All
};
yield return new object[]
{
"gzip",
new Func<Stream, Stream>(s => new GZipStream(s, CompressionLevel.Optimal, leaveOpen: true)),
specifyAllMethods ? DecompressionMethods.GZip : DecompressionMethods.All
};
yield return new object[]
{
"br",
new Func<Stream, Stream>(s => new BrotliStream(s, CompressionLevel.Optimal, leaveOpen: true)),
specifyAllMethods ? DecompressionMethods.Brotli : DecompressionMethods.All
};
}
}
[Theory]
[MemberData(nameof(DecompressedResponse_MethodSpecified_DecompressedContentReturned_MemberData))]
public async Task DecompressedResponse_MethodSpecified_DecompressedContentReturned(
string encodingName, Func<Stream, Stream> compress, DecompressionMethods methods)
{
if (!UseSocketsHttpHandler && encodingName == "br")
{
// Brotli only supported on SocketsHttpHandler.
return;
}
var expectedContent = new byte[12345];
new Random(42).NextBytes(expectedContent);
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.AutomaticDecompression = methods;
Assert.Equal<byte>(expectedContent, await client.GetByteArrayAsync(uri));
}
}, async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAsync();
await connection.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nContent-Encoding: {encodingName}\r\n\r\n");
using (Stream compressedStream = compress(connection.Stream))
{
await compressedStream.WriteAsync(expectedContent);
}
});
});
}
public static IEnumerable<object[]> DecompressedResponse_MethodNotSpecified_OriginalContentReturned_MemberData()
{
yield return new object[]
{
"deflate",
new Func<Stream, Stream>(s => new DeflateStream(s, CompressionLevel.Optimal, leaveOpen: true)),
DecompressionMethods.None
};
yield return new object[]
{
"gzip",
new Func<Stream, Stream>(s => new GZipStream(s, CompressionLevel.Optimal, leaveOpen: true)),
DecompressionMethods.Brotli
};
yield return new object[]
{
"br",
new Func<Stream, Stream>(s => new BrotliStream(s, CompressionLevel.Optimal, leaveOpen: true)),
DecompressionMethods.Deflate | DecompressionMethods.GZip
};
}
[Theory]
[MemberData(nameof(DecompressedResponse_MethodNotSpecified_OriginalContentReturned_MemberData))]
public async Task DecompressedResponse_MethodNotSpecified_OriginalContentReturned(
string encodingName, Func<Stream, Stream> compress, DecompressionMethods methods)
{
if (IsCurlHandler && encodingName == "br")
{
// 'Content-Encoding' response header with Brotli causes error
// with some Linux distros of libcurl.
return;
}
var expectedContent = new byte[12345];
new Random(42).NextBytes(expectedContent);
var compressedContentStream = new MemoryStream();
using (Stream s = compress(compressedContentStream))
{
await s.WriteAsync(expectedContent);
}
byte[] compressedContent = compressedContentStream.ToArray();
await LoopbackServer.CreateClientAndServerAsync(async uri =>
{
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.AutomaticDecompression = methods;
Assert.Equal<byte>(compressedContent, await client.GetByteArrayAsync(uri));
}
}, async server =>
{
await server.AcceptConnectionAsync(async connection =>
{
await connection.ReadRequestHeaderAsync();
await connection.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nContent-Encoding: {encodingName}\r\n\r\n");
await connection.Stream.WriteAsync(compressedContent);
});
});
}
[OuterLoop("Uses external servers")]
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Uri server)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(server))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string responseContent = await response.Content.ReadAsStringAsync();
_output.WriteLine(responseContent);
TestHelper.VerifyResponseBody(
responseContent,
response.Content.Headers.ContentMD5,
false,
null);
}
}
}
[OuterLoop("Uses external server")]
[Theory, MemberData(nameof(CompressedServers))]
public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Uri server)
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var client = new HttpClient(handler))
using (HttpResponseMessage response = await client.GetAsync(server, HttpCompletionOption.ResponseHeadersRead))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found");
Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found");
}
}
[Theory]
#if netcoreapp
[InlineData(DecompressionMethods.Brotli, "br", "")]
[InlineData(DecompressionMethods.Brotli, "br", "br")]
[InlineData(DecompressionMethods.Brotli, "br", "gzip")]
[InlineData(DecompressionMethods.Brotli, "br", "gzip, deflate")]
#endif
[InlineData(DecompressionMethods.GZip, "gzip", "")]
[InlineData(DecompressionMethods.Deflate, "deflate", "")]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "")]
[InlineData(DecompressionMethods.GZip, "gzip", "gzip")]
[InlineData(DecompressionMethods.Deflate, "deflate", "deflate")]
[InlineData(DecompressionMethods.GZip, "gzip", "deflate")]
[InlineData(DecompressionMethods.GZip, "gzip", "br")]
[InlineData(DecompressionMethods.Deflate, "deflate", "gzip")]
[InlineData(DecompressionMethods.Deflate, "deflate", "br")]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "gzip, deflate")]
public async Task GetAsync_SetAutomaticDecompression_AcceptEncodingHeaderSentWithNoDuplicates(
DecompressionMethods methods,
string encodings,
string manualAcceptEncodingHeaderValues)
{
if (IsCurlHandler)
{
// Skip these tests on CurlHandler, dotnet/corefx #29905.
return;
}
if (!UseSocketsHttpHandler &&
(encodings.Contains("br") || manualAcceptEncodingHeaderValues.Contains("br")))
{
// Brotli encoding only supported on SocketsHttpHandler.
return;
}
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.AutomaticDecompression = methods;
using (var client = new HttpClient(handler))
{
if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues))
{
client.DefaultRequestHeaders.Add("Accept-Encoding", manualAcceptEncodingHeaderValues);
}
Task<HttpResponseMessage> clientTask = client.GetAsync(url);
Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync();
await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask });
List<string> requestLines = await serverTask;
string requestLinesString = string.Join("\r\n", requestLines);
_output.WriteLine(requestLinesString);
Assert.InRange(Regex.Matches(requestLinesString, "Accept-Encoding").Count, 1, 1);
Assert.InRange(Regex.Matches(requestLinesString, encodings).Count, 1, 1);
if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues))
{
Assert.InRange(Regex.Matches(requestLinesString, manualAcceptEncodingHeaderValues).Count, 1, 1);
}
using (HttpResponseMessage response = await clientTask)
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
});
}
}
}
| |
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Batch.FileStaging.Tests.IntegrationTestUtilities
{
using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Batch;
using Microsoft.Azure.Batch.Auth;
using Microsoft.Azure.Batch.Common;
using Microsoft.Azure.Batch.FileStaging;
public static class TestUtilities
{
#region Credentials helpers
public static BatchSharedKeyCredentials GetCredentialsFromEnvironment()
{
return new BatchSharedKeyCredentials(
TestCommon.Configuration.BatchAccountUrl,
TestCommon.Configuration.BatchAccountName,
TestCommon.Configuration.BatchAccountKey);
}
public static BatchClient OpenBatchClient(BatchSharedKeyCredentials sharedKeyCredentials, bool addDefaultRetryPolicy = true)
{
BatchClient client = BatchClient.Open(sharedKeyCredentials);
//Force us to get exception if the server returns something we don't expect
//TODO: To avoid including this test assembly via "InternalsVisibleTo" we resort to some reflection trickery... maybe this property
//TODO: should just be public?
//TODO: Disabled for now because the swagger spec does not accurately reflect all properties returned by the server
//SetDeserializationSettings(client);
//Set up some common stuff like a retry policy
if (addDefaultRetryPolicy)
{
client.CustomBehaviors.Add(RetryPolicyProvider.LinearRetryProvider(TimeSpan.FromSeconds(3), 5));
}
return client;
}
public static BatchClient OpenBatchClientFromEnvironment()
{
BatchClient client = OpenBatchClient(GetCredentialsFromEnvironment());
return client;
}
public static StagingStorageAccount GetStorageCredentialsFromEnvironment()
{
string storageAccountKey = TestCommon.Configuration.StorageAccountKey;
string storageAccountName = TestCommon.Configuration.StorageAccountName;
string storageAccountBlobEndpoint = TestCommon.Configuration.StorageAccountBlobEndpoint;
StagingStorageAccount storageStagingCredentials = new StagingStorageAccount(storageAccountName, storageAccountKey, storageAccountBlobEndpoint);
return storageStagingCredentials;
}
#endregion
#region Naming helpers
public static string GetMyName()
{
string domainName = Environment.GetEnvironmentVariable("USERNAME");
return domainName;
}
#endregion
#region Deletion helpers
public static async Task DeleteJobIfExistsAsync(BatchClient client, string jobId)
{
try
{
await client.JobOperations.DeleteJobAsync(jobId).ConfigureAwait(false);
}
catch (BatchException e)
{
if (!IsExceptionNotFound(e) && !IsExceptionConflict(e))
{
throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404
}
}
}
public static async Task DeleteJobScheduleIfExistsAsync(BatchClient client, string jobScheduleId)
{
try
{
await client.JobScheduleOperations.DeleteJobScheduleAsync(jobScheduleId).ConfigureAwait(false);
}
catch (BatchException e)
{
if (!IsExceptionNotFound(e) && !IsExceptionConflict(e))
{
throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404
}
}
}
public static async Task DeletePoolIfExistsAsync(BatchClient client, string poolId)
{
try
{
await client.PoolOperations.DeletePoolAsync(poolId).ConfigureAwait(false);
}
catch (BatchException e)
{
if (!IsExceptionNotFound(e) && !IsExceptionConflict(e))
{
throw; //re-throw in the case where we tried to delete the job and got an exception with a status code which wasn't 409 or 404
}
}
}
public static async Task DeleteCertificateIfExistsAsync(BatchClient client, string thumbprintAlgorithm, string thumbprint)
{
try
{
await client.CertificateOperations.DeleteCertificateAsync(thumbprintAlgorithm, thumbprint).ConfigureAwait(false);
}
catch (BatchException e)
{
if (!IsExceptionNotFound(e) && !IsExceptionConflict(e))
{
throw; //re-throw in the case where we tried to delete the cert and got an exception with a status code which wasn't 409 or 404
}
}
}
#endregion
#region Wait helpers
public static async Task WaitForPoolToReachStateAsync(BatchClient client, string poolId, AllocationState targetAllocationState, TimeSpan timeout)
{
CloudPool pool = await client.PoolOperations.GetPoolAsync(poolId);
await RefreshBasedPollingWithTimeoutAsync(
refreshing: pool,
condition: () => Task.FromResult(pool.AllocationState == targetAllocationState),
timeout: timeout).ConfigureAwait(false);
}
/// <summary>
/// Will throw if timeout is exceeded.
/// </summary>
/// <param name="refreshing"></param>
/// <param name="condition"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public static async Task RefreshBasedPollingWithTimeoutAsync(IRefreshable refreshing, Func<Task<bool>> condition, TimeSpan timeout)
{
DateTime allocationWaitStartTime = DateTime.UtcNow;
DateTime timeoutAfterThisTimeUtc = allocationWaitStartTime.Add(timeout);
while (!(await condition().ConfigureAwait(continueOnCapturedContext: false)))
{
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(continueOnCapturedContext: false);
await refreshing.RefreshAsync().ConfigureAwait(continueOnCapturedContext: false);
if (DateTime.UtcNow > timeoutAfterThisTimeUtc)
{
throw new Exception("RefreshBasedPollingWithTimeout: Timed out waiting for condition to be met.");
}
}
}
#endregion
#region Private helpers
private static bool IsExceptionNotFound(BatchException e)
{
return e.RequestInformation != null && e.RequestInformation.HttpStatusCode == HttpStatusCode.NotFound;
}
private static bool IsExceptionConflict(BatchException e)
{
return e.RequestInformation != null && e.RequestInformation.HttpStatusCode == HttpStatusCode.Conflict;
}
#endregion
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
namespace Orleans.Runtime.Configuration
{
/// <summary>
/// Individual node-specific silo configuration parameters.
/// </summary>
[Serializable]
public class NodeConfiguration : ITraceConfiguration, IStatisticsConfiguration
{
private readonly DateTime creationTimestamp;
private string siloName;
/// <summary>
/// The name of this silo.
/// </summary>
public string SiloName
{
get { return siloName; }
set
{
siloName = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// The DNS host name of this silo.
/// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName().
/// </summary>
public string DNSHostName { get; private set; }
/// <summary>
/// The host name or IP address of this silo.
/// This is a configurable IP address or Hostname.
/// </summary>
public string HostNameOrIPAddress { get; set; }
private IPAddress Address { get { return ClusterConfiguration.ResolveIPAddress(HostNameOrIPAddress, Subnet, AddressType); } }
/// <summary>
/// The port this silo uses for silo-to-silo communication.
/// </summary>
public int Port { get; set; }
/// <summary>
/// The epoch generation number for this silo.
/// </summary>
public int Generation { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for silo-to-silo communication.
/// </summary>
public IPEndPoint Endpoint
{
get { return new IPEndPoint(Address, Port); }
}
/// <summary>
/// The AddressFamilyof the IP address of this silo.
/// </summary>
public AddressFamily AddressType { get; set; }
/// <summary>
/// The IPEndPoint this silo uses for (gateway) silo-to-client communication.
/// </summary>
public IPEndPoint ProxyGatewayEndpoint { get; set; }
internal byte[] Subnet { get; set; } // from global
/// <summary>
/// Whether this is a primary silo (applies for dev settings only).
/// </summary>
public bool IsPrimaryNode { get; internal set; }
/// <summary>
/// Whether this is one of the seed silos (applies for dev settings only).
/// </summary>
public bool IsSeedNode { get; internal set; }
/// <summary>
/// Whether this is silo is a proxying gateway silo.
/// </summary>
public bool IsGatewayNode { get { return ProxyGatewayEndpoint != null; } }
/// <summary>
/// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow.
/// Generally this number should be roughly equal to the number of cores on the node.
/// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead.
/// </summary>
public int MaxActiveThreads { get; set; }
/// <summary>
/// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written.
/// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written.
/// The default value is 10 seconds.
/// </summary>
public TimeSpan DelayWarningThreshold { get; set; }
/// <summary>
/// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns).
/// If a activation was running its micro-turns longer than this, we will give up the thread.
/// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing).
/// </summary>
public TimeSpan ActivationSchedulingQuantum { get; set; }
/// <summary>
/// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU.
/// </summary>
public TimeSpan TurnWarningLengthThreshold { get; set; }
internal bool InjectMoreWorkerThreads { get; set; }
/// <summary>
/// The LoadShedding element specifies the gateway load shedding configuration for the node.
/// If it does not appear, gateway load shedding is disabled.
/// </summary>
public bool LoadSheddingEnabled { get; set; }
/// <summary>
/// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed.
/// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is
/// typically between 80 and 95.
/// This value is ignored if load shedding is disabled, which is the default.
/// If load shedding is enabled and this attribute does not appear, then the default limit is 95%.
/// </summary>
public int LoadSheddingLimit { get; set; }
/// <summary>
/// The values for various silo limits.
/// </summary>
public LimitManager LimitManager { get; private set; }
private string traceFilePattern;
/// <summary>
/// </summary>
public Logger.Severity DefaultTraceLevel { get; set; }
/// <summary>
/// </summary>
public IList<Tuple<string, Logger.Severity>> TraceLevelOverrides { get; private set; }
/// <summary>
/// </summary>
public bool WriteMessagingTraces { get; set; }
/// <summary>
/// </summary>
public bool TraceToConsole { get; set; }
/// <summary>
/// </summary>
public string TraceFilePattern
{
get { return traceFilePattern; }
set
{
traceFilePattern = value;
ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp);
}
}
/// <summary>
/// </summary>
public string TraceFileName { get; set; }
/// <summary>
/// </summary>
public int LargeMessageWarningThreshold { get; set; }
/// <summary>
/// </summary>
public bool PropagateActivityId { get; set; }
/// <summary>
/// </summary>
public int BulkMessageLimit { get; set; }
/// <summary>
/// Specifies the name of the Startup class in the configuration file.
/// </summary>
public string StartupTypeName { get; set; }
public string StatisticsProviderName { get; set; }
/// <summary>
/// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsMetricsTableWriteInterval { get; set; }
/// <summary>
/// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters.
/// The default is 30 seconds.
/// </summary>
public TimeSpan StatisticsPerfCountersWriteInterval { get; set; }
/// <summary>
/// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file.
/// The default is 5 minutes.
/// </summary>
public TimeSpan StatisticsLogWriteInterval { get; set; }
/// <summary>
/// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table.
/// The default is yes.
/// </summary>
public bool StatisticsWriteLogStatisticsToTable { get; set; }
/// <summary>
/// </summary>
public StatisticsLevel StatisticsCollectionLevel { get; set; }
private string workingStoreDir;
/// <summary>
/// </summary>
internal string WorkingStorageDirectory
{
get { return workingStoreDir ?? (workingStoreDir = GetDefaultWorkingStoreDirectory()); }
set { workingStoreDir = value; }
}
/// <summary>
/// </summary>
public int MinDotNetThreadPoolSize { get; set; }
/// <summary>
/// </summary>
public bool Expect100Continue { get; set; }
/// <summary>
/// </summary>
public int DefaultConnectionLimit { get; set; }
/// <summary>
/// </summary>
public bool UseNagleAlgorithm { get; set; }
public string SiloShutdownEventName { get; set; }
internal const string DEFAULT_NODE_NAME = "default";
private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30);
private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5);
internal static readonly StatisticsLevel DEFAULT_STATS_COLLECTION_LEVEL = StatisticsLevel.Info;
private static readonly int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, System.Environment.ProcessorCount);
internal static readonly int DEFAULT_MAX_LOCAL_ACTIVATIONS = System.Environment.ProcessorCount;
private const int DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE = 200;
private static readonly int DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
private static readonly TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100);
internal const bool INJECT_MORE_WORKER_THREADS = false;
public NodeConfiguration()
{
creationTimestamp = DateTime.UtcNow;
SiloName = "";
HostNameOrIPAddress = "";
DNSHostName = Dns.GetHostName();
Port = 0;
Generation = 0;
AddressType = AddressFamily.InterNetwork;
ProxyGatewayEndpoint = null;
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
DelayWarningThreshold = TimeSpan.FromMilliseconds(10000); // 10,000 milliseconds
ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM;
TurnWarningLengthThreshold = TimeSpan.FromMilliseconds(200);
InjectMoreWorkerThreads = INJECT_MORE_WORKER_THREADS;
LoadSheddingEnabled = false;
LoadSheddingLimit = 95;
DefaultTraceLevel = Logger.Severity.Info;
TraceLevelOverrides = new List<Tuple<string, Logger.Severity>>();
TraceToConsole = true;
TraceFilePattern = "{0}-{1}.log";
WriteMessagingTraces = false;
LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD;
PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID;
BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT;
StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD;
StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD;
StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD;
StatisticsWriteLogStatisticsToTable = true;
StatisticsCollectionLevel = DEFAULT_STATS_COLLECTION_LEVEL;
LimitManager = new LimitManager();
MinDotNetThreadPoolSize = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE;
// .NET ServicePointManager settings / optimizations
Expect100Continue = false;
DefaultConnectionLimit = DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT;
UseNagleAlgorithm = false;
}
public NodeConfiguration(NodeConfiguration other)
{
creationTimestamp = other.creationTimestamp;
SiloName = other.SiloName;
HostNameOrIPAddress = other.HostNameOrIPAddress;
DNSHostName = other.DNSHostName;
Port = other.Port;
Generation = other.Generation;
AddressType = other.AddressType;
ProxyGatewayEndpoint = other.ProxyGatewayEndpoint;
MaxActiveThreads = other.MaxActiveThreads;
DelayWarningThreshold = other.DelayWarningThreshold;
ActivationSchedulingQuantum = other.ActivationSchedulingQuantum;
TurnWarningLengthThreshold = other.TurnWarningLengthThreshold;
InjectMoreWorkerThreads = other.InjectMoreWorkerThreads;
LoadSheddingEnabled = other.LoadSheddingEnabled;
LoadSheddingLimit = other.LoadSheddingLimit;
DefaultTraceLevel = other.DefaultTraceLevel;
TraceLevelOverrides = new List<Tuple<string, Logger.Severity>>(other.TraceLevelOverrides);
TraceToConsole = other.TraceToConsole;
TraceFilePattern = other.TraceFilePattern;
TraceFileName = other.TraceFileName;
WriteMessagingTraces = other.WriteMessagingTraces;
LargeMessageWarningThreshold = other.LargeMessageWarningThreshold;
PropagateActivityId = other.PropagateActivityId;
BulkMessageLimit = other.BulkMessageLimit;
StatisticsProviderName = other.StatisticsProviderName;
StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval;
StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval;
StatisticsLogWriteInterval = other.StatisticsLogWriteInterval;
StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable;
StatisticsCollectionLevel = other.StatisticsCollectionLevel;
LimitManager = new LimitManager(other.LimitManager); // Shallow copy
Subnet = other.Subnet;
MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize;
Expect100Continue = other.Expect100Continue;
DefaultConnectionLimit = other.DefaultConnectionLimit;
UseNagleAlgorithm = other.UseNagleAlgorithm;
StartupTypeName = other.StartupTypeName;
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append(" Silo Name: ").AppendLine(SiloName);
sb.Append(" Generation: ").Append(Generation).AppendLine();
sb.Append(" Host Name or IP Address: ").AppendLine(HostNameOrIPAddress);
sb.Append(" DNS Host Name: ").AppendLine(DNSHostName);
sb.Append(" Port: ").Append(Port).AppendLine();
sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(), ".")).AppendLine();
sb.Append(" Preferred Address Family: ").Append(AddressType).AppendLine();
if (IsGatewayNode)
{
sb.Append(" Proxy Gateway: ").Append(ProxyGatewayEndpoint.ToString()).AppendLine();
}
else
{
sb.Append(" IsGatewayNode: ").Append(IsGatewayNode).AppendLine();
}
sb.Append(" IsPrimaryNode: ").Append(IsPrimaryNode).AppendLine();
sb.Append(" Scheduler: ").AppendLine();
sb.Append(" ").Append(" Max Active Threads: ").Append(MaxActiveThreads).AppendLine();
sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine();
sb.Append(" ").Append(" Delay Warning Threshold: ").Append(DelayWarningThreshold).AppendLine();
sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(ActivationSchedulingQuantum).AppendLine();
sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(TurnWarningLengthThreshold).AppendLine();
sb.Append(" ").Append(" Inject More Worker Threads: ").Append(InjectMoreWorkerThreads).AppendLine();
sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(MinDotNetThreadPoolSize).AppendLine();
int workerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine();
sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", DefaultConnectionLimit, Expect100Continue, UseNagleAlgorithm).AppendLine();
sb.Append(" Load Shedding Enabled: ").Append(LoadSheddingEnabled).AppendLine();
sb.Append(" Load Shedding Limit: ").Append(LoadSheddingLimit).AppendLine();
sb.Append(" SiloShutdownEventName: ").Append(SiloShutdownEventName).AppendLine();
sb.Append(" Debug: ").AppendLine();
sb.Append(ConfigUtilities.TraceConfigurationToString(this));
sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this));
sb.Append(LimitManager);
return sb.ToString();
}
internal void Load(XmlElement root)
{
SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME;
foreach (XmlNode c in root.ChildNodes)
{
var child = c as XmlElement;
if (child == null) continue; // Skip comment lines
switch (child.LocalName)
{
case "Networking":
if (child.HasAttribute("Address"))
{
HostNameOrIPAddress = child.GetAttribute("Address");
}
if (child.HasAttribute("Port"))
{
Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"),
"Non-numeric Port attribute value on Networking element for " + SiloName);
}
if (child.HasAttribute("PreferredFamily"))
{
AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"),
"Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'");
}
break;
case "ProxyingGateway":
ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, Subnet);
break;
case "Scheduler":
if (child.HasAttribute("MaxActiveThreads"))
{
MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"),
"Non-numeric MaxActiveThreads attribute value on Scheduler element for " + SiloName);
if (MaxActiveThreads < 1)
{
MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS;
}
}
if (child.HasAttribute("DelayWarningThreshold"))
{
DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"),
"Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("ActivationSchedulingQuantum"))
{
ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"),
"Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("TurnWarningLengthThreshold"))
{
TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"),
"Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("MinDotNetThreadPoolSize"))
{
MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"),
"Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("Expect100Continue"))
{
Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"),
"Invalid ParseBool Expect100Continue value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("DefaultConnectionLimit"))
{
DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"),
"Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + SiloName);
}
if (child.HasAttribute("UseNagleAlgorithm "))
{
UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "),
"Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + SiloName);
}
break;
case "LoadShedding":
if (child.HasAttribute("Enabled"))
{
LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"),
"Invalid boolean value for Enabled attribute on LoadShedding attribute for " + SiloName);
}
if (child.HasAttribute("LoadLimit"))
{
LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"),
"Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + SiloName);
if (LoadSheddingLimit < 0)
{
LoadSheddingLimit = 0;
}
if (LoadSheddingLimit > 100)
{
LoadSheddingLimit = 100;
}
}
break;
case "Tracing":
ConfigUtilities.ParseTracing(this, child, SiloName);
break;
case "Statistics":
ConfigUtilities.ParseStatistics(this, child, SiloName);
break;
case "Limits":
ConfigUtilities.ParseLimitValues(LimitManager, child, SiloName);
break;
case "Startup":
if (child.HasAttribute("Type"))
{
StartupTypeName = child.GetAttribute("Type");
}
break;
}
}
}
private string GetDefaultWorkingStoreDirectory()
{
string workingStoreLocation = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify);
string cacheDirBase = Path.Combine(workingStoreLocation, "OrleansData");
return cacheDirBase;
}
}
}
| |
/*
* REST API Documentation for Schoolbus
*
* API Sample
*
* OpenAPI spec version: v1
*
*
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using SchoolBusAPI.Models;
using SchoolBusAPI.ViewModels;
using SchoolBusAPI.Mappings;
using Microsoft.EntityFrameworkCore;
namespace SchoolBusAPI.Services.Impl
{
/// <summary>
///
/// </summary>
public class SchoolBusOwnerService : ISchoolBusOwnerService
{
private readonly DbAppContext _context;
/// <summary>
/// Create a service and set the database context
/// </summary>
public SchoolBusOwnerService (DbAppContext context)
{
_context = context;
}
private void AdjustSchoolBusOwner (SchoolBusOwner item)
{
// adjust Primary Contact.
if (item.PrimaryContact != null)
{
int primary_contact_id = item.PrimaryContact.Id;
var primary_contact_exists = _context.Contacts.Any(a => a.Id == primary_contact_id);
if (primary_contact_exists)
{
Contact contact = _context.Contacts.First(a => a.Id == primary_contact_id);
item.PrimaryContact = contact;
}
else
{
item.PrimaryContact = null;
}
}
// adjust District.
if (item.District != null)
{
int district_id = item.District.Id;
var district_exists = _context.ServiceAreas.Any(a => a.Id == district_id);
if (district_exists)
{
District district = _context.Districts.First(a => a.Id == district_id);
item.District = district;
}
else
{
item.District = null;
}
}
// adjust contacts
if (item.Contacts != null)
{
for (int i = 0; i < item.Contacts.Count; i++)
{
Contact contact = item.Contacts[i];
if (contact != null)
{
int contact_id = contact.Id;
bool contact_exists = _context.Contacts.Any(a => a.Id == contact_id);
if (contact_exists)
{
Contact new_contact = _context.Contacts.First(a => a.Id == contact_id);
item.Contacts[i] = new_contact;
}
else
{
item.Contacts[i] = null;
}
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
/// <response code="201">SchoolBusOwners created</response>
public virtual IActionResult SchoolbusownersBulkPostAsync (SchoolBusOwner[] items)
{
if (items == null)
{
return new BadRequestResult();
}
foreach (SchoolBusOwner item in items)
{
AdjustSchoolBusOwner(item);
var exists = _context.SchoolBusOwners.Any(a => a.Id == item.Id);
if (exists)
{
_context.SchoolBusOwners.Update(item);
}
else
{
_context.SchoolBusOwners.Add(item);
}
}
// Save the changes
_context.SaveChanges();
return new NoContentResult();
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersGetAsync ()
{
var result = _context.SchoolBusOwners
.Include(x => x.Attachments)
.Include(x => x.Contacts)
.Include(x => x.District.Region)
.Include(x => x.History)
.Include(x => x.Notes)
.Include(x => x.PrimaryContact)
.ToList();
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular SchoolBusOwner</remarks>
/// <param name="id">id of SchoolBusOwner to fetch attachments for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersIdAttachmentsGetAsync (int id)
{
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
SchoolBusOwner schoolBusOwner = _context.SchoolBusOwners
.Include(x => x.Attachments)
.First(a => a.Id == id);
var result = MappingExtensions.GetAttachmentListAsViewModel(schoolBusOwner.Attachments);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
public virtual IActionResult SchoolbusownersIdDeletePostAsync (int id)
{
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
var item = _context.SchoolBusOwners.First(a => a.Id == id);
_context.SchoolBusOwners.Remove(item);
// Save the changes
_context.SaveChanges();
return new ObjectResult(item);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a particular SchoolBusOwner</remarks>
/// <param name="id">id of SchoolBusOwner to fetch</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersIdGetAsync (int id)
{
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
var result = _context.SchoolBusOwners
.Include(x => x.Attachments)
.Include(x => x.Contacts)
.Include(x => x.District.Region)
.Include(x => x.History)
.Include(x => x.Notes)
.Include(x => x.PrimaryContact)
.First(a => a.Id == id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular SchoolBusOwner</remarks>
/// <param name="id">id of SchoolBusOwner to fetch History for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersIdHistoryGetAsync(int id, int? offset, int? limit)
{
bool exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
SchoolBusOwner schoolBusOwner = _context.SchoolBusOwners
.Include(x => x.History)
.First(a => a.Id == id);
List<History> data = schoolBusOwner.History.OrderByDescending(y => y.LastUpdateTimestamp).ToList();
if (offset == null)
{
offset = 0;
}
if (limit == null)
{
limit = data.Count() - offset;
}
List<HistoryViewModel> result = new List<HistoryViewModel>();
for (int i = (int)offset; i < data.Count() && i < offset + limit; i++)
{
result.Add(data[i].ToViewModel(id));
}
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
public virtual IActionResult SchoolbusownersIdHistoryPostAsync(int id, History item)
{
HistoryViewModel result = new HistoryViewModel();
bool exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
SchoolBusOwner schoolBusOwner = _context.SchoolBusOwners
.Include(x => x.History)
.First(a => a.Id == id);
if (schoolBusOwner.History == null)
{
schoolBusOwner.History = new List<History>();
}
// force add
item.Id = 0;
schoolBusOwner.History.Add(item);
_context.SchoolBusOwners.Update(schoolBusOwner);
_context.SaveChanges();
}
result.HistoryText = item.HistoryText;
result.Id = item.Id;
result.LastUpdateTimestamp = item.LastUpdateTimestamp;
result.LastUpdateUserid = item.LastUpdateUserid;
result.AffectedEntityId = id;
return new ObjectResult(result);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns notes for a particular SchoolBusOwner</remarks>
/// <param name="id">id of SchoolBusOwner to fetch notes for</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersIdNotesGetAsync (int id)
{
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
SchoolBusOwner schoolBusOwner = _context.SchoolBusOwners
.Include(x => x.Notes)
.First(a => a.Id == id);
var result = schoolBusOwner.Notes;
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBusOwner to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBusOwner not found</response>
public virtual IActionResult SchoolbusownersIdPutAsync (int id, SchoolBusOwner body)
{
AdjustSchoolBusOwner(body);
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists && id == body.Id)
{
_context.SchoolBusOwners.Update(body);
// Save the changes
_context.SaveChanges();
return new ObjectResult(body);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
/// Utility function used by the owner view service
/// </summary>
/// <param name="schoolBusOwnerId">Owner for which to lookup inspections</param>
/// <returns>Date of next inspection, or null if there is none</returns>
private DateTime? GetNextInspectionDate (int schoolBusOwnerId)
{
DateTime? result = null;
// next inspection is drawn from the schoolbus table
bool exists = _context.SchoolBuss.Any(x => x.SchoolBusOwner.Id == schoolBusOwnerId && x.NextInspectionDate != null && x.Status.ToLower() == "active");
if (exists)
{
SchoolBus schoolbus = _context.SchoolBuss.Where(x => x.SchoolBusOwner.Id == schoolBusOwnerId && x.NextInspectionDate != null && x.Status.ToLower() == "active")
.OrderByDescending(x => x.NextInspectionDate)
.First();
result = schoolbus.NextInspectionDate;
}
return result;
}
/// <summary>
/// Utility function used by the owner view service
/// </summary>
/// <param name="schoolBusOwnerId">Owner for which to lookup school buses</param>
/// <returns>Number of associated school buses</returns>
private int GetNumberSchoolBuses(int schoolBusOwnerId)
{
int result = 0;
// next inspection is drawn from the inspections table.
bool exists = _context.SchoolBuss.Any(x => x.SchoolBusOwner.Id == schoolBusOwnerId);
if (exists)
{
result = _context.SchoolBuss.Where(x => x.SchoolBusOwner.Id == schoolBusOwnerId && x.Status.ToLower() == "active")
.Count();
}
return result;
}
private string GetNextInspectionTypeCode(int schoolBusOwnerId)
{
string result = null;
// next inspection is drawn from the inspections table.
bool exists = _context.SchoolBuss.Any(x => x.SchoolBusOwner.Id == schoolBusOwnerId && x.NextInspectionDate != null && x.Status.ToLower() == "active");
if (exists)
{
var record = _context.SchoolBuss
.Where(x => x.SchoolBusOwner.Id == schoolBusOwnerId && x.NextInspectionDate != null && x.Status.ToLower() == "active")
.OrderByDescending(x => x.NextInspectionDate)
.First();
result = record.NextInspectionTypeCode;
}
return result;
}
/// <summary>
/// View service used by the view school bus owner page
/// </summary>
/// <param name="id">SchoolBusOwner Id</param>
/// <returns>A SchoolBusOwnerViewModel, or 404 if the record does not exist</returns>
public IActionResult SchoolbusownersIdViewGetAsync(int id)
{
var exists = _context.SchoolBusOwners.Any(a => a.Id == id);
if (exists)
{
SchoolBusOwner schoolBusOwner = _context.SchoolBusOwners.First(a => a.Id == id);
SchoolBusOwnerViewModel result = schoolBusOwner.ToViewModel();
// populate the calculated fields.
result.NextInspectionDate = GetNextInspectionDate(id); ;
result.NumberOfBuses = GetNumberSchoolBuses(id);
result.NextInspectionTypeCode = GetNextInspectionTypeCode(id);
return new ObjectResult(result);
}
else
{
// record not found
return new StatusCodeResult(404);
}
}
/// <summary>
///
/// </summary>
/// <param name="body"></param>
/// <response code="201">SchoolBusOwner created</response>
public virtual IActionResult SchoolbusownersPostAsync (SchoolBusOwner body)
{
AdjustSchoolBusOwner(body);
body.DateCreated = DateTime.UtcNow;
_context.SchoolBusOwners.Add(body);
_context.SaveChanges();
return new ObjectResult(body);
}
/// <summary>
/// Searches school bus owners
/// </summary>
/// <remarks>Used for the search school bus owners.</remarks>
/// <param name="districts">Districts (array of id numbers)</param>
/// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param>
/// <param name="owner"></param>
/// <param name="includeInactive">True if Inactive schoolbuses will be returned</param>
/// <response code="200">OK</response>
public virtual IActionResult SchoolbusownersSearchGetAsync(int?[] districts, int?[] inspectors, int? owner, bool? includeInactive)
{
// Eager loading of related data
var data = _context.SchoolBusOwners
.Include(x => x.Attachments)
.Include(x => x.Contacts)
.Include(x => x.District.Region)
.Include(x => x.History)
.Include(x => x.Notes)
.Include(x => x.PrimaryContact)
.Select(x => x);
// Note that Districts searches SchoolBus Districts, not SchoolBusOwner Districts
if (districts != null)
{
List<int> ids = new List<int>();
// get the owner ids for matching records.
foreach (int? district in districts)
{
if (district != null)
{
var buses = _context.SchoolBuss
.Include(x => x.District)
.Include(x => x.SchoolBusOwner)
.Where(x => x.District.Id == district);
foreach (var bus in buses)
{
if (bus.SchoolBusOwner != null)
{
ids.Add(bus.SchoolBusOwner.Id);
}
}
}
}
if (ids.Count > 0)
{
data = data.Where(x => ids.Contains(x.Id));
}
}
if (inspectors != null)
{
List<int> ids = new List<int>();
// get the owner ids for matching records.
foreach (int? inspector in inspectors)
{
if (inspector != null)
{
var buses = _context.SchoolBuss
.Include(x => x.Inspector)
.Include( x => x.SchoolBusOwner)
.Where(x => x.Inspector.Id == inspector);
foreach (var bus in buses)
{
if (bus.SchoolBusOwner != null)
{
ids.Add(bus.SchoolBusOwner.Id);
}
}
}
}
if (ids.Count > 0)
{
data = data.Where(x => ids.Contains(x.Id));
}
}
if (owner != null)
{
data = data.Where(x => x.Id == owner);
}
if (includeInactive == null || includeInactive == false)
{
data = data.Where(x => x.Status == "Active");
}
// now convert the results to the view model.
var result = new List<SchoolBusOwnerViewModel>();
foreach (SchoolBusOwner item in data)
{
SchoolBusOwnerViewModel record = item.ToViewModel();
result.Add(record);
}
// second pass to get the calculated fields
foreach (SchoolBusOwnerViewModel item in result)
{
// populate the calculated fields.
item.NextInspectionDate = GetNextInspectionDate(item.Id); ;
item.NumberOfBuses = GetNumberSchoolBuses(item.Id);
item.NextInspectionTypeCode = GetNextInspectionTypeCode(item.Id);
}
return new ObjectResult(result);
}
}
}
| |
/*
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 java.lang;
using java.util;
using stab.query;
using stab.reflection;
using cnatural.compiler;
using cnatural.syntaxtree;
namespace cnatural.eclipse.helpers {
public class SyntaxTreeHelper {
public static Iterable<TypeMemberNode> getTypeMembers(CompilationUnitNode compilationUnit) {
var result = new ArrayList<TypeMemberNode>();
addTypeMembers(compilationUnit.getBody(), result);
return result;
}
public static Iterable<TypeInfo> getTypeMemberDependencies(TypeMemberNode tm) {
var result = new HashSet<TypeInfo>();
addTypeMemberDependencies(tm, result);
return result;
}
private static void addTypeMembers(PackageBodyNode packageBody, List<TypeMemberNode> types) {
if (packageBody != null) {
foreach (var m in packageBody.getMembers()) {
switch (m.PackageMemberKind) {
case Package:
var p = (PackageDeclarationNode)m;
if (p.Body != null) {
addTypeMembers(p.Body, types);
}
break;
case Class:
var c = (ClassDeclarationNode)m;
addTypeMembers(c, types);
break;
case Interface:
case Delegate:
types.add((TypeMemberNode)m);
break;
}
}
}
}
private static void addTypeMembers(ClassDeclarationNode classDeclaration, List<TypeMemberNode> types) {
types.add(classDeclaration);
foreach (var m in classDeclaration.Members) {
switch (m.TypeMemberKind) {
case Class:
var c = (ClassDeclarationNode)m;
addTypeMembers(c, types);
break;
case Interface:
case Delegate:
types.add((TypeMemberNode)m);
break;
}
}
}
private static void addDependencies(TypeInfo type, Set<TypeInfo> dependencies) {
if (type == null || type.IsPrimitive || type.IsGenericParameter) {
return;
}
while (type.IsArray) {
type = type.ElementType;
}
foreach (var a in type.GenericArguments) {
addDependencies(a, dependencies);
}
dependencies.add(type);
}
private static void addTypeMemberDependencies(TypeMemberNode tm, Set<TypeInfo> dependencies) {
var t = tm.getUserData(typeof(TypeInfo));
if (t == null) {
return;
}
addAnnotationsDependencies(t.Annotations, dependencies);
foreach (var ga in t.GenericArguments) {
foreach (var b in ga.GenericParameterBounds) {
addDependencies(b, dependencies);
}
}
ExpressionDependenciesHandler expressionHandler = null;
switch (tm.TypeMemberKind) {
case Class:
var c = (ClassDeclarationNode)tm;
addDependencies(t.BaseType, dependencies);
foreach (var i in t.Interfaces) {
addDependencies(i, dependencies);
}
foreach (var cm in c.Members) {
switch (cm.TypeMemberKind) {
case Class:
case Interface:
case Delegate:
addTypeMemberDependencies((TypeMemberNode)cm, dependencies);
break;
case EnumConstant:
var enumConstant = (EnumConstantDeclarationNode)cm;
addTypeMemberDependencies(enumConstant, dependencies);
foreach (var e in enumConstant.Arguments) {
if (expressionHandler == null) {
expressionHandler = new ExpressionDependenciesHandler(null);
}
expressionHandler.handleExpression(e, dependencies, true);
}
break;
case Field:
foreach (var decl in ((FieldDeclarationNode)cm).Declarators) {
var f = decl.getUserData(typeof(FieldInfo));
addDependencies(f.Type, dependencies);
addAnnotationsDependencies(f.Annotations, dependencies);
if (decl.Value != null) {
if (expressionHandler == null) {
expressionHandler = new ExpressionDependenciesHandler(null);
}
expressionHandler.handleExpression(decl.Value, dependencies, true);
}
}
break;
case Constructor:
var constructor = (ConstructorDeclarationNode)cm;
addBodyDependencies(constructor.getUserData(typeof(MethodInfo)), constructor.Body, dependencies);
if (constructor.Initializer != null) {
foreach (var e in constructor.Initializer.Arguments) {
if (expressionHandler == null) {
expressionHandler = new ExpressionDependenciesHandler(null);
}
expressionHandler.handleExpression(e, dependencies, true);
}
}
break;
case Destructor:
var destructor = (DestructorDeclarationNode)cm;
addBodyDependencies(destructor.getUserData(typeof(MethodInfo)), destructor.Body, dependencies);
break;
case Method:
var method = (MethodDeclarationNode)cm;
addBodyDependencies(method.getUserData(typeof(MethodInfo)), method.Body, dependencies);
break;
case Property:
case Indexer:
var accessorsOwner = (IAccessorsOwner)cm;
var get = accessorsOwner.getGetAccessor();
var set = accessorsOwner.getSetAccessor();
if (get != null) {
addBodyDependencies(get.getUserData(typeof(MethodInfo)), get.Body, dependencies);
}
if (set != null) {
addBodyDependencies(set.getUserData(typeof(MethodInfo)), set.Body, dependencies);
}
break;
}
}
break;
case Interface:
case Delegate:
foreach (var i in t.getInterfaces()) {
addDependencies(i, dependencies);
addAnnotationsDependencies(i.Annotations, dependencies);
}
foreach (var meth in t.Methods) {
addDependencies(meth.ReturnType, dependencies);
addAnnotationsDependencies(meth.Annotations, dependencies);
foreach (var p in meth.Parameters) {
addDependencies(p.Type, dependencies);
addAnnotationsDependencies(p.Annotations, dependencies);
}
}
break;
}
}
private static void addBodyDependencies(MethodInfo meth, BlockStatementNode body, Set<TypeInfo> dependencies) {
addAnnotationsDependencies(meth.Annotations, dependencies);
addDependencies(meth.ReturnType, dependencies);
foreach (var p in meth.Parameters) {
addDependencies(p.Type, dependencies);
addAnnotationsDependencies(p.Annotations, dependencies);
}
foreach (var tp in meth.GenericArguments) {
foreach (var b in tp.GenericParameterBounds) {
addDependencies(b, dependencies);
}
}
if (body != null) {
new StatementDependenciesHandler(null).handleStatement(body, dependencies);
}
}
private static void addAnnotationsDependencies(Iterable<AnnotationValue> values, Set<TypeInfo> dependencies) {
foreach (var av in values) {
foreach (var s in av.getArgumentNames()) {
addAnnotationDependencies(av.getArgument(s), dependencies);
}
}
}
private static void addAnnotationDependencies(AnnotationArgument arg, Set<TypeInfo> dependencies) {
switch (arg.AnnotationArgumentKind) {
case Annotation:
foreach (var s in arg.getArgumentNames()) {
addAnnotationDependencies(arg.getArgument(s), dependencies);
}
break;
case Array:
foreach (var e in arg.getElements()) {
addAnnotationDependencies(e, dependencies);
}
break;
case Enum:
case Type:
addDependencies(arg.Type, dependencies);
break;
}
}
class StatementDependenciesHandler : StatementHandler<Set<TypeInfo>, Void> {
private ExpressionDependenciesHandler expressionHandler;
StatementDependenciesHandler(ExpressionDependenciesHandler expressionHandler)
: super(false) {
this.expressionHandler = expressionHandler ?? new ExpressionDependenciesHandler(this);
}
protected override Void handleBlock(BlockStatementNode block, Set<TypeInfo> dependencies) {
foreach (StatementNode s in block.Statements) {
handleStatement(s, dependencies);
}
return null;
}
protected override Void handleDo(DoStatementNode doStatement, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(doStatement.Condition, dependencies, true);
handleStatement(doStatement.Statement, dependencies);
return null;
}
protected override Void handleExpression(ExpressionStatementNode expression, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(expression.Expression, dependencies, false);
return null;
}
protected override Void handleFor(ForStatementNode forStatement, Set<TypeInfo> dependencies) {
foreach (var s in forStatement.Initializer) {
handleStatement(s, dependencies);
}
if (forStatement.Condition != null) {
expressionHandler.handleExpression(forStatement.Condition, dependencies, true);
}
foreach (var s in forStatement.Iterator) {
handleStatement(s, dependencies);
}
handleStatement(forStatement.Statement, dependencies);
return null;
}
protected override Void handleForeach(ForeachStatementNode foreachStatement, Set<TypeInfo> dependencies) {
if (foreachStatement.Type != null) {
var info = foreachStatement.getUserData(typeof(MemberInfo));
addDependencies(info.Type, dependencies);
}
expressionHandler.handleExpression(foreachStatement.Source, dependencies, true);
handleStatement(foreachStatement.Statement, dependencies);
return null;
}
protected override Void handleIf(IfStatementNode ifStatement, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(ifStatement.Condition, dependencies, true);
handleStatement(ifStatement.IfTrue, dependencies);
if (ifStatement.IfFalse != null) {
handleStatement(ifStatement.IfFalse, dependencies);
}
return null;
}
protected override Void handleLabeled(LabeledStatementNode labeled, Set<TypeInfo> dependencies) {
handleStatement(labeled.Statement, dependencies);
return null;
}
protected override Void handleLocalDeclaration(LocalDeclarationStatementNode localDeclaration, Set<TypeInfo> dependencies) {
var info = localDeclaration.getUserData(typeof(ExpressionInfo));
addDependencies(info.Type, dependencies);
foreach (var decl in localDeclaration.Declarators) {
if (decl.Value != null) {
expressionHandler.handleExpression(decl.Value, dependencies, true);
}
}
return null;
}
protected override Void handleReturn(ReturnStatementNode returnStatement, Set<TypeInfo> dependencies) {
if (returnStatement.Value != null) {
expressionHandler.handleExpression(returnStatement.Value, dependencies, true);
}
return null;
}
protected override Void handleSwitch(SwitchStatementNode switchStatement, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(switchStatement.Selector, dependencies, true);
var sinfo = switchStatement.Selector.getUserData(typeof(ExpressionInfo));
addDependencies(sinfo.Type, dependencies);
foreach (var section in switchStatement.Sections) {
if (section.CaseExpression != null) {
if (!sinfo.Type.IsEnum) {
expressionHandler.handleExpression(section.CaseExpression, dependencies, true);
}
}
foreach (var s in section.Statements) {
handleStatement(s, dependencies);
}
}
return null;
}
protected override Void handleSynchronized(SynchronizedStatementNode synchronizedStatement, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(synchronizedStatement.Lock, dependencies, true);
handleStatement(synchronizedStatement.Statement, dependencies);
return null;
}
protected override Void handleThrow(ThrowStatementNode throwStatement, Set<TypeInfo> dependencies) {
if (throwStatement.Exception != null) {
expressionHandler.handleExpression(throwStatement.Exception, dependencies, true);
}
return null;
}
protected override Void handleTry(TryStatementNode tryStatement, Set<TypeInfo> dependencies) {
handleBlock(tryStatement.Block, dependencies);
foreach (var cc in tryStatement.CatchClauses) {
if (cc.ExceptionType != null) {
addDependencies(cc.getUserData(typeof(TypeInfo)), dependencies);
}
handleBlock(cc.Block, dependencies);
}
if (tryStatement.Finally != null) {
handleBlock(tryStatement.Finally, dependencies);
}
return null;
}
protected override Void handleUsing(UsingStatementNode usingStatement, Set<TypeInfo> dependencies) {
handleStatement(usingStatement.ResourceAcquisition, dependencies);
handleStatement(usingStatement.Statement, dependencies);
return null;
}
protected override Void handleWhile(WhileStatementNode whileStatement, Set<TypeInfo> dependencies) {
expressionHandler.handleExpression(whileStatement.Condition, dependencies, true);
handleStatement(whileStatement.Statement, dependencies);
return null;
}
protected override Void handleYield(YieldStatementNode yield, Set<TypeInfo> dependencies) {
if (yield.Value != null) {
expressionHandler.handleExpression(yield.Value, dependencies, true);
}
return null;
}
}
class ExpressionDependenciesHandler : ExpressionHandler<Set<TypeInfo>, Void> {
private StatementDependenciesHandler statementHandler;
ExpressionDependenciesHandler(StatementDependenciesHandler statementHandler)
: super(false) {
this.statementHandler = statementHandler ?? new StatementDependenciesHandler(this);
}
protected override Void handleAnonymousObjectCreation(AnonymousObjectCreationExpressionNode anonymousObject, Set<TypeInfo> dependencies, bool nested) {
foreach (MemberInitializerNode mi in anonymousObject.getMemberDeclarators()) {
handleExpression(mi.getValue(), dependencies, nested);
}
return null;
}
protected override Void handleArrayCreation(ArrayCreationExpressionNode arrayCreation, Set<TypeInfo> dependencies, bool nested) {
var info = arrayCreation.getUserData(typeof(ExpressionInfo));
addDependencies(info.Type, dependencies);
foreach (var e in arrayCreation.DimensionExpressions) {
handleExpression(e, dependencies, true);
}
if (arrayCreation.Initializer != null) {
handleExpression(arrayCreation.Initializer, dependencies, true);
}
return null;
}
protected override Void handleArrayInitializer(ArrayInitializerExpressionNode arrayInitializer, Set<TypeInfo> dependencies, bool nested) {
foreach (var e in arrayInitializer.Values) {
handleExpression(e, dependencies, true);
}
return null;
}
protected override Void handleAssign(AssignExpressionNode assign, Set<TypeInfo> dependencies, bool nested) {
handleExpression(assign.Left, dependencies, true);
handleExpression(assign.Right, dependencies, true);
return null;
}
protected override Void handleBinary(BinaryExpressionNode binary, Set<TypeInfo> dependencies, bool nested) {
handleExpression(binary.LeftOperand, dependencies, true);
handleExpression(binary.RightOperand, dependencies, true);
return null;
}
protected override Void handleCast(CastExpressionNode cast, Set<TypeInfo> dependencies, bool nested) {
var info = cast.getUserData(typeof(ExpressionInfo));
addDependencies(info.Type, dependencies);
handleExpression(cast.Expression, dependencies, true);
return null;
}
protected override Void handleConditional(ConditionalExpressionNode conditional, Set<TypeInfo> dependencies, bool nested) {
handleExpression(conditional.Condition, dependencies, true);
handleExpression(conditional.IfTrue, dependencies, true);
handleExpression(conditional.IfFalse, dependencies, true);
return null;
}
protected override Void handleElementAccess(ElementAccessExpressionNode elementAccess, Set<TypeInfo> dependencies, bool nested) {
handleExpression(elementAccess.TargetObject, dependencies, true);
foreach (var e in elementAccess.Indexes) {
handleExpression(e, dependencies, true);
}
return null;
}
protected override Void handleInvocation(InvocationExpressionNode invocation, Set<TypeInfo> dependencies, bool nested) {
handleExpression(invocation.TargetObject, dependencies, nested);
foreach (var e in invocation.Arguments) {
handleExpression(e, dependencies, true);
}
return null;
}
protected override Void handleLambda(LambdaExpressionNode lambda, Set<TypeInfo> dependencies, bool nested) {
var m = lambda.getUserData(typeof(MethodInfo));
foreach (var p in m.Parameters) {
addDependencies(p.Type, dependencies);
}
statementHandler.handleStatement(lambda.Body, dependencies);
return null;
}
protected override Void handleMemberAccess(MemberAccessExpressionNode memberAccess, Set<TypeInfo> dependencies, bool nested) {
var info = memberAccess.getUserData(typeof(ExpressionInfo));
var member = info.getMember();
handleExpression(memberAccess.TargetObject, dependencies, nested);
if (member == null) {
var type = info.Type;
if (type != null) {
addDependencies(type, dependencies);
}
}
return null;
}
protected override Void handleObjectCreation(ObjectCreationExpressionNode objectCreation, Set<TypeInfo> dependencies, bool nested) {
var info = objectCreation.getUserData(typeof(ExpressionInfo));
addDependencies(info.Type, dependencies);
foreach (var e in objectCreation.Arguments) {
handleExpression(e, dependencies, true);
}
if (objectCreation.Initializer != null) {
handleExpression(objectCreation.Initializer, dependencies, true);
}
return null;
}
protected override Void handleCollectionInitializer(CollectionInitializerExpressionNode initializer, Set<TypeInfo> dependencies, bool nested) {
foreach (var e in initializer.Values.selectMany(p => p)) {
handleExpression(e, dependencies, true);
}
return null;
}
protected override Void handleObjectInitializer(ObjectInitializerExpressionNode initializer, Set<TypeInfo> dependencies, bool nested) {
foreach (var init in initializer.MemberInitializers) {
handleExpression(init.Value, dependencies, true);
}
return null;
}
protected override Void handleSimpleName(SimpleNameExpressionNode simpleName, Set<TypeInfo> dependencies, bool nested) {
var info = simpleName.getUserData(typeof(ExpressionInfo));
var member = info.Member;
if (member != null && member.MemberKind == MemberKind.Type) {
addDependencies(member.Type, dependencies);
}
return null;
}
protected override Void handleSizeof(SizeofExpressionNode sizeofExpression, Set<TypeInfo> dependencies, bool nested) {
handleExpression(sizeofExpression.Expression, dependencies, nested);
return null;
}
protected override Void handleType(TypeExpressionNode type, Set<TypeInfo> dependencies, bool nested) {
var info = type.getUserData(typeof(ExpressionInfo));
addDependencies(info.Type, dependencies);
return null;
}
protected override Void handleTypeof(TypeofExpressionNode typeofExpression, Set<TypeInfo> dependencies, bool nested) {
addDependencies(typeofExpression.getUserData(typeof(TypeInfo)), dependencies);
return null;
}
protected override Void handleUnary(UnaryExpressionNode unary, Set<TypeInfo> dependencies, bool nested) {
handleExpression(unary.Operand, dependencies, true);
return null;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// UAudioManagerBase provides the base functionality for UAudioManager classes.
/// </summary>
/// <typeparam name="TEvent">The type of AudioEvent being managed.</typeparam>
/// <remarks>The TEvent type specified must derive from AudioEvent.</remarks>
public partial class UAudioManagerBase<TEvent> : MonoBehaviour where TEvent : AudioEvent, new()
{
[SerializeField]
protected TEvent[] Events = null;
protected const float InfiniteLoop = -1;
protected List<ActiveEvent> ActiveEvents;
#if UNITY_EDITOR
public TEvent[] EditorEvents { get { return Events; } set { Events = value; } }
public List<ActiveEvent> ProfilerEvents { get { return ActiveEvents; } }
#endif
protected void Awake()
{
ActiveEvents = new List<ActiveEvent>();
}
private void Update()
{
UpdateEmitterVolumes();
}
protected void OnDestroy()
{
StopAllEvents();
}
/// <summary>
/// Stops all ActiveEvents
/// </summary>
public void StopAllEvents()
{
for (int i = ActiveEvents.Count - 1; i >= 0; i--)
{
StopEvent(ActiveEvents[i]);
}
}
/// <summary>
/// Fades out all of the events over fadeTime and stops once completely faded out.
/// </summary>
/// <param name="fadeTime">The amount of time, in seconds, to fade between current volume and 0.</param>
public void StopAllEvents(float fadeTime)
{
for (int i = ActiveEvents.Count - 1; i >= 0; i--)
{
StartCoroutine(StopEventWithFadeCoroutine(ActiveEvents[i], fadeTime));
}
}
/// <summary>
/// Stops all events on a single emitter.
/// </summary>
public void StopAllEvents(GameObject emitter)
{
for (int i = ActiveEvents.Count - 1; i >= 0; i--)
{
if (ActiveEvents[i].AudioEmitter == emitter)
{
StopEvent(ActiveEvents[i]);
}
}
}
/// <summary>
/// Stops all events on one AudioSource.
/// </summary>
public void StopAllEvents(AudioSource emitter)
{
for (int i = ActiveEvents.Count - 1; i >= 0; i--)
{
if (ActiveEvents[i].PrimarySource == emitter)
{
StopEvent(ActiveEvents[i]);
}
}
}
/// <summary>
/// Linearly interpolates the volume property on all of the AudioSource components in the ActiveEvents.
/// </summary>
private void UpdateEmitterVolumes()
{
// Move through each active event and change the settings for the AudioSource components to smoothly fade volumes.
for (int i = 0; i < ActiveEvents.Count; i++)
{
ActiveEvent currentEvent = this.ActiveEvents[i];
// If we have a secondary source (for crossfades) adjust the volume based on the current fade time for each active event.
if (currentEvent.SecondarySource != null && currentEvent.SecondarySource.volume != currentEvent.AltVolDest)
{
if (Mathf.Abs(currentEvent.AltVolDest - currentEvent.SecondarySource.volume) < Time.deltaTime / currentEvent.CurrentFade)
{
currentEvent.SecondarySource.volume = currentEvent.AltVolDest;
}
else
{
currentEvent.SecondarySource.volume += (currentEvent.AltVolDest - currentEvent.SecondarySource.volume) * Time.deltaTime / currentEvent.CurrentFade;
}
}
// Adjust the volume of the main source based on the current fade time for each active event.
if (currentEvent.PrimarySource != null && currentEvent.PrimarySource.volume != currentEvent.VolDest)
{
if (Mathf.Abs(currentEvent.VolDest - currentEvent.PrimarySource.volume) < Time.deltaTime / currentEvent.CurrentFade)
{
currentEvent.PrimarySource.volume = currentEvent.VolDest;
}
else
{
currentEvent.PrimarySource.volume += (currentEvent.VolDest - currentEvent.PrimarySource.volume) * Time.deltaTime / currentEvent.CurrentFade;
}
}
// If there is no time left in the fade, make sure we are set to the destination volume.
if (currentEvent.CurrentFade > 0)
{
currentEvent.CurrentFade -= Time.deltaTime;
}
}
}
/// <summary>
/// Determine which rules to follow for container playback, and begin the appropriate function.
/// </summary>
/// <param name="activeEvent">The event to play.</param>
protected void PlayContainer(ActiveEvent activeEvent)
{
if (activeEvent.AudioEvent.Container.Sounds.Length == 0)
{
Debug.LogErrorFormat(this, "Trying to play container \"{0}\" with no clips.", activeEvent.AudioEvent.Container);
// Clean up the ActiveEvent before we discard it, so it will release its AudioSource(s).
activeEvent.Dispose();
return;
}
switch (activeEvent.AudioEvent.Container.ContainerType)
{
case AudioContainerType.Random:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.Simultaneous:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.Sequence:
StartOneOffEvent(activeEvent);
break;
case AudioContainerType.ContinuousSequence:
PlayContinuousSequenceContainer(activeEvent.AudioEvent.Container, activeEvent.PrimarySource, activeEvent);
break;
case AudioContainerType.ContinuousRandom:
PlayContinuousRandomContainer(activeEvent.AudioEvent.Container, activeEvent.PrimarySource, activeEvent);
break;
default:
Debug.LogErrorFormat(this, "Trying to play container \"{0}\" with an unknown AudioContainerType \"{1}\".", activeEvent.AudioEvent.Container, activeEvent.AudioEvent.Container.ContainerType);
// Clean up the ActiveEvent before we discard it, so it will release its AudioSource(s).
activeEvent.Dispose();
break;
}
}
/// <summary>
/// Begin playing a non-continuous container, loop if applicable.
/// </summary>
private void StartOneOffEvent(ActiveEvent activeEvent)
{
if (activeEvent.AudioEvent.Container.Looping)
{
StartCoroutine(PlayLoopingOneOffContainerCoroutine(activeEvent));
activeEvent.ActiveTime = InfiniteLoop;
}
else
{
PlayOneOffContainer(activeEvent);
}
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
}
/// <summary>
/// Play a non-continuous container.
/// </summary>
private float PlayOneOffContainer(ActiveEvent activeEvent)
{
AudioContainer currentContainer = activeEvent.AudioEvent.Container;
// Fading or Looping overrides immediate volume settings.
if (activeEvent.AudioEvent.FadeInTime == 0 && !activeEvent.AudioEvent.Container.Looping)
{
activeEvent.VolDest = activeEvent.PrimarySource.volume;
}
// Simultaneous sounds.
float clipTime = 0;
if (currentContainer.ContainerType == AudioContainerType.Simultaneous)
{
clipTime = PlaySimultaneousClips(currentContainer, activeEvent);
}
// Sequential and Random sounds.
else
{
clipTime = PlaySingleClip(currentContainer, activeEvent);
}
activeEvent.ActiveTime = clipTime;
return clipTime;
}
/// <summary>
/// Play all clips in container simultaneously
/// </summary>
private float PlaySimultaneousClips(AudioContainer currentContainer, ActiveEvent activeEvent)
{
float tempDelay = 0;
float finalActiveTime = 0f;
if (currentContainer.Looping)
{
finalActiveTime = InfiniteLoop;
}
for (int i = 0; i < currentContainer.Sounds.Length; i++)
{
tempDelay = PlayClipAndGetTime(currentContainer.Sounds[i], activeEvent.PrimarySource, activeEvent);
if (finalActiveTime != InfiniteLoop)
{
float estimatedActiveTimeNeeded = GetActiveTimeEstimate(currentContainer.Sounds[i], activeEvent, tempDelay);
if (estimatedActiveTimeNeeded == InfiniteLoop || estimatedActiveTimeNeeded > finalActiveTime)
{
finalActiveTime = estimatedActiveTimeNeeded;
}
}
}
return finalActiveTime;
}
/// <summary>
/// Play one sound from a container based on container behavior.
/// </summary>
/// <param name="currentContainer"></param>
/// <param name="activeEvent"></param>
/// <returns>The estimated ActiveTime for the clip, or InfiniteLoop if the container and/or clip are set to loop.</returns>
private float PlaySingleClip(AudioContainer currentContainer, ActiveEvent activeEvent)
{
float tempDelay = 0;
if (currentContainer.ContainerType == AudioContainerType.Random)
{
currentContainer.CurrentClip = Random.Range(0, currentContainer.Sounds.Length);
}
UAudioClip currentClip = currentContainer.Sounds[currentContainer.CurrentClip];
// Trigger sound and save the delay (in seconds) to add to the total amount of time the event will be considered active.
tempDelay = PlayClipAndGetTime(currentClip, activeEvent.PrimarySource, activeEvent);
// Ready the next clip in the series if sequence container.
if (currentContainer.ContainerType == AudioContainerType.Sequence)
{
currentContainer.CurrentClip++;
if (currentContainer.CurrentClip >= currentContainer.Sounds.Length)
{
currentContainer.CurrentClip = 0;
}
}
// Return active time based on Looping or clip time.
return GetActiveTimeEstimate(currentClip, activeEvent, tempDelay);
}
/// <summary>
/// Repeatedly trigger the one-off container based on the loop time.
/// </summary>
private IEnumerator PlayLoopingOneOffContainerCoroutine(ActiveEvent activeEvent)
{
while (!activeEvent.CancelEvent)
{
float tempLoopTime = PlayOneOffContainer(activeEvent);
float eventLoopTime = activeEvent.AudioEvent.Container.LoopTime;
// Protect against containers Looping every frame by defaulting to the length of the audio clip.
if (eventLoopTime != 0)
{
tempLoopTime = eventLoopTime;
}
yield return new WaitForSeconds(tempLoopTime);
}
}
/// <summary>
/// Choose a random sound from a container and play, calling the Looping coroutine to constantly choose new audio clips when current clip ends.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void PlayContinuousRandomContainer(AudioContainer audioContainer, AudioSource emitter, ActiveEvent activeEvent)
{
audioContainer.CurrentClip = Random.Range(0, audioContainer.Sounds.Length);
UAudioClip tempClip = audioContainer.Sounds[audioContainer.CurrentClip];
activeEvent.PrimarySource.volume = 0f;
activeEvent.VolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.AltVolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
float waitTime = (tempClip.Sound.length / emitter.pitch) - activeEvent.AudioEvent.Container.CrossfadeTime;
// Ignore clip delay since container is continuous.
PlayClipAndGetTime(tempClip, emitter, activeEvent);
activeEvent.ActiveTime = InfiniteLoop;
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
audioContainer.CurrentClip++;
if (audioContainer.CurrentClip >= audioContainer.Sounds.Length)
{
audioContainer.CurrentClip = 0;
}
StartCoroutine(ContinueRandomContainerCoroutine(audioContainer, activeEvent, waitTime));
}
/// <summary>
/// Coroutine for "continuous" random containers that alternates between two sources to crossfade clips for continuous playlist Looping.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="waitTime">The time in seconds to wait before switching AudioSources for crossfading.</param>
/// <returns>The coroutine.</returns>
private IEnumerator ContinueRandomContainerCoroutine(AudioContainer audioContainer, ActiveEvent activeEvent, float waitTime)
{
while (!activeEvent.CancelEvent)
{
yield return new WaitForSeconds(waitTime);
audioContainer.CurrentClip = Random.Range(0, audioContainer.Sounds.Length);
UAudioClip tempClip = audioContainer.Sounds[audioContainer.CurrentClip];
// Play on primary source.
if (activeEvent.PlayingAlt)
{
activeEvent.PrimarySource.volume = 0f;
activeEvent.VolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.AltVolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
waitTime = (tempClip.Sound.length / activeEvent.PrimarySource.pitch) - audioContainer.CrossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.PrimarySource, activeEvent);
}
// Play on secondary source.
else
{
activeEvent.SecondarySource.volume = 0f;
activeEvent.AltVolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.VolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
waitTime = (tempClip.Sound.length / activeEvent.SecondarySource.pitch) - audioContainer.CrossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.SecondarySource, activeEvent);
}
activeEvent.PlayingAlt = !activeEvent.PlayingAlt;
}
}
/// <summary>
/// Play the current clip in a container, and call the coroutine to constantly choose new audio clips when the current clip ends.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void PlayContinuousSequenceContainer(AudioContainer audioContainer, AudioSource emitter, ActiveEvent activeEvent)
{
UAudioClip tempClip = audioContainer.Sounds[audioContainer.CurrentClip];
activeEvent.PrimarySource.volume = 0f;
activeEvent.VolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.AltVolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
float waitTime = (tempClip.Sound.length / emitter.pitch) - activeEvent.AudioEvent.Container.CrossfadeTime;
// Ignore clip delay since the container is continuous.
PlayClipAndGetTime(tempClip, emitter, activeEvent);
activeEvent.ActiveTime = InfiniteLoop;
StartCoroutine(RecordEventInstanceCoroutine(activeEvent));
audioContainer.CurrentClip++;
if (audioContainer.CurrentClip >= audioContainer.Sounds.Length)
{
audioContainer.CurrentClip = 0;
}
StartCoroutine(ContinueSequenceContainerCoroutine(audioContainer, activeEvent, waitTime));
}
/// <summary>
/// Coroutine for "continuous" sequence containers that alternates between two sources to crossfade clips for continuous playlist Looping.
/// </summary>
/// <param name="audioContainer">The audio container.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="waitTime">The time in seconds to wait before switching AudioSources to crossfading.</param>
/// <returns>The coroutine.</returns>
private IEnumerator ContinueSequenceContainerCoroutine(AudioContainer audioContainer, ActiveEvent activeEvent, float waitTime)
{
while (!activeEvent.CancelEvent)
{
yield return new WaitForSeconds(waitTime);
UAudioClip tempClip = audioContainer.Sounds[audioContainer.CurrentClip];
if (tempClip.Sound == null)
{
Debug.LogErrorFormat(this, "Sound clip in event \"{0}\" is null!", activeEvent.AudioEvent.Name);
waitTime = 0;
}
else
{
// Play on primary source.
if (activeEvent.PlayingAlt)
{
activeEvent.PrimarySource.volume = 0f;
activeEvent.VolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.AltVolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
waitTime = (tempClip.Sound.length / activeEvent.PrimarySource.pitch) - audioContainer.CrossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.PrimarySource, activeEvent);
}
// Play on secondary source.
else
{
activeEvent.SecondarySource.volume = 0f;
activeEvent.AltVolDest = activeEvent.AudioEvent.VolumeCenter;
activeEvent.VolDest = 0f;
activeEvent.CurrentFade = audioContainer.CrossfadeTime;
waitTime = (tempClip.Sound.length / activeEvent.SecondarySource.pitch) - audioContainer.CrossfadeTime;
PlayClipAndGetTime(tempClip, activeEvent.SecondarySource, activeEvent);
}
}
audioContainer.CurrentClip++;
if (audioContainer.CurrentClip >= audioContainer.Sounds.Length)
{
audioContainer.CurrentClip = 0;
}
activeEvent.PlayingAlt = !activeEvent.PlayingAlt;
}
}
/// <summary>
/// Play a single clip on an AudioSource; if Looping forever, return InfiniteLoop for the event time.
/// </summary>
/// <param name="audioClip">The audio clip to play.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The amount of delay, if any, we are waiting before playing the clip. A Looping clip will always return InfiniteLoop.</returns>
private float PlayClipAndGetTime(UAudioClip audioClip, AudioSource emitter, ActiveEvent activeEvent)
{
if (audioClip.DelayCenter == 0)
{
emitter.PlayClip(audioClip.Sound, audioClip.Looping);
if (audioClip.Looping)
{
return InfiniteLoop;
}
return 0;
}
else
{
float rndDelay = Random.Range(audioClip.DelayCenter - audioClip.DelayRandomization, audioClip.DelayCenter + audioClip.DelayRandomization);
StartCoroutine(PlayClipDelayedCoroutine(audioClip, emitter, rndDelay, activeEvent));
if (audioClip.Looping)
{
return InfiniteLoop;
}
return rndDelay;
}
}
/// <summary>
/// Coroutine for playing a clip after a delay (in seconds).
/// </summary>
/// <param name="audioClip">The clip to play.</param>
/// <param name="emitter">The emitter to use.</param>
/// <param name="delay">The amount of time in seconds to wait before playing audio clip.</param>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The coroutine.</returns>
private IEnumerator PlayClipDelayedCoroutine(UAudioClip audioClip, AudioSource emitter, float delay, ActiveEvent activeEvent)
{
yield return new WaitForSeconds(delay);
if (this.ActiveEvents.Contains(activeEvent))
{
emitter.PlayClip(audioClip.Sound, audioClip.Looping);
}
}
/// <summary>
/// Stop audio sources in an event, and clean up instance references.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
protected void StopEvent(ActiveEvent activeEvent)
{
if (activeEvent.PrimarySource != null)
{
activeEvent.PrimarySource.Stop();
}
if (activeEvent.SecondarySource != null)
{
activeEvent.SecondarySource.Stop();
}
activeEvent.CancelEvent = true;
RemoveEventInstance(activeEvent);
}
/// <summary>
/// Coroutine for fading out an AudioSource, and stopping the event once fade is complete.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <param name="fadeTime">The amount of time, in seconds, to completely fade out the sound.</param>
/// <returns>The coroutine.</returns>
protected IEnumerator StopEventWithFadeCoroutine(ActiveEvent activeEvent, float fadeTime)
{
if (activeEvent.IsStoppable)
{
activeEvent.IsStoppable = false;
activeEvent.VolDest = 0f;
activeEvent.AltVolDest = 0f;
activeEvent.CurrentFade = fadeTime;
yield return new WaitForSeconds(fadeTime);
if (activeEvent.PrimarySource != null)
{
activeEvent.PrimarySource.Stop();
}
if (activeEvent.SecondarySource != null)
{
activeEvent.SecondarySource.Stop();
}
activeEvent.CancelEvent = true;
RemoveEventInstance(activeEvent);
}
}
/// <summary>
/// Keep an event in the "ActiveEvents" list for the amount of time we think it will be playing, plus the instance buffer.
/// This is mostly done for instance limiting purposes.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
/// <returns>The coroutine.</returns>
private IEnumerator RecordEventInstanceCoroutine(ActiveEvent activeEvent)
{
// Unity has no callback for an audioclip ending, so we have to estimate it ahead of time.
// Changing the pitch during playback will alter actual playback time.
ActiveEvents.Add(activeEvent);
// Only return active time if sound is not Looping/continuous.
if (activeEvent.ActiveTime > 0)
{
yield return new WaitForSeconds(activeEvent.ActiveTime);
// Mark this event so it no longer counts against the instance limit.
activeEvent.IsActiveTimeComplete = true;
// Since the ActiveTime estimate may not be enough time to complete the clip (due to pitch changes during playback, or a negative instanceBuffer value, for example)
// wait here until it is finished, so that we don't cut off the end.
if (activeEvent.IsPlaying)
{
yield return null;
}
}
// Otherwise, continue at next frame.
else
{
yield return null;
}
if (activeEvent.ActiveTime != InfiniteLoop)
{
RemoveEventInstance(activeEvent);
}
}
/// <summary>
/// Remove event from the currently active events.
/// </summary>
/// <param name="activeEvent">The persistent reference to the event as long as it is playing.</param>
private void RemoveEventInstance(ActiveEvent activeEvent)
{
ActiveEvents.Remove(activeEvent);
// Send message notifying user that sound is complete
if (!string.IsNullOrEmpty(activeEvent.MessageOnAudioEnd))
{
activeEvent.AudioEmitter.SendMessage(activeEvent.MessageOnAudioEnd);
}
activeEvent.Dispose();
}
/// <summary>
/// Return the number of instances matching the name eventName for instance limiting check.
/// </summary>
/// <param name="eventName">The name of the event to check.</param>
/// <returns>The number of instances of that event currently active.</returns>
protected int GetInstances(string eventName)
{
int tempInstances = 0;
for (int i = 0; i < ActiveEvents.Count; i++)
{
var eventInstance = ActiveEvents[i];
if (!eventInstance.IsActiveTimeComplete && eventInstance.AudioEvent.Name == eventName)
{
tempInstances++;
}
}
return tempInstances;
}
/// <summary>
/// Calculates the estimated active time for an ActiveEvent playing the given clip.
/// </summary>
/// <param name="audioClip">The clip being played.</param>
/// <param name="activeEvent">The event being played.</param>
/// <param name="additionalDelay">The delay before playing in seconds.</param>
/// <returns>The estimated active time of the event based on Looping or clip time. If Looping, this will return InfiniteLoop.</returns>
private static float GetActiveTimeEstimate(UAudioClip audioClip, ActiveEvent activeEvent, float additionalDelay)
{
if (audioClip.Looping || activeEvent.AudioEvent.Container.Looping || additionalDelay == InfiniteLoop)
{
return InfiniteLoop;
}
else
{
float pitchAdjustedClipLength = activeEvent.PrimarySource.pitch != 0 ? (audioClip.Sound.length / activeEvent.PrimarySource.pitch) : 0;
// Restrict non-Looping ActiveTime values to be non-negative.
return Mathf.Max(0.0f, pitchAdjustedClipLength + activeEvent.AudioEvent.InstanceTimeBuffer + additionalDelay);
}
}
}
}
| |
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2009 Oracle. All rights reserved.
*
*/
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections;
using System.Diagnostics;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using BerkeleyDB;
namespace ex_btrec {
class Program {
static void Main(string[] args) {
string dbFileName;
string dbName;
string wordFile;
/*
* ex_btrec is meant to be run from build_windows\AnyCPU, in either
* the Debug or Release directory. The required core libraries,
* however, are in either build_windows\Win32 or build_windows\x64,
* depending upon the platform. That location needs to be added to
* the PATH environment variable for the P/Invoke calls to work.
*/
try {
String pwd = Environment.CurrentDirectory;
pwd = Path.Combine(pwd, "..");
pwd = Path.Combine(pwd, "..");
if (IntPtr.Size == 4)
pwd = Path.Combine(pwd, "Win32");
else
pwd = Path.Combine(pwd, "x64");
#if DEBUG
pwd = Path.Combine(pwd, "Debug");
#else
pwd = Path.Combine(pwd, "Release");
#endif
pwd += ";" + Environment.GetEnvironmentVariable("PATH");
Environment.SetEnvironmentVariable("PATH", pwd);
} catch (Exception e) {
Console.WriteLine(
"Unable to set the PATH environment variable.");
Console.WriteLine(e.Message);
return;
}
try {
dbFileName = args[0];
dbName = args[1];
wordFile = args[2];
} catch {
usage();
return;
}
ex_csharp_btrec(dbFileName, dbName, wordFile);
}
public static int ex_csharp_btrec(string dbFileName,
string dbName, string wordFile) {
BTreeCursor dbc;
BTreeDatabase btreeDB;
BTreeDatabaseConfig btreeDBconfig;
DatabaseEntry key, data;
KeyValuePair<DatabaseEntry, DatabaseEntry> pair;
StreamReader wordList;
string buff;
char[] rbuff;
int i, j;
uint cnt;
string progName = "ex_csharp_btrec";
/* Check if word list exists. */
if (!File.Exists(wordFile)) {
Console.WriteLine("Cannot find {0}/{1}.",
Environment.CurrentDirectory, wordFile);
return (1);
}
/* Optionally remove the previous database. */
if (File.Exists(dbFileName)) {
while (true) {
Console.Write
("Database already exists, delete or not (y/n)?");
buff = Console.ReadLine();
if (buff == "y" || buff == "n")
break;
}
if (buff == "y") {
File.Delete(dbFileName);
Console.WriteLine("The existing {0} is deleted",
dbName);
}
}
/* Create and initialize database object, open the database. */
btreeDBconfig = new BTreeDatabaseConfig();
btreeDBconfig.Creation = CreatePolicy.IF_NEEDED;
btreeDBconfig.ErrorPrefix = progName;
btreeDBconfig.UseRecordNumbers = true;
try {
btreeDB = BTreeDatabase.Open(dbFileName, dbName,
btreeDBconfig);
} catch {
Console.WriteLine("Database can not be opened");
return (1);
}
/*
* Insert records into the database, where the key is the word
* preceded by its record number, and the data is the same,
* but in reverse order.
*/
key = new DatabaseEntry();
data = new DatabaseEntry();
wordList = new StreamReader(wordFile);
for (cnt = 1; cnt <= 1000; cnt++) {
/* Read one word from word list. */
try {
buff = wordList.ReadLine();
} catch {
Console.WriteLine("Error when reading word list");
btreeDB.Close();
wordList.Close();
return (1);
}
/*
* Prefix the word with record number and store
* them in key.
*/
try {
buff = cnt.ToString("0000") + buff;
} catch {
Console.WriteLine(
"Wrong format for record number.");
btreeDB.Close();
wordList.Close();
return (1);
}
dbtFromString(key, buff);
/* Reverse buff to rbuff and store them in data. */
rbuff = new char[buff.Length];
for (i = 0, j = buff.Length - 1; i < buff.Length; i++, j--)
rbuff[i] = buff[j];
dbtFromString(data, new string(rbuff));
/* Put the key/data pair into database. */
try {
btreeDB.PutNoOverwrite(key, data);
} catch {
Console.WriteLine("Put error with key::{0} and"
+ "data::{1}", buff, new string(rbuff));
btreeDB.Close();
wordList.Close();
return (1);
}
}
/* Close the word list. */
wordList.Close();
/* Acquire a cursor for the database. */
dbc = btreeDB.Cursor();
/*
* Input an available record number and get its
* corresponding key/data pair in the database.
*/
while (true) {
Console.WriteLine("Please input record number"
+ ", input 0 to stop");
while (true) {
Console.WriteLine("recno #:\t");
buff = Console.ReadLine();
try {
cnt = uint.Parse(buff);
break;
} catch {
Console.WriteLine("Invalid Record Number. "
+ "Try Again.");
}
}
if (cnt == 0)
break;
/*
* Position the cursor at a key/data pair in the database
* where the record number points to.
*/
if (!dbc.Move(cnt)) {
Console.WriteLine("No record is found");
break;
}
/* Get the current key/data pair and display them.*/
pair = dbc.Current;
Console.WriteLine("key::{0, 18:G} data::{1, 18:G}",
strFromDBT(pair.Key), strFromDBT(pair.Value));
/* Check if it's the right record number. */
if (dbc.Recno() != cnt) {
Console.WriteLine("The current record is not"
+ "the right one of the given record number.");
btreeDB.Close();
dbc.Close();
return (1);
}
/* Get the next record. */
if (!dbc.MoveNext()) {
Console.WriteLine(
"Next record is not found");
break;
}
/* Get the current key/data pair and display them.*/
pair = dbc.Current;
Console.WriteLine("key::{0, 18:G} data::{1, 18:G}\n",
strFromDBT(pair.Key), strFromDBT(pair.Value));
}
/* Close cursor and database. */
dbc.Close();
btreeDB.Close();
return (0);
}
#region Utilities
/* Show the usage. */
public static void usage() {
Console.WriteLine(
"Usage: [db file name] [db name] [word list file]");
}
/* Get dbt from string. */
static void dbtFromString(DatabaseEntry dbt, string s) {
dbt.Data = System.Text.Encoding.ASCII.GetBytes(s);
}
/* Get string from dbt. */
public static string strFromDBT(DatabaseEntry dbt) {
System.Text.ASCIIEncoding decode =
new ASCIIEncoding();
return decode.GetString(dbt.Data);
}
#endregion Utilities
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Reflection;
using Orleans.Runtime;
#if CLUSTERING_ADONET
namespace Orleans.Clustering.AdoNet.Storage
#elif PERSISTENCE_ADONET
namespace Orleans.Persistence.AdoNet.Storage
#elif REMINDERS_ADONET
namespace Orleans.Reminders.AdoNet.Storage
#elif TESTER_SQLUTILS
namespace Orleans.Tests.SqlUtils
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// This class implements the expected contract between Orleans and the underlying relational storage.
/// It makes sure all the stored queries are present and
/// </summary>
internal class DbStoredQueries
{
private readonly Dictionary<string, string> queries;
internal DbStoredQueries(Dictionary<string, string> queries)
{
var fields = typeof(DbStoredQueries).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)
.Select(p => p.Name);
var missingQueryKeys = fields.Except(queries.Keys).ToArray();
if (missingQueryKeys.Length > 0)
{
throw new ArgumentException(
$"Not all required queries found. Missing are: {string.Join(",", missingQueryKeys)}");
}
this.queries = queries;
}
/// <summary>
/// The query that's used to get all the stored queries.
/// this will probably be the same for all relational dbs.
/// </summary>
internal const string GetQueriesKey = "SELECT QueryKey, QueryText FROM OrleansQuery";
#if CLUSTERING_ADONET || TESTER_SQLUTILS
/// <summary>
/// A query template to retrieve gateway URIs.
/// </summary>
internal string GatewaysQueryKey => queries[nameof(GatewaysQueryKey)];
/// <summary>
/// A query template to retrieve a single row of membership data.
/// </summary>
internal string MembershipReadRowKey => queries[nameof(MembershipReadRowKey)];
/// <summary>
/// A query template to retrieve all membership data.
/// </summary>
internal string MembershipReadAllKey => queries[nameof(MembershipReadAllKey)];
/// <summary>
/// A query template to insert a membership version row.
/// </summary>
internal string InsertMembershipVersionKey => queries[nameof(InsertMembershipVersionKey)];
/// <summary>
/// A query template to update "I Am Alive Time".
/// </summary>
internal string UpdateIAmAlivetimeKey => queries[nameof(UpdateIAmAlivetimeKey)];
/// <summary>
/// A query template to insert a membership row.
/// </summary>
internal string InsertMembershipKey => queries[nameof(InsertMembershipKey)];
/// <summary>
/// A query template to update a membership row.
/// </summary>
internal string UpdateMembershipKey => queries[nameof(UpdateMembershipKey)];
/// <summary>
/// A query template to delete membership entries.
/// </summary>
internal string DeleteMembershipTableEntriesKey => queries[nameof(DeleteMembershipTableEntriesKey)];
#endif
#if REMINDERS_ADONET || TESTER_SQLUTILS
/// <summary>
/// A query template to read reminder entries.
/// </summary>
internal string ReadReminderRowsKey => queries[nameof(ReadReminderRowsKey)];
/// <summary>
/// A query template to read reminder entries with ranges.
/// </summary>
internal string ReadRangeRows1Key => queries[nameof(ReadRangeRows1Key)];
/// <summary>
/// A query template to read reminder entries with ranges.
/// </summary>
internal string ReadRangeRows2Key => queries[nameof(ReadRangeRows2Key)];
/// <summary>
/// A query template to read a reminder entry with ranges.
/// </summary>
internal string ReadReminderRowKey => queries[nameof(ReadReminderRowKey)];
/// <summary>
/// A query template to upsert a reminder row.
/// </summary>
internal string UpsertReminderRowKey => queries[nameof(UpsertReminderRowKey)];
/// <summary>
/// A query template to delete a reminder row.
/// </summary>
internal string DeleteReminderRowKey => queries[nameof(DeleteReminderRowKey)];
/// <summary>
/// A query template to delete all reminder rows.
/// </summary>
internal string DeleteReminderRowsKey => queries[nameof(DeleteReminderRowsKey)];
#endif
internal class Converters
{
internal static KeyValuePair<string, string> GetQueryKeyAndValue(IDataRecord record)
{
return new KeyValuePair<string, string>(record.GetValue<string>("QueryKey"),
record.GetValue<string>("QueryText"));
}
internal static ReminderEntry GetReminderEntry(IDataRecord record, GrainReferenceKeyStringConverter grainReferenceConverter)
{
//Having non-null field, GrainId, means with the query filter options, an entry was found.
string grainId = record.GetValueOrDefault<string>(nameof(Columns.GrainId));
if (grainId != null)
{
return new ReminderEntry
{
GrainRef = grainReferenceConverter.FromKeyString(grainId),
ReminderName = record.GetValue<string>(nameof(Columns.ReminderName)),
StartAt = record.GetDateTimeValue(nameof(Columns.StartTime)),
//Use the GetInt64 method instead of the generic GetValue<TValue> version to retrieve the value from the data record
//GetValue<int> causes an InvalidCastException with oracle data provider. See https://github.com/dotnet/orleans/issues/3561
Period = TimeSpan.FromMilliseconds(record.GetInt64(nameof(Columns.Period))),
ETag = GetVersion(record).ToString()
};
}
return null;
}
internal static Tuple<MembershipEntry, int> GetMembershipEntry(IDataRecord record)
{
//TODO: This is a bit of hack way to check in the current version if there's membership data or not, but if there's a start time, there's member.
DateTime? startTime = record.GetDateTimeValueOrDefault(nameof(Columns.StartTime));
MembershipEntry entry = null;
if (startTime.HasValue)
{
entry = new MembershipEntry
{
SiloAddress = GetSiloAddress(record, nameof(Columns.Port)),
SiloName = TryGetSiloName(record),
HostName = record.GetValue<string>(nameof(Columns.HostName)),
Status = (SiloStatus)Enum.Parse(typeof(SiloStatus), record.GetInt32(nameof(Columns.Status)).ToString()),
ProxyPort = record.GetInt32(nameof(Columns.ProxyPort)),
StartTime = startTime.Value,
IAmAliveTime = record.GetDateTimeValue(nameof(Columns.IAmAliveTime))
};
string suspectingSilos = record.GetValueOrDefault<string>(nameof(Columns.SuspectTimes));
if (!string.IsNullOrWhiteSpace(suspectingSilos))
{
entry.SuspectTimes = new List<Tuple<SiloAddress, DateTime>>();
entry.SuspectTimes.AddRange(suspectingSilos.Split('|').Select(s =>
{
var split = s.Split(',');
return new Tuple<SiloAddress, DateTime>(SiloAddress.FromParsableString(split[0]),
LogFormatter.ParseDate(split[1]));
}));
}
}
return Tuple.Create(entry, GetVersion(record));
}
/// <summary>
/// This method is for compatibility with membership tables that
/// do not contain a SiloName field
/// </summary>
private static string TryGetSiloName(IDataRecord record)
{
int pos;
try
{
pos = record.GetOrdinal(nameof(Columns.SiloName));
}
catch (IndexOutOfRangeException)
{
return null;
}
return (string)record.GetValue(pos);
}
internal static int GetVersion(IDataRecord record)
{
return Convert.ToInt32(record.GetValue<object>(nameof(Version)));
}
internal static Uri GetGatewayUri(IDataRecord record)
{
return GetSiloAddress(record, nameof(Columns.ProxyPort)).ToGatewayUri();
}
private static SiloAddress GetSiloAddress(IDataRecord record, string portName)
{
//Use the GetInt32 method instead of the generic GetValue<TValue> version to retrieve the value from the data record
//GetValue<int> causes an InvalidCastException with orcale data provider. See https://github.com/dotnet/orleans/issues/3561
int port = record.GetInt32(portName);
int generation = record.GetInt32(nameof(Columns.Generation));
string address = record.GetValue<string>(nameof(Columns.Address));
var siloAddress = SiloAddress.New(new IPEndPoint(IPAddress.Parse(address), port), generation);
return siloAddress;
}
internal static bool GetSingleBooleanValue(IDataRecord record)
{
if (record.FieldCount != 1) throw new InvalidOperationException("Expected a single column");
return Convert.ToBoolean(record.GetValue(0));
}
}
internal class Columns
{
private readonly IDbCommand command;
internal Columns(IDbCommand cmd)
{
command = cmd;
}
private void Add<T>(string paramName, T paramValue, DbType? dbType = null)
{
command.AddParameter(paramName, paramValue, dbType: dbType);
}
private void AddAddress(string name, IPAddress address)
{
Add(name, address.ToString(), dbType: DbType.AnsiString);
}
private void AddGrainHash(string name, uint grainHash)
{
Add(name, (int)grainHash);
}
internal string ClientId
{
set { Add(nameof(ClientId), value); }
}
internal int GatewayPort
{
set { Add(nameof(GatewayPort), value); }
}
internal IPAddress GatewayAddress
{
set { AddAddress(nameof(GatewayAddress), value); }
}
internal string SiloId
{
set { Add(nameof(SiloId), value); }
}
internal string Id
{
set { Add(nameof(Id), value); }
}
internal string Name
{
set { Add(nameof(Name), value); }
}
internal const string IsValueDelta = nameof(IsValueDelta);
internal const string StatValue = nameof(StatValue);
internal const string Statistic = nameof(Statistic);
internal SiloAddress SiloAddress
{
set
{
Address = value.Endpoint.Address;
Port = value.Endpoint.Port;
Generation = value.Generation;
}
}
internal int Generation
{
set { Add(nameof(Generation), value); }
}
internal int Port
{
set { Add(nameof(Port), value); }
}
internal uint BeginHash
{
set { AddGrainHash(nameof(BeginHash), value); }
}
internal uint EndHash
{
set { AddGrainHash(nameof(EndHash), value); }
}
internal uint GrainHash
{
set { AddGrainHash(nameof(GrainHash), value); }
}
internal DateTime StartTime
{
set { Add(nameof(StartTime), value); }
}
internal IPAddress Address
{
set { AddAddress(nameof(Address), value); }
}
internal string ServiceId
{
set { Add(nameof(ServiceId), value); }
}
internal string DeploymentId
{
set { Add(nameof(DeploymentId), value); }
}
internal string SiloName
{
set { Add(nameof(SiloName), value); }
}
internal string HostName
{
set { Add(nameof(HostName), value); }
}
internal string Version
{
set { Add(nameof(Version), int.Parse(value)); }
}
internal DateTime IAmAliveTime
{
set { Add(nameof(IAmAliveTime), value); }
}
internal string GrainId
{
set { Add(nameof(GrainId), value, dbType: DbType.AnsiString); }
}
internal string ReminderName
{
set { Add(nameof(ReminderName), value); }
}
internal TimeSpan Period
{
set {
if (value.TotalMilliseconds <= int.MaxValue)
{
// Original casting when old schema is used. Here to maintain backwards compatibility
Add(nameof(Period), (int)value.TotalMilliseconds);
}
else
{
Add(nameof(Period), (long)value.TotalMilliseconds);
}
}
}
internal SiloStatus Status
{
set { Add(nameof(Status), (int)value); }
}
internal int ProxyPort
{
set { Add(nameof(ProxyPort), value); }
}
internal List<Tuple<SiloAddress, DateTime>> SuspectTimes
{
set
{
Add(nameof(SuspectTimes), value == null
? null
: string.Join("|", value.Select(
s => $"{s.Item1.ToParsableString()},{LogFormatter.PrintDate(s.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.
/******************************************************************************
* 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 BlendUInt321()
{
var test = new ImmBinaryOpTest__BlendUInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.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 (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__BlendUInt321
{
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt321 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static ImmBinaryOpTest__BlendUInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ImmBinaryOpTest__BlendUInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendUInt321();
var result = Avx2.Blend(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((1 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (((1 & (1 << i)) == 0) ? left[i] : right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt32>(Vector256<UInt32>.1, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Buffers.Text
{
public static partial class Utf8Parser
{
//
// Parse an RFC1123 date string.
//
// 01234567890123456789012345678
// -----------------------------
// Tue, 03 Jan 2017 08:08:05 GMT
//
private static bool TryParseDateTimeOffsetR(ReadOnlySpan<byte> source, uint caseFlipXorMask, out DateTimeOffset dateTimeOffset, out int bytesConsumed)
{
if (source.Length < 29)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
DayOfWeek dayOfWeek;
{
uint dow0 = source[0] ^ caseFlipXorMask;
uint dow1 = source[1];
uint dow2 = source[2];
uint comma = source[3];
uint dowString = (dow0 << 24) | (dow1 << 16) | (dow2 << 8) | comma;
switch (dowString)
{
case 0x53756E2c /* 'Sun,' */: dayOfWeek = DayOfWeek.Sunday; break;
case 0x4d6f6e2c /* 'Mon,' */: dayOfWeek = DayOfWeek.Monday; break;
case 0x5475652c /* 'Tue,' */: dayOfWeek = DayOfWeek.Tuesday; break;
case 0x5765642c /* 'Wed,' */: dayOfWeek = DayOfWeek.Wednesday; break;
case 0x5468752c /* 'Thu,' */: dayOfWeek = DayOfWeek.Thursday; break;
case 0x4672692c /* 'Fri,' */: dayOfWeek = DayOfWeek.Friday; break;
case 0x5361742c /* 'Sat,' */: dayOfWeek = DayOfWeek.Saturday; break;
default:
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
}
if (source[4] != Utf8Constants.Space)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
int day;
{
uint digit1 = source[5] - 48u; // '0'
uint digit2 = source[6] - 48u; // '0'
if (digit1 > 9 || digit2 > 9)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
day = (int)(digit1 * 10 + digit2);
}
if (source[7] != Utf8Constants.Space)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
int month;
{
uint mon0 = source[8] ^ caseFlipXorMask;
uint mon1 = source[9];
uint mon2 = source[10];
uint space = source[11];
uint monthString = (mon0 << 24) | (mon1 << 16) | (mon2 << 8) | space;
switch (monthString)
{
case 0x4a616e20 /* 'Jan ' */ : month = 1; break;
case 0x46656220 /* 'Feb ' */ : month = 2; break;
case 0x4d617220 /* 'Mar ' */ : month = 3; break;
case 0x41707220 /* 'Apr ' */ : month = 4; break;
case 0x4d617920 /* 'May ' */ : month = 5; break;
case 0x4a756e20 /* 'Jun ' */ : month = 6; break;
case 0x4a756c20 /* 'Jul ' */ : month = 7; break;
case 0x41756720 /* 'Aug ' */ : month = 8; break;
case 0x53657020 /* 'Sep ' */ : month = 9; break;
case 0x4f637420 /* 'Oct ' */ : month = 10; break;
case 0x4e6f7620 /* 'Nov ' */ : month = 11; break;
case 0x44656320 /* 'Dec ' */ : month = 12; break;
default:
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
}
int year;
{
uint digit1 = source[12] - 48u; // '0'
uint digit2 = source[13] - 48u; // '0'
uint digit3 = source[14] - 48u; // '0'
uint digit4 = source[15] - 48u; // '0'
if (digit1 > 9 || digit2 > 9 || digit3 > 9 || digit4 > 9)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
year = (int)(digit1 * 1000 + digit2 * 100 + digit3 * 10 + digit4);
}
if (source[16] != Utf8Constants.Space)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
int hour;
{
uint digit1 = source[17] - 48u; // '0'
uint digit2 = source[18] - 48u; // '0'
if (digit1 > 9 || digit2 > 9)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
hour = (int)(digit1 * 10 + digit2);
}
if (source[19] != Utf8Constants.Colon)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
int minute;
{
uint digit1 = source[20] - 48u; // '0'
uint digit2 = source[21] - 48u; // '0'
if (digit1 > 9 || digit2 > 9)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
minute = (int)(digit1 * 10 + digit2);
}
if (source[22] != Utf8Constants.Colon)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
int second;
{
uint digit1 = source[23] - 48u; // '0'
uint digit2 = source[24] - 48u; // '0'
if (digit1 > 9 || digit2 > 9)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
second = (int)(digit1 * 10 + digit2);
}
{
uint space = source[25];
uint g = source[26] ^ caseFlipXorMask;
uint m = source[27] ^ caseFlipXorMask;
uint t = source[28] ^ caseFlipXorMask;
uint gmtString = (space << 24) | (g << 16) | (m << 8) | t;
if (gmtString != 0x20474d54 /* ' GMT' */)
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
}
if (!TryCreateDateTimeOffset(year: year, month: month, day: day, hour: hour, minute: minute, second: second, fraction: 0, offsetNegative: false, offsetHours: 0, offsetMinutes: 0, out dateTimeOffset))
{
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
if (dayOfWeek != dateTimeOffset.DayOfWeek)
{
// If we got here, the day of week did not match the actual date.
bytesConsumed = 0;
dateTimeOffset = default;
return false;
}
bytesConsumed = 29;
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Xml;
using System.Globalization;
using System.Collections.Generic;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public class XmlReaderDelegator
#else
internal class XmlReaderDelegator
#endif
{
protected XmlReader reader;
protected XmlDictionaryReader dictionaryReader;
protected bool isEndOfEmptyElement = false;
public XmlReaderDelegator(XmlReader reader)
{
XmlObjectSerializer.CheckNull(reader, "reader");
this.reader = reader;
this.dictionaryReader = reader as XmlDictionaryReader;
}
internal XmlReader UnderlyingReader
{
get { return reader; }
}
internal int AttributeCount
{
get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; }
}
internal string GetAttribute(string name)
{
return isEndOfEmptyElement ? null : reader.GetAttribute(name);
}
internal string GetAttribute(string name, string namespaceUri)
{
return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri);
}
internal string GetAttribute(int i)
{
if (isEndOfEmptyElement)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.Format(SR.XmlElementAttributes)));
return reader.GetAttribute(i);
}
internal bool IsEmptyElement
{
get { return false; }
}
internal bool IsNamespaceURI(string ns)
{
if (dictionaryReader == null)
return ns == reader.NamespaceURI;
else
return dictionaryReader.IsNamespaceUri(ns);
}
internal bool IsLocalName(string localName)
{
if (dictionaryReader == null)
return localName == reader.LocalName;
else
return dictionaryReader.IsLocalName(localName);
}
internal bool IsNamespaceUri(XmlDictionaryString ns)
{
if (dictionaryReader == null)
return ns.Value == reader.NamespaceURI;
else
return dictionaryReader.IsNamespaceUri(ns);
}
internal bool IsLocalName(XmlDictionaryString localName)
{
if (dictionaryReader == null)
return localName.Value == reader.LocalName;
else
return dictionaryReader.IsLocalName(localName);
}
internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns)
{
if (dictionaryReader != null)
return dictionaryReader.IndexOfLocalName(localNames, ns);
if (reader.NamespaceURI == ns.Value)
{
string localName = this.LocalName;
for (int i = 0; i < localNames.Length; i++)
{
if (localName == localNames[i].Value)
{
return i;
}
}
}
return -1;
}
#if USE_REFEMIT
public bool IsStartElement()
#else
internal bool IsStartElement()
#endif
{
return !isEndOfEmptyElement && reader.IsStartElement();
}
internal bool IsStartElement(string localname, string ns)
{
return !isEndOfEmptyElement && reader.IsStartElement(localname, ns);
}
#if USE_REFEMIT
public bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
#else
internal bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
#endif
{
if (dictionaryReader == null)
return !isEndOfEmptyElement && reader.IsStartElement(localname.Value, ns.Value);
else
return !isEndOfEmptyElement && dictionaryReader.IsStartElement(localname, ns);
}
internal bool MoveToAttribute(string name)
{
return isEndOfEmptyElement ? false : reader.MoveToAttribute(name);
}
internal bool MoveToAttribute(string name, string ns)
{
return isEndOfEmptyElement ? false : reader.MoveToAttribute(name, ns);
}
internal void MoveToAttribute(int i)
{
if (isEndOfEmptyElement)
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("i", SR.Format(SR.XmlElementAttributes)));
reader.MoveToAttribute(i);
}
internal bool MoveToElement()
{
return isEndOfEmptyElement ? false : reader.MoveToElement();
}
internal bool MoveToFirstAttribute()
{
return isEndOfEmptyElement ? false : reader.MoveToFirstAttribute();
}
internal bool MoveToNextAttribute()
{
return isEndOfEmptyElement ? false : reader.MoveToNextAttribute();
}
#if USE_REFEMIT
public XmlNodeType NodeType
#else
internal XmlNodeType NodeType
#endif
{
get { return isEndOfEmptyElement ? XmlNodeType.EndElement : reader.NodeType; }
}
internal bool Read()
{
//reader.MoveToFirstAttribute();
//if (NodeType == XmlNodeType.Attribute)
reader.MoveToElement();
if (!reader.IsEmptyElement)
return reader.Read();
if (isEndOfEmptyElement)
{
isEndOfEmptyElement = false;
return reader.Read();
}
isEndOfEmptyElement = true;
return true;
}
internal XmlNodeType MoveToContent()
{
if (isEndOfEmptyElement)
return XmlNodeType.EndElement;
return reader.MoveToContent();
}
internal bool ReadAttributeValue()
{
return isEndOfEmptyElement ? false : reader.ReadAttributeValue();
}
#if USE_REFEMIT
public void ReadEndElement()
#else
internal void ReadEndElement()
#endif
{
if (isEndOfEmptyElement)
Read();
else
reader.ReadEndElement();
}
private void ThrowConversionException(string value, string type)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type))));
}
private void ThrowNotAtElement()
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement")));
}
#if USE_REFEMIT
public virtual char ReadElementContentAsChar()
#else
internal virtual char ReadElementContentAsChar()
#endif
{
return ToChar(ReadElementContentAsInt());
}
private char ToChar(int value)
{
if (value < char.MinValue || value > char.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Char");
}
return (char)value;
}
#if USE_REFEMIT
public string ReadElementContentAsString()
#else
internal string ReadElementContentAsString()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsString();
}
internal string ReadContentAsString()
{
return isEndOfEmptyElement ? String.Empty : reader.ReadContentAsString();
}
#if USE_REFEMIT
public bool ReadElementContentAsBoolean()
#else
internal bool ReadElementContentAsBoolean()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsBoolean();
}
internal bool ReadContentAsBoolean()
{
if (isEndOfEmptyElement)
ThrowConversionException(string.Empty, "Boolean");
return reader.ReadContentAsBoolean();
}
#if USE_REFEMIT
public float ReadElementContentAsFloat()
#else
internal float ReadElementContentAsFloat()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsFloat();
}
#if USE_REFEMIT
public double ReadElementContentAsDouble()
#else
internal double ReadElementContentAsDouble()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsDouble();
}
#if USE_REFEMIT
public decimal ReadElementContentAsDecimal()
#else
internal decimal ReadElementContentAsDecimal()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsDecimal();
}
#if USE_REFEMIT
public virtual byte[] ReadElementContentAsBase64()
#else
internal virtual byte[] ReadElementContentAsBase64()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
if (dictionaryReader == null)
{
return ReadContentAsBase64(reader.ReadElementContentAsString());
}
else
{
return dictionaryReader.ReadElementContentAsBase64();
}
}
internal byte[] ReadContentAsBase64(string str)
{
if (str == null)
return null;
str = str.Trim();
if (str.Length == 0)
return Array.Empty<byte>();
try
{
return Convert.FromBase64String(str);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception));
}
}
#if USE_REFEMIT
public virtual DateTime ReadElementContentAsDateTime()
#else
internal virtual DateTime ReadElementContentAsDateTime()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
}
#if USE_REFEMIT
public int ReadElementContentAsInt()
#else
internal int ReadElementContentAsInt()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsInt();
}
internal int ReadContentAsInt()
{
if (isEndOfEmptyElement)
ThrowConversionException(string.Empty, "Int32");
return reader.ReadContentAsInt();
}
#if USE_REFEMIT
public long ReadElementContentAsLong()
#else
internal long ReadElementContentAsLong()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
return reader.ReadElementContentAsLong();
}
#if USE_REFEMIT
public short ReadElementContentAsShort()
#else
internal short ReadElementContentAsShort()
#endif
{
return ToShort(ReadElementContentAsInt());
}
private short ToShort(int value)
{
if (value < short.MinValue || value > short.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Int16");
}
return (short)value;
}
#if USE_REFEMIT
public byte ReadElementContentAsUnsignedByte()
#else
internal byte ReadElementContentAsUnsignedByte()
#endif
{
return ToByte(ReadElementContentAsInt());
}
private byte ToByte(int value)
{
if (value < byte.MinValue || value > byte.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte");
}
return (byte)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public SByte ReadElementContentAsSignedByte()
#else
internal SByte ReadElementContentAsSignedByte()
#endif
{
return ToSByte(ReadElementContentAsInt());
}
private SByte ToSByte(int value)
{
if (value < SByte.MinValue || value > SByte.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "SByte");
}
return (SByte)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public UInt32 ReadElementContentAsUnsignedInt()
#else
internal UInt32 ReadElementContentAsUnsignedInt()
#endif
{
return ToUInt32(ReadElementContentAsLong());
}
private UInt32 ToUInt32(long value)
{
if (value < UInt32.MinValue || value > UInt32.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt32");
}
return (UInt32)value;
}
#if USE_REFEMIT
[CLSCompliant(false)]
public virtual UInt64 ReadElementContentAsUnsignedLong()
#else
internal virtual UInt64 ReadElementContentAsUnsignedLong()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
if (str == null || str.Length == 0)
ThrowConversionException(string.Empty, "UInt64");
return XmlConverter.ToUInt64(str);
}
#if USE_REFEMIT
[CLSCompliant(false)]
public UInt16 ReadElementContentAsUnsignedShort()
#else
internal UInt16 ReadElementContentAsUnsignedShort()
#endif
{
return ToUInt16(ReadElementContentAsInt());
}
private UInt16 ToUInt16(int value)
{
if (value < UInt16.MinValue || value > UInt16.MaxValue)
{
ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt16");
}
return (UInt16)value;
}
#if USE_REFEMIT
public TimeSpan ReadElementContentAsTimeSpan()
#else
internal TimeSpan ReadElementContentAsTimeSpan()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
return XmlConverter.ToTimeSpan(str);
}
#if USE_REFEMIT
public Guid ReadElementContentAsGuid()
#else
internal Guid ReadElementContentAsGuid()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = reader.ReadElementContentAsString();
try
{
return new Guid(str);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
catch (OverflowException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception));
}
}
#if USE_REFEMIT
public Uri ReadElementContentAsUri()
#else
internal Uri ReadElementContentAsUri()
#endif
{
if (isEndOfEmptyElement)
ThrowNotAtElement();
string str = ReadElementContentAsString();
try
{
return new Uri(str, UriKind.RelativeOrAbsolute);
}
catch (ArgumentException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception));
}
}
#if USE_REFEMIT
public XmlQualifiedName ReadElementContentAsQName()
#else
internal XmlQualifiedName ReadElementContentAsQName()
#endif
{
Read();
XmlQualifiedName obj = ReadContentAsQName();
ReadEndElement();
return obj;
}
internal virtual XmlQualifiedName ReadContentAsQName()
{
return ParseQualifiedName(ReadContentAsString());
}
private XmlQualifiedName ParseQualifiedName(string str)
{
string name, ns, prefix;
if (str == null || str.Length == 0)
name = ns = String.Empty;
else
XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix);
return new XmlQualifiedName(name, ns);
}
private void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength)
{
context.IncrementItemCount(arrayLength);
}
protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context)
{
return Math.Min(context.RemainingItemCount, int.MaxValue);
}
private void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace)
{
if (expectedLength != actualLength)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, expectedLength, itemName.Value, itemNamespace.Value)));
}
#if USE_REFEMIT
public bool TryReadBooleanArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out bool[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new bool[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = BooleanArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDateTimeArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out DateTime[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new DateTime[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DateTimeArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDecimalArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out decimal[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new decimal[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DecimalArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadInt32Array(XmlObjectSerializerReadContext context,
#else
internal bool TryReadInt32Array(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out int[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new int[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = Int32ArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadInt64Array(XmlObjectSerializerReadContext context,
#else
internal bool TryReadInt64Array(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out long[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new long[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = Int64ArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadSingleArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadSingleArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out float[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new float[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = SingleArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
#if USE_REFEMIT
public bool TryReadDoubleArray(XmlObjectSerializerReadContext context,
#else
internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context,
#endif
XmlDictionaryString itemName, XmlDictionaryString itemNamespace,
int arrayLength, out double[] array)
{
if (dictionaryReader == null)
{
array = null;
return false;
}
if (arrayLength != -1)
{
CheckExpectedArrayLength(context, arrayLength);
array = new double[arrayLength];
int read = 0, offset = 0;
while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0)
{
offset += read;
}
CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace);
}
else
{
array = DoubleArrayHelperWithDictionaryString.Instance.ReadArray(
dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context));
context.IncrementItemCount(array.Length);
}
return true;
}
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null;
}
// IXmlLineInfo members
internal bool HasLineInfo()
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo();
}
internal int LineNumber
{
get
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber;
}
}
internal int LinePosition
{
get
{
IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo;
return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition;
}
}
// IXmlTextParser members
// delegating properties and methods
internal string Name { get { return reader.Name; } }
internal string LocalName { get { return reader.LocalName; } }
internal string NamespaceURI { get { return reader.NamespaceURI; } }
internal string Value { get { return reader.Value; } }
internal Type ValueType { get { return reader.ValueType; } }
internal int Depth { get { return reader.Depth; } }
internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); }
internal bool EOF { get { return reader.EOF; } }
internal void Skip()
{
reader.Skip();
isEndOfEmptyElement = false;
}
}
}
| |
/*
Matali Physics Demo
Copyright (c) 2013 KOMIRES Sp. z o. o.
*/
using System;
using System.Collections.Generic;
using OpenTK;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using Komires.MataliPhysics;
namespace MataliPhysicsDemo
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Boat1Animation1
{
Demo demo;
PhysicsScene scene;
string instanceIndexName;
string cameraBodyName;
string cameraDownName;
string cameraConstraintName;
PhysicsObject bodyBox0;
PhysicsObject engineSwitch;
Constraint constraint1;
Constraint constraint2;
PhysicsObject engine;
PhysicsObject engineRotor;
DemoKeyboardState oldKeyboardState;
bool enableExternalMoving;
Vector3 driverLocalPosition;
Vector3 position;
Matrix4 rotation;
Vector3 velocity;
Quaternion objectOrientation;
Matrix4 objectRotation;
Matrix4 objectInitRotation;
Vector3 position1;
Quaternion orientation1;
Quaternion orientation2;
Vector3 vectorZero;
Matrix4 matrixIdentity;
Quaternion quaternionIdentity;
Vector3 unitZ;
public Boat1Animation1(Demo demo, int instanceIndex)
{
this.demo = demo;
instanceIndexName = " " + instanceIndex.ToString();
cameraBodyName = "Camera 2 Body";
cameraDownName = "Camera 2 Down";
cameraConstraintName = "Boat 1 Camera Constraint" + instanceIndexName;
driverLocalPosition = new Vector3(0.0f, 4.3f, -11.0f);
vectorZero = Vector3.Zero;
matrixIdentity = Matrix4.Identity;
quaternionIdentity = Quaternion.Identity;
unitZ = Vector3.UnitZ;
}
public void Initialize(PhysicsScene scene)
{
this.scene = scene;
}
public void SetControllers(bool enableExternalMoving)
{
bodyBox0 = scene.Factory.PhysicsObjectManager.Find("Boat 1 Body Box 0" + instanceIndexName);
engineSwitch = scene.Factory.PhysicsObjectManager.Find("Boat 1 Engine Switch" + instanceIndexName);
constraint1 = scene.Factory.ConstraintManager.Find("Boat 1 Constraint 1" + instanceIndexName);
constraint2 = scene.Factory.ConstraintManager.Find("Boat 1 Constraint 2" + instanceIndexName);
engine = scene.Factory.PhysicsObjectManager.Find("Boat 1 Engine" + instanceIndexName);
engineRotor = scene.Factory.PhysicsObjectManager.Find("Boat 1 Engine Rotor" + instanceIndexName);
oldKeyboardState = demo.GetKeyboardState();
this.enableExternalMoving = enableExternalMoving;
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Boat 1 Body" + instanceIndexName);
if (objectBase != null)
objectBase.UserControllers.PostTransformMethods += new SimulateMethod(Move);
}
void Move(SimulateMethodArgs args)
{
PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex);
PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex);
float time = args.Time;
PhysicsObject physicsObjectWithActiveCamera = scene.GetPhysicsObjectWithActiveCamera(0);
if (physicsObjectWithActiveCamera == null) return;
PhysicsObject cameraBody = physicsObjectWithActiveCamera.RigidGroupOwner.FindChildPhysicsObject(cameraBodyName, true, true);
PhysicsObject cameraDown = physicsObjectWithActiveCamera.RigidGroupOwner.FindChildPhysicsObject(cameraDownName, true, true);
if ((bodyBox0 == null) || (engineSwitch == null) || (cameraBody == null) || (cameraDown == null)) return;
Constraint CameraConstraint = objectBase.Scene.Factory.ConstraintManager.Find(cameraConstraintName);
bool rotorWorking = true;
if (constraint2 != null)
{
if (constraint2.PhysicsObject1 != null)
if (constraint2.PhysicsObject1.IsBrokenRigidGroup || constraint2.IsBroken)
rotorWorking = false;
if (constraint2.PhysicsObject2 != null)
if (constraint2.PhysicsObject2.IsBrokenRigidGroup || constraint2.IsBroken)
rotorWorking = false;
}
else
{
rotorWorking = false;
}
if (objectBase.IsBrokenRigidGroup || !rotorWorking)
{
if (constraint1 != null)
constraint1.EnableControlAngleY = false;
if ((CameraConstraint != null) && (CameraConstraint.PhysicsObject1 == cameraDown))
{
objectBase.Scene.Factory.ConstraintManager.Remove(CameraConstraint);
physicsObjectWithActiveCamera.Camera.EnableControl = false;
cameraDown.RigidGroupOwner.MaxPreUpdateAngularVelocity = 0.0f;
cameraDown.RigidGroupOwner.MaxPostUpdateAngularVelocity = 0.0f;
Vector3 euler = vectorZero;
Vector3 cameraEuler = vectorZero;
Vector3 objectEuler = vectorZero;
physicsObjectWithActiveCamera.Camera.GetEuler(ref cameraEuler);
physicsObjectWithActiveCamera.MainWorldTransform.GetTransposeRotation(ref objectRotation);
physicsObjectWithActiveCamera.InitLocalTransform.GetRotation(ref objectInitRotation);
Matrix4.Mult(ref objectRotation, ref objectInitRotation, out rotation);
physicsObjectWithActiveCamera.Camera.SetEuler(ref rotation);
physicsObjectWithActiveCamera.Camera.GetEuler(ref objectEuler);
Vector3.Add(ref objectEuler, ref cameraEuler, out euler);
Matrix4 rotationX, rotationY;
Matrix4.CreateRotationX(-euler.X, out rotationX);
Matrix4.CreateRotationY(-euler.Y, out rotationY);
Matrix4.Mult(ref rotationY, ref rotationX, out rotation);
physicsObjectWithActiveCamera.Camera.SetEuler(ref euler);
physicsObjectWithActiveCamera.Camera.SetRotation(ref rotation);
Matrix4.CreateRotationY(euler.Y, out rotation);
physicsObjectWithActiveCamera.RigidGroupOwner.MainWorldTransform.SetRotation(ref rotation);
physicsObjectWithActiveCamera.RigidGroupOwner.RecalculateMainTransform();
}
return;
}
DemoKeyboardState keyboardState = demo.GetKeyboardState();
if (physicsObjectWithActiveCamera.Camera.EnableControl && (CameraConstraint != null) && (CameraConstraint.PhysicsObject1 == cameraDown))
{
if (keyboardState[Key.Space] && !oldKeyboardState[Key.Space])
{
if (constraint1 != null)
constraint1.EnableControlAngleY = false;
objectBase.Scene.Factory.ConstraintManager.Remove(CameraConstraint);
physicsObjectWithActiveCamera.Camera.EnableControl = false;
cameraDown.RigidGroupOwner.MaxPreUpdateAngularVelocity = 0.0f;
cameraDown.RigidGroupOwner.MaxPostUpdateAngularVelocity = 0.0f;
Vector3 euler = vectorZero;
Vector3 cameraEuler = vectorZero;
Vector3 objectEuler = vectorZero;
physicsObjectWithActiveCamera.Camera.GetEuler(ref cameraEuler);
physicsObjectWithActiveCamera.MainWorldTransform.GetTransposeRotation(ref objectRotation);
physicsObjectWithActiveCamera.InitLocalTransform.GetRotation(ref objectInitRotation);
Matrix4.Mult(ref objectRotation, ref objectInitRotation, out rotation);
physicsObjectWithActiveCamera.Camera.SetEuler(ref rotation);
physicsObjectWithActiveCamera.Camera.GetEuler(ref objectEuler);
Vector3.Add(ref objectEuler, ref cameraEuler, out euler);
euler.Z = 0.0f;
Matrix4 rotationX, rotationY;
Matrix4.CreateRotationX(-euler.X, out rotationX);
Matrix4.CreateRotationY(-euler.Y, out rotationY);
Matrix4.Mult(ref rotationY, ref rotationX, out rotation);
physicsObjectWithActiveCamera.Camera.SetEuler(ref euler);
physicsObjectWithActiveCamera.Camera.SetRotation(ref rotation);
Matrix4.CreateRotationY(euler.Y, out rotation);
physicsObjectWithActiveCamera.RigidGroupOwner.MainWorldTransform.SetRotation(ref rotation);
physicsObjectWithActiveCamera.RigidGroupOwner.RecalculateMainTransform();
oldKeyboardState = keyboardState;
return;
}
if (keyboardState[Key.W])
{
if ((engine != null) && (engineRotor != null))
{
Vector3.Multiply(ref unitZ, -10.0f, out velocity);
engineRotor.MainWorldTransform.SetLocalAngularVelocity(ref velocity);
if (engineRotor.IsUnderFluidSurface)
{
Vector3.Multiply(ref unitZ, 5.0f, out velocity);
engine.MainWorldTransform.AddLocalLinearVelocity(ref velocity);
}
}
}
if (keyboardState[Key.S])
{
if ((engine != null) && (engineRotor != null))
{
Vector3.Multiply(ref unitZ, 10.0f, out velocity);
engineRotor.MainWorldTransform.SetLocalAngularVelocity(ref velocity);
if (engineRotor.IsUnderFluidSurface)
{
Vector3.Multiply(ref unitZ, -5.0f, out velocity);
engine.MainWorldTransform.AddLocalLinearVelocity(ref velocity);
}
}
}
if (keyboardState[Key.D])
{
if (constraint1 != null)
constraint1.ControlDegAngleY += 0.5f;
}
if (keyboardState[Key.A])
{
if (constraint1 != null)
constraint1.ControlDegAngleY -= 0.5f;
}
}
else
{
if (constraint1 != null)
constraint1.EnableControlAngleY = false;
if (engineSwitch.IsColliding(cameraBody))
{
if (keyboardState[Key.Space] && !oldKeyboardState[Key.Space])
{
physicsObjectWithActiveCamera.Camera.EnableControl = true;
if (constraint1 != null)
constraint1.EnableControlAngleY = true;
constraint1.ControlDegAngleY = 0.0f;
cameraDown.RigidGroupOwner.MaxPreUpdateAngularVelocity = 1000.0f;
cameraDown.RigidGroupOwner.MaxPostUpdateAngularVelocity = 1000.0f;
Quaternion cameraOrientationX = quaternionIdentity;
Quaternion cameraOrientationY = quaternionIdentity;
Quaternion cameraOrientationZ = quaternionIdentity;
Quaternion cameraOrientationXY = quaternionIdentity;
Quaternion cameraOrientation = quaternionIdentity;
Quaternion.Multiply(ref cameraOrientationX, ref cameraOrientationY, out cameraOrientationXY);
Quaternion.Multiply(ref cameraOrientationXY, ref cameraOrientationZ, out cameraOrientation);
rotation = Matrix4.CreateFromQuaternion(cameraOrientation);
physicsObjectWithActiveCamera.Camera.SetOrientation(ref cameraOrientation);
physicsObjectWithActiveCamera.Camera.SetRotation(ref rotation);
physicsObjectWithActiveCamera.Camera.SetEuler(ref rotation);
objectOrientation = quaternionIdentity;
objectRotation = Matrix4.CreateFromQuaternion(objectOrientation);
Vector3 boatDeckPosition = vectorZero;
Matrix4 boatDeckRotation = matrixIdentity;
bodyBox0.MainWorldTransform.GetPosition(ref boatDeckPosition);
bodyBox0.MainWorldTransform.GetRotation(ref boatDeckRotation);
Matrix4.Mult(ref objectRotation, ref boatDeckRotation, out rotation);
Vector3.TransformVector(ref driverLocalPosition, ref boatDeckRotation, out position);
Vector3.Add(ref boatDeckPosition, ref position, out position);
physicsObjectWithActiveCamera.RigidGroupOwner.MainWorldTransform.SetRotation(ref rotation);
physicsObjectWithActiveCamera.RigidGroupOwner.MainWorldTransform.SetPosition(ref position);
physicsObjectWithActiveCamera.RigidGroupOwner.RecalculateMainTransform();
if (CameraConstraint == null)
{
CameraConstraint = scene.Factory.ConstraintManager.Create(cameraConstraintName);
CameraConstraint.PhysicsObject1 = cameraDown;
CameraConstraint.PhysicsObject2 = bodyBox0;
CameraConstraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1);
CameraConstraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1);
CameraConstraint.PhysicsObject2.MainWorldTransform.GetOrientation(ref orientation2);
boatDeckPosition.X = boatDeckPosition.Z = 0.0f;
boatDeckPosition.Y = 2.0f;
Vector3.Subtract(ref position1, ref boatDeckPosition, out position1);
CameraConstraint.SetAnchor1(ref position1);
CameraConstraint.SetAnchor2(ref position1);
CameraConstraint.SetInitWorldOrientation1(ref orientation1);
CameraConstraint.SetInitWorldOrientation2(ref orientation2);
CameraConstraint.EnableLimitAngleX = true;
CameraConstraint.EnableLimitAngleY = true;
CameraConstraint.EnableLimitAngleZ = true;
CameraConstraint.LimitAngleForce = 0.6f;
CameraConstraint.Update();
}
}
}
if (enableExternalMoving)
{
if (keyboardState[Key.Up])
{
if (constraint1 != null)
constraint1.EnableControlAngleY = true;
if ((engine != null) && (engineRotor != null))
{
Vector3.Multiply(ref unitZ, -10.0f, out velocity);
engineRotor.MainWorldTransform.SetLocalAngularVelocity(ref velocity);
if (engineRotor.IsUnderFluidSurface)
{
Vector3.Multiply(ref unitZ, 5.0f, out velocity);
engine.MainWorldTransform.AddLocalLinearVelocity(ref velocity);
}
}
}
if (keyboardState[Key.Down])
{
if (constraint1 != null)
constraint1.EnableControlAngleY = true;
if ((engine != null) && (engineRotor != null))
{
Vector3.Multiply(ref unitZ, 10.0f, out velocity);
engineRotor.MainWorldTransform.SetLocalAngularVelocity(ref velocity);
if (engineRotor.IsUnderFluidSurface)
{
Vector3.Multiply(ref unitZ, -5.0f, out velocity);
engine.MainWorldTransform.AddLocalLinearVelocity(ref velocity);
}
}
}
if (keyboardState[Key.Right])
{
if (constraint1 != null)
constraint1.EnableControlAngleY = true;
if (constraint1 != null)
constraint1.ControlDegAngleY += 0.5f;
}
if (keyboardState[Key.Left])
{
if (constraint1 != null)
constraint1.EnableControlAngleY = true;
if (constraint1 != null)
constraint1.ControlDegAngleY -= 0.5f;
}
}
}
oldKeyboardState = keyboardState;
}
}
}
| |
using System;
using System.Collections.Generic;
using CocosSharp;
using Microsoft.Xna.Framework;
using PilotAndGunPortable.Classes;
namespace PilotAndGunPortable
{
public class GameLayer : CCLayerColor
{
private const string SCORE_CONTENT = "Score: ";
private const float PLAYER_SHOOTING_INTEVAL = 0.5f;
private const float ENEMY_SHOOTING_INTERVAL = 2f;
private const float ENEMY_BULLET_SPEED = 300f;
private const int NO_OF_ENEMIES_IN_A_BATCH = 5;
private const int BACKGROUND_INDEX = 0;
private const int SCORE_INDEX = 1;
private const int HEALTH_BAR_INDEX = 1;
private const int PAUSE_BUTTON_INDEX = 50;
private const int ENEMY_INDEX = 10;
private const int PLAYER_INDEX = 10;
private const int PLAYER_BULLET_INDEX = 2;
private const int ENEMY_BULLET_INDEX = 2;
int noOfBatch;
long score = 0;
CCLabel lblScore;
Player player;
PlayerHealthBar healthBar;
List<CCSprite> visibleEnemies = new List<CCSprite>();
List<EnemyBullet> visileEnemyBullets = new List<EnemyBullet>();
List<PlayerBullet> visiblePlayerBullets = new List<PlayerBullet>();
private float rightBoundX;
private float leftBoundX;
CCCallFuncN moveOutOfView = new CCCallFuncN(node => node.RemoveFromParent());
Random random = new Random();
CCMenu mnuPause;
CCMenuItemImage mniPause;
CCParallaxNode parallaxBackground;
public GameLayer() : base(CCColor4B.Black)
{
player = new Player();
AddChild(player, PLAYER_INDEX);
healthBar = new PlayerHealthBar();
AddChild(healthBar, HEALTH_BAR_INDEX);
lblScore = new CCLabel(SCORE_CONTENT + score, "Fonts/MarkerFelt", 22, CCLabelFormat.SpriteFont);
lblScore.AnchorPoint = new CCPoint(0f, 1f);
lblScore.Schedule(s => { lblScore.Text = SCORE_CONTENT + score; });
AddChild(lblScore, SCORE_INDEX);
mniPause = new CCMenuItemImage(new CCSprite("btnPause.png"), new CCSprite("btnPauseSelected.png"), delegate (object obj)
{
//GameView.Paused = !GameView.Paused;
});
mnuPause = new CCMenu(new CCMenuItem[] { mniPause });
mnuPause.AlignItemsVertically();
mnuPause.AnchorPoint = CCPoint.AnchorUpperRight;
AddChild(mnuPause, PAUSE_BUTTON_INDEX);
//check collision
Schedule(s => CheckCollision());
//player shoots bullets
Schedule(s => visiblePlayerBullets.Add(AddPlayerBullet()), PLAYER_SHOOTING_INTEVAL);
//spawn enemies
Schedule(s => SpawnEnemies(), 2f);
}
private void AddBackground()
{
float h = VisibleBoundsWorldspace.Size.Height;
parallaxBackground = new CCParallaxNode { Position = new CCPoint(0, h) };
AddChild(parallaxBackground, BACKGROUND_INDEX);
var bg = new CCSprite("gameBg.png");
parallaxBackground.AddChild(bg, 0, new CCPoint(1f, 0), new CCPoint(bg.ContentSize.Width / 2, bg.ContentSize.Height / 2));
}
private void RemoveNoParentNodes()
{
//remove invisible nodes
visiblePlayerBullets.RemoveAll(spr => spr.Parent == null);
visibleEnemies.RemoveAll(spr => spr.Parent == null);
visileEnemyBullets.RemoveAll(spr => spr.Parent == null);
}
private void Explode(CCPoint position)
{
var explosion = new CCParticleExplosion(position);
explosion.TotalParticles = 10;
explosion.AutoRemoveOnFinish = true;
AddChild(explosion);
}
private void CheckCollision()
{
RemoveNoParentNodes();
//check if player intersects with enemy bullets
foreach (EnemyBullet eb in visileEnemyBullets)
{
bool hit = eb.BoundingBoxTransformedToParent.IntersectsRect(player.BoundingBoxTransformedToParent);
if (hit)
{
Explode(eb.Position);
eb.RemoveFromParent();
healthBar.Decrease(eb.Damage);
}
}
//check if player intersects with enemies
foreach (CCSprite enemy in visibleEnemies)
{
bool hit = enemy.BoundingBoxTransformedToParent.IntersectsRect(player.BoundingBoxTransformedToParent);
if (hit)
{
Explode(enemy.Position);
Explode(player.Position);
enemy.RemoveFromParent();
healthBar.Decrease(1);
}
}
//check if enemies intersects with player bullets
foreach (PlayerBullet pb in visiblePlayerBullets)
{
foreach (CCSprite enemy in visibleEnemies)
{
bool hit = pb.BoundingBoxTransformedToParent.IntersectsRect(enemy.BoundingBoxTransformedToParent);
if (hit)
{
Explode(pb.Position);
pb.RemoveFromParent();
if (enemy is Enemy)
{
enemy.RemoveFromParent();
score += (enemy as Enemy).Score;
}
else
{
Boss b = enemy as Boss;
b.HealthBar.Decrease(1);
if (b.HealthBar.Health == 0)
{
b.RemoveFromParent();
score += b.Score;
}
}
}
}
}
//check GAME END
if (healthBar.Health == 0)
GameView.Director.PushScene(ScoreLayer.ScoreScene(GameView));
RemoveNoParentNodes();
}
private void SpawnEnemies()
{
if (visibleEnemies.Count != 0)
return;
noOfBatch++;
//boss appears each 10 batchs
if (noOfBatch % 10 == 0)
{
//spawn a boss
ScheduleOnce(s => visibleEnemies.Add(AddBoss()), 0);
}
else
{
//spawn a batch
bool direction = random.Next(2) == 0;
Schedule(s => visibleEnemies.Add(AddEnemy(direction)), 1.0f, NO_OF_ENEMIES_IN_A_BATCH - 1, 0);
}
}
private CCSprite AddBoss()
{
Boss boss = new Boss();
float y = VisibleBoundsWorldspace.MaxY - boss.ContentSize.Height - 10;
CCPoint left = new CCPoint(boss.ContentSize.Width / 2, y);
CCPoint right = new CCPoint(VisibleBoundsWorldspace.MaxX - boss.ContentSize.Width / 2, y);
boss.Position = left;
var moveRight = new CCMoveTo(3f, right);
var moveLeft = new CCMoveTo(3f, left);
var forever = new CCRepeatForever(new CCFiniteTimeAction[] { moveRight, moveLeft });
AddChild(boss, ENEMY_INDEX);
boss.RunAction(forever);
boss.Schedule(s => visileEnemyBullets.Add(AddEnemyBullet(boss)), 1f);
return boss;
}
private CCSprite AddEnemy(bool leftToRight)
{
Enemy enemy = new Enemy();
float enemyMoveDuration = 5.0f;
CCMoveTo moveEnemy;
if (leftToRight)
{
enemy.Position = new CCPoint(0, VisibleBoundsWorldspace.MaxY);
moveEnemy = new CCMoveTo(enemyMoveDuration, new CCPoint(VisibleBoundsWorldspace.MaxX, 0));
}
else
{
enemy.Position = new CCPoint(VisibleBoundsWorldspace.MaxX, VisibleBoundsWorldspace.MaxY);
moveEnemy = new CCMoveTo(enemyMoveDuration, new CCPoint(0, 0));
}
AddChild(enemy, ENEMY_INDEX);
enemy.RunActions(moveEnemy, moveOutOfView);
enemy.ScheduleOnce(s => visileEnemyBullets.Add(AddEnemyBullet(enemy)), random.Next(1, 3));
return enemy;
}
private EnemyBullet AddEnemyBullet(CCSprite sender)
{
EnemyBullet bullet = new EnemyBullet();
bullet.Position = new CCPoint(sender.Position.X, sender.Position.Y - sender.ContentSize.Height / 2);
AddChild(bullet, ENEMY_BULLET_INDEX);
CCPoint target = CCPoint.IntersectPoint(bullet.Position, player.Position, CCPoint.Zero, new CCPoint(VisibleBoundsWorldspace.MaxX, 0));
float distance = CCPoint.Distance(bullet.Position, target);
var moveBullet = new CCMoveTo(distance / ENEMY_BULLET_SPEED, target);
bullet.RunActions(moveBullet, moveOutOfView);
return bullet;
}
private PlayerBullet AddPlayerBullet()
{
PlayerBullet bullet = new PlayerBullet();
bullet.Position = new CCPoint(player.Position.X, player.Position.Y + player.ContentSize.Height / 2);
AddChild(bullet, PLAYER_BULLET_INDEX);
var moveBullet = new CCMoveTo(5.0f, new CCPoint(bullet.Position.X, VisibleBoundsWorldspace.MaxY));
bullet.RunActions(moveBullet, moveOutOfView);
return bullet;
}
protected override void AddedToScene()
{
base.AddedToScene();
AddBackground();
player.Position = new CCPoint(VisibleBoundsWorldspace.Center.X, player.ContentSize.Height / 2);
healthBar.Position = CCPoint.Zero;
lblScore.Position = new CCPoint(0 + 10, VisibleBoundsWorldspace.MaxY - 10);
mnuPause.Position = new CCPoint(VisibleBoundsWorldspace.MaxX - mnuPause.ContentSize.Width - 10, VisibleBoundsWorldspace.MaxY - mnuPause.ContentSize.Height - 10);
leftBoundX = player.ContentSize.Width / 2;
rightBoundX = VisibleBoundsWorldspace.MaxX - player.ContentSize.Width / 2;
var touchListener = new CCEventListenerTouchAllAtOnce();
touchListener.OnTouchesBegan = OnTouchesBegan;
touchListener.OnTouchesMoved = OnTouchesMoved;
AddEventListener(touchListener, this);
}
private void OnTouchesBegan(List<CCTouch> touches, CCEvent touchEvent)
{
var location = touches[0].Location;
CCNode currentTarget = touchEvent.CurrentTarget;
}
private void OnTouchesMoved(List<CCTouch> touches, CCEvent touchEvent)
{
player.StopAllActions();
var location = touches[0].Location;
float x = location.X;
if (x > rightBoundX)
x = rightBoundX;
if (x < leftBoundX)
x = leftBoundX;
player.Position = new CCPoint(x, player.Position.Y);
}
public static CCScene GameScene(CCGameView gameView)
{
var scene = new CCScene(gameView);
var layer = new GameLayer();
scene.AddChild(layer);
return scene;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace CodapaloozaAPI.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) .NET Foundation. 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.Linq;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Pomelo.EntityFrameworkCore.MySql.Internal;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Xunit;
// ReSharper disable InconsistentNaming
namespace Microsoft.EntityFrameworkCore.Metadata
{
public class MySqlMetadataExtensionsTest
{
[Fact]
public void Can_get_and_set_column_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal("Name", property.MySql().ColumnName);
Assert.Equal("Name", ((IProperty)property).MySql().ColumnName);
property.Relational().ColumnName = "Eman";
Assert.Equal("Name", property.Name);
Assert.Equal("Eman", property.Relational().ColumnName);
Assert.Equal("Eman", property.MySql().ColumnName);
Assert.Equal("Eman", ((IProperty)property).MySql().ColumnName);
property.MySql().ColumnName = "MyNameIs";
Assert.Equal("Name", property.Name);
Assert.Equal("MyNameIs", property.Relational().ColumnName);
Assert.Equal("MyNameIs", property.MySql().ColumnName);
Assert.Equal("MyNameIs", ((IProperty)property).MySql().ColumnName);
property.MySql().ColumnName = null;
Assert.Equal("Name", property.Name);
Assert.Equal("Name", property.Relational().ColumnName);
Assert.Equal("Name", property.MySql().ColumnName);
Assert.Equal("Name", ((IProperty)property).MySql().ColumnName);
}
[Fact]
public void Can_get_and_set_table_name()
{
var modelBuilder = GetModelBuilder();
var entityType = modelBuilder
.Entity<Customer>()
.Metadata;
Assert.Equal("Customer", entityType.MySql().TableName);
Assert.Equal("Customer", ((IEntityType)entityType).MySql().TableName);
entityType.Relational().TableName = "Customizer";
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Customizer", entityType.Relational().TableName);
Assert.Equal("Customizer", entityType.MySql().TableName);
Assert.Equal("Customizer", ((IEntityType)entityType).MySql().TableName);
entityType.MySql().TableName = "Custardizer";
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Custardizer", entityType.Relational().TableName);
Assert.Equal("Custardizer", entityType.MySql().TableName);
Assert.Equal("Custardizer", ((IEntityType)entityType).MySql().TableName);
entityType.MySql().TableName = null;
Assert.Equal("Customer", entityType.DisplayName());
Assert.Equal("Customer", entityType.Relational().TableName);
Assert.Equal("Customer", entityType.MySql().TableName);
Assert.Equal("Customer", ((IEntityType)entityType).MySql().TableName);
}
[Fact]
public void Can_get_and_set_schema_name()
{
var modelBuilder = GetModelBuilder();
var entityType = modelBuilder
.Entity<Customer>()
.Metadata;
Assert.Null(entityType.Relational().Schema);
Assert.Null(entityType.MySql().Schema);
Assert.Null(((IEntityType)entityType).MySql().Schema);
entityType.Relational().Schema = "db0";
Assert.Equal("db0", entityType.Relational().Schema);
Assert.Equal("db0", entityType.MySql().Schema);
Assert.Equal("db0", ((IEntityType)entityType).MySql().Schema);
entityType.MySql().Schema = "dbOh";
Assert.Equal("dbOh", entityType.Relational().Schema);
Assert.Equal("dbOh", entityType.MySql().Schema);
Assert.Equal("dbOh", ((IEntityType)entityType).MySql().Schema);
entityType.MySql().Schema = null;
Assert.Null(entityType.Relational().Schema);
Assert.Null(entityType.MySql().Schema);
Assert.Null(((IEntityType)entityType).MySql().Schema);
}
[Fact]
public void Can_get_and_set_column_type()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().ColumnType);
Assert.Null(property.MySql().ColumnType);
Assert.Null(((IProperty)property).MySql().ColumnType);
property.Relational().ColumnType = "nvarchar(max)";
Assert.Equal("nvarchar(max)", property.Relational().ColumnType);
Assert.Equal("nvarchar(max)", property.MySql().ColumnType);
Assert.Equal("nvarchar(max)", ((IProperty)property).MySql().ColumnType);
property.MySql().ColumnType = "nvarchar(verstappen)";
Assert.Equal("nvarchar(verstappen)", property.Relational().ColumnType);
Assert.Equal("nvarchar(verstappen)", property.MySql().ColumnType);
Assert.Equal("nvarchar(verstappen)", ((IProperty)property).MySql().ColumnType);
property.MySql().ColumnType = null;
Assert.Null(property.Relational().ColumnType);
Assert.Null(property.MySql().ColumnType);
Assert.Null(((IProperty)property).MySql().ColumnType);
}
[Fact]
public void Can_get_and_set_column_default_expression()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().DefaultValueSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Null(((IProperty)property).MySql().DefaultValueSql);
property.Relational().DefaultValueSql = "newsequentialid()";
Assert.Equal("newsequentialid()", property.Relational().DefaultValueSql);
Assert.Equal("newsequentialid()", property.MySql().DefaultValueSql);
Assert.Equal("newsequentialid()", ((IProperty)property).MySql().DefaultValueSql);
property.MySql().DefaultValueSql = "expressyourself()";
Assert.Equal("expressyourself()", property.Relational().DefaultValueSql);
Assert.Equal("expressyourself()", property.MySql().DefaultValueSql);
Assert.Equal("expressyourself()", ((IProperty)property).MySql().DefaultValueSql);
property.MySql().DefaultValueSql = null;
Assert.Null(property.Relational().DefaultValueSql);
Assert.Null(property.MySql().DefaultValueSql);
Assert.Null(((IProperty)property).MySql().DefaultValueSql);
}
[Fact]
public void Can_get_and_set_column_computed_expression()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Null(property.Relational().ComputedColumnSql);
Assert.Null(property.MySql().ComputedColumnSql);
Assert.Null(((IProperty)property).MySql().ComputedColumnSql);
property.Relational().ComputedColumnSql = "newsequentialid()";
Assert.Equal("newsequentialid()", property.Relational().ComputedColumnSql);
Assert.Equal("newsequentialid()", property.MySql().ComputedColumnSql);
Assert.Equal("newsequentialid()", ((IProperty)property).MySql().ComputedColumnSql);
property.MySql().ComputedColumnSql = "expressyourself()";
Assert.Equal("expressyourself()", property.Relational().ComputedColumnSql);
Assert.Equal("expressyourself()", property.MySql().ComputedColumnSql);
Assert.Equal("expressyourself()", ((IProperty)property).MySql().ComputedColumnSql);
property.MySql().ComputedColumnSql = null;
Assert.Null(property.Relational().ComputedColumnSql);
Assert.Null(property.MySql().ComputedColumnSql);
Assert.Null(((IProperty)property).MySql().ComputedColumnSql);
}
[Fact]
public void Can_get_and_set_column_default_value()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.ByteArray)
.Metadata;
Assert.Null(property.Relational().DefaultValue);
Assert.Null(property.MySql().DefaultValue);
Assert.Null(((IProperty)property).MySql().DefaultValue);
property.Relational().DefaultValue = new byte[] { 69, 70, 32, 82, 79, 67, 75, 83 };
Assert.Equal(new byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.Relational().DefaultValue);
Assert.Equal(new byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, property.MySql().DefaultValue);
Assert.Equal(new byte[] { 69, 70, 32, 82, 79, 67, 75, 83 }, ((IProperty)property).MySql().DefaultValue);
property.MySql().DefaultValue = new byte[] { 69, 70, 32, 83, 79, 67, 75, 83 };
Assert.Equal(new byte[] { 69, 70, 32, 83, 79, 67, 75, 83 }, property.Relational().DefaultValue);
Assert.Equal(new byte[] { 69, 70, 32, 83, 79, 67, 75, 83 }, property.MySql().DefaultValue);
Assert.Equal(new byte[] { 69, 70, 32, 83, 79, 67, 75, 83 }, ((IProperty)property).MySql().DefaultValue);
property.MySql().DefaultValue = null;
Assert.Null(property.Relational().DefaultValue);
Assert.Null(property.MySql().DefaultValue);
Assert.Null(((IProperty)property).MySql().DefaultValue);
}
[Theory]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValue), nameof(RelationalPropertyAnnotations.DefaultValueSql))]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValue), nameof(RelationalPropertyAnnotations.ComputedColumnSql))]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValue), nameof(MySqlPropertyAnnotations.ValueGenerationStrategy))]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValueSql), nameof(RelationalPropertyAnnotations.DefaultValue))]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValueSql), nameof(RelationalPropertyAnnotations.ComputedColumnSql))]
[InlineData(nameof(RelationalPropertyAnnotations.DefaultValueSql), nameof(MySqlPropertyAnnotations.ValueGenerationStrategy))]
[InlineData(nameof(RelationalPropertyAnnotations.ComputedColumnSql), nameof(RelationalPropertyAnnotations.DefaultValue))]
[InlineData(nameof(RelationalPropertyAnnotations.ComputedColumnSql), nameof(RelationalPropertyAnnotations.DefaultValueSql))]
[InlineData(nameof(RelationalPropertyAnnotations.ComputedColumnSql), nameof(MySqlPropertyAnnotations.ValueGenerationStrategy))]
[InlineData(nameof(MySqlPropertyAnnotations.ValueGenerationStrategy), nameof(RelationalPropertyAnnotations.DefaultValue))]
[InlineData(nameof(MySqlPropertyAnnotations.ValueGenerationStrategy), nameof(RelationalPropertyAnnotations.DefaultValueSql))]
[InlineData(nameof(MySqlPropertyAnnotations.ValueGenerationStrategy), nameof(RelationalPropertyAnnotations.ComputedColumnSql))]
public void Metadata_throws_when_setting_conflicting_serverGenerated_values(string firstConfiguration, string secondConfiguration)
{
var modelBuilder = GetModelBuilder();
var propertyBuilder = modelBuilder
.Entity<Customer>()
.Property(e => e.NullableInt);
ConfigureProperty(propertyBuilder.Metadata, firstConfiguration, "1");
Assert.Equal(
RelationalStrings.ConflictingColumnServerGeneration(secondConfiguration, nameof(Customer.NullableInt), firstConfiguration),
Assert.Throws<InvalidOperationException>(
() =>
ConfigureProperty(propertyBuilder.Metadata, secondConfiguration, "2")).Message);
}
protected virtual void ConfigureProperty(IMutableProperty property, string configuration, string value)
{
var propertyAnnotations = property.MySql();
switch (configuration)
{
case nameof(RelationalPropertyAnnotations.DefaultValue):
propertyAnnotations.DefaultValue = int.Parse(value);
break;
case nameof(RelationalPropertyAnnotations.DefaultValueSql):
propertyAnnotations.DefaultValueSql = value;
break;
case nameof(RelationalPropertyAnnotations.ComputedColumnSql):
propertyAnnotations.ComputedColumnSql = value;
break;
case nameof(MySqlPropertyAnnotations.ValueGenerationStrategy):
propertyAnnotations.ValueGenerationStrategy = MySqlValueGenerationStrategy.IdentityColumn;
break;
default:
throw new NotImplementedException();
}
}
[Fact]
public void Can_get_and_set_column_key_name()
{
var modelBuilder = GetModelBuilder();
var key = modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.Metadata;
Assert.Equal("PK_Customer", key.Relational().Name);
Assert.Equal("PK_Customer", key.MySql().Name);
Assert.Equal("PK_Customer", ((IKey)key).MySql().Name);
key.Relational().Name = "PrimaryKey";
Assert.Equal("PrimaryKey", key.Relational().Name);
Assert.Equal("PrimaryKey", key.MySql().Name);
Assert.Equal("PrimaryKey", ((IKey)key).MySql().Name);
key.MySql().Name = "PrimarySchool";
Assert.Equal("PrimarySchool", key.Relational().Name);
Assert.Equal("PrimarySchool", key.MySql().Name);
Assert.Equal("PrimarySchool", ((IKey)key).MySql().Name);
key.MySql().Name = null;
Assert.Equal("PK_Customer", key.Relational().Name);
Assert.Equal("PK_Customer", key.MySql().Name);
Assert.Equal("PK_Customer", ((IKey)key).MySql().Name);
}
[Fact]
public void Can_get_and_set_column_foreign_key_name()
{
var modelBuilder = GetModelBuilder();
modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id);
var foreignKey = modelBuilder
.Entity<Order>()
.HasOne<Customer>()
.WithOne()
.HasForeignKey<Order>(e => e.CustomerId)
.Metadata;
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.Relational().Name);
Assert.Equal("FK_Order_Customer_CustomerId", ((IForeignKey)foreignKey).Relational().Name);
foreignKey.Relational().Name = "FK";
Assert.Equal("FK", foreignKey.Relational().Name);
Assert.Equal("FK", ((IForeignKey)foreignKey).Relational().Name);
foreignKey.Relational().Name = "KFC";
Assert.Equal("KFC", foreignKey.Relational().Name);
Assert.Equal("KFC", ((IForeignKey)foreignKey).Relational().Name);
foreignKey.Relational().Name = null;
Assert.Equal("FK_Order_Customer_CustomerId", foreignKey.Relational().Name);
Assert.Equal("FK_Order_Customer_CustomerId", ((IForeignKey)foreignKey).Relational().Name);
}
[Fact]
public void Can_get_and_set_index_name()
{
var modelBuilder = GetModelBuilder();
var index = modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.Metadata;
Assert.Equal("IX_Customer_Id", index.Relational().Name);
Assert.Equal("IX_Customer_Id", ((IIndex)index).Relational().Name);
index.Relational().Name = "MyIndex";
Assert.Equal("MyIndex", index.Relational().Name);
Assert.Equal("MyIndex", ((IIndex)index).Relational().Name);
index.MySql().Name = "DexKnows";
Assert.Equal("DexKnows", index.Relational().Name);
Assert.Equal("DexKnows", ((IIndex)index).Relational().Name);
index.MySql().Name = null;
Assert.Equal("IX_Customer_Id", index.Relational().Name);
Assert.Equal("IX_Customer_Id", ((IIndex)index).Relational().Name);
}
[Fact]
public void Can_get_and_set_index_filter()
{
var modelBuilder = new ModelBuilder(new ConventionSet());
var index = modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.Metadata;
Assert.Null(index.Relational().Filter);
Assert.Null(index.MySql().Filter);
Assert.Null(((IIndex)index).MySql().Filter);
index.Relational().Name = "Generic expression";
Assert.Equal("Generic expression", index.Relational().Name);
Assert.Equal("Generic expression", index.MySql().Name);
Assert.Equal("Generic expression", ((IIndex)index).MySql().Name);
index.MySql().Name = "MySql-specific expression";
Assert.Equal("MySql-specific expression", index.Relational().Name);
Assert.Equal("MySql-specific expression", index.MySql().Name);
Assert.Equal("MySql-specific expression", ((IIndex)index).MySql().Name);
index.MySql().Name = null;
Assert.Null(index.Relational().Filter);
Assert.Null(index.MySql().Filter);
Assert.Null(((IIndex)index).MySql().Filter);
}
[Fact]
public void Can_get_and_set_index_clustering()
{
var modelBuilder = GetModelBuilder();
var index = modelBuilder
.Entity<Customer>()
.HasIndex(e => e.Id)
.Metadata;
Assert.Null(index.MySql().IsClustered);
Assert.Null(((IIndex)index).MySql().IsClustered);
index.MySql().IsClustered = true;
Assert.True(index.MySql().IsClustered.Value);
Assert.True(((IIndex)index).MySql().IsClustered.Value);
index.MySql().IsClustered = null;
Assert.Null(index.MySql().IsClustered);
Assert.Null(((IIndex)index).MySql().IsClustered);
}
[Fact]
public void Can_get_and_set_key_clustering()
{
var modelBuilder = GetModelBuilder();
var key = modelBuilder
.Entity<Customer>()
.HasKey(e => e.Id)
.Metadata;
Assert.Null(key.MySql().IsClustered);
Assert.Null(((IKey)key).MySql().IsClustered);
key.MySql().IsClustered = true;
Assert.True(key.MySql().IsClustered.Value);
Assert.True(((IKey)key).MySql().IsClustered.Value);
key.MySql().IsClustered = null;
Assert.Null(key.MySql().IsClustered);
Assert.Null(((IKey)key).MySql().IsClustered);
}
[Fact]
public void Can_get_and_set_sequence()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Null(model.Relational().FindSequence("Foo"));
Assert.Null(model.MySql().FindSequence("Foo"));
Assert.Null(((IModel)model).MySql().FindSequence("Foo"));
var sequence = model.MySql().GetOrAddSequence("Foo");
Assert.Equal("Foo", model.Relational().FindSequence("Foo").Name);
Assert.Equal("Foo", ((IModel)model).Relational().FindSequence("Foo").Name);
Assert.Equal("Foo", model.MySql().FindSequence("Foo").Name);
Assert.Equal("Foo", ((IModel)model).MySql().FindSequence("Foo").Name);
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
Assert.NotNull(model.Relational().FindSequence("Foo"));
var sequence2 = model.MySql().FindSequence("Foo");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.MinValue = 2001;
sequence.MaxValue = 2010;
sequence.ClrType = typeof(int);
Assert.Equal("Foo", sequence.Name);
Assert.Null(sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
Assert.Equal(sequence2.Name, sequence.Name);
Assert.Equal(sequence2.Schema, sequence.Schema);
Assert.Equal(sequence2.IncrementBy, sequence.IncrementBy);
Assert.Equal(sequence2.StartValue, sequence.StartValue);
Assert.Equal(sequence2.MinValue, sequence.MinValue);
Assert.Equal(sequence2.MaxValue, sequence.MaxValue);
Assert.Same(sequence2.ClrType, sequence.ClrType);
}
[Fact]
public void Can_get_and_set_sequence_with_schema_name()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Null(model.Relational().FindSequence("Foo", "Smoo"));
Assert.Null(model.MySql().FindSequence("Foo", "Smoo"));
Assert.Null(((IModel)model).MySql().FindSequence("Foo", "Smoo"));
var sequence = model.MySql().GetOrAddSequence("Foo", "Smoo");
Assert.Equal("Foo", model.Relational().FindSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", ((IModel)model).Relational().FindSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", model.MySql().FindSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", ((IModel)model).MySql().FindSequence("Foo", "Smoo").Name);
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(1, sequence.IncrementBy);
Assert.Equal(1, sequence.StartValue);
Assert.Null(sequence.MinValue);
Assert.Null(sequence.MaxValue);
Assert.Same(typeof(long), sequence.ClrType);
Assert.NotNull(model.Relational().FindSequence("Foo", "Smoo"));
var sequence2 = model.MySql().FindSequence("Foo", "Smoo");
sequence.StartValue = 1729;
sequence.IncrementBy = 11;
sequence.MinValue = 2001;
sequence.MaxValue = 2010;
sequence.ClrType = typeof(int);
Assert.Equal("Foo", sequence.Name);
Assert.Equal("Smoo", sequence.Schema);
Assert.Equal(11, sequence.IncrementBy);
Assert.Equal(1729, sequence.StartValue);
Assert.Equal(2001, sequence.MinValue);
Assert.Equal(2010, sequence.MaxValue);
Assert.Same(typeof(int), sequence.ClrType);
Assert.Equal(sequence2.Name, sequence.Name);
Assert.Equal(sequence2.Schema, sequence.Schema);
Assert.Equal(sequence2.IncrementBy, sequence.IncrementBy);
Assert.Equal(sequence2.StartValue, sequence.StartValue);
Assert.Equal(sequence2.MinValue, sequence.MinValue);
Assert.Equal(sequence2.MaxValue, sequence.MaxValue);
Assert.Same(sequence2.ClrType, sequence.ClrType);
}
[Fact]
public void Can_get_multiple_sequences()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
model.Relational().GetOrAddSequence("Fibonacci");
model.MySql().GetOrAddSequence("Golomb");
var sequences = model.MySql().Sequences;
Assert.Equal(2, sequences.Count);
Assert.Contains(sequences, s => s.Name == "Fibonacci");
Assert.Contains(sequences, s => s.Name == "Golomb");
}
[Fact]
public void Can_get_multiple_sequences_when_overridden()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
model.Relational().GetOrAddSequence("Fibonacci").StartValue = 1;
model.MySql().GetOrAddSequence("Fibonacci").StartValue = 3;
model.MySql().GetOrAddSequence("Golomb");
var sequences = model.MySql().Sequences;
Assert.Equal(2, sequences.Count);
Assert.Contains(sequences, s => s.Name == "Golomb");
var sequence = sequences.FirstOrDefault(s => s.Name == "Fibonacci");
Assert.NotNull(sequence);
Assert.Equal(3, sequence.StartValue);
}
[Fact]
public void Can_get_and_set_value_generation_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Equal(MySqlValueGenerationStrategy.IdentityColumn, model.MySql().ValueGenerationStrategy);
model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, model.MySql().ValueGenerationStrategy);
model.MySql().ValueGenerationStrategy = null;
Assert.Null(model.MySql().ValueGenerationStrategy);
}
[Fact]
public void Can_get_and_set_default_sequence_name_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Null(model.MySql().HiLoSequenceName);
Assert.Null(((IModel)model).MySql().HiLoSequenceName);
model.MySql().HiLoSequenceName = "Tasty.Snook";
Assert.Equal("Tasty.Snook", model.MySql().HiLoSequenceName);
Assert.Equal("Tasty.Snook", ((IModel)model).MySql().HiLoSequenceName);
model.MySql().HiLoSequenceName = null;
Assert.Null(model.MySql().HiLoSequenceName);
Assert.Null(((IModel)model).MySql().HiLoSequenceName);
}
[Fact]
public void Can_get_and_set_default_sequence_schema_on_model()
{
var modelBuilder = GetModelBuilder();
var model = modelBuilder.Model;
Assert.Null(model.MySql().HiLoSequenceSchema);
Assert.Null(((IModel)model).MySql().HiLoSequenceSchema);
model.MySql().HiLoSequenceSchema = "Tasty.Snook";
Assert.Equal("Tasty.Snook", model.MySql().HiLoSequenceSchema);
Assert.Equal("Tasty.Snook", ((IModel)model).MySql().HiLoSequenceSchema);
model.MySql().HiLoSequenceSchema = null;
Assert.Null(model.MySql().HiLoSequenceSchema);
Assert.Null(((IModel)model).MySql().HiLoSequenceSchema);
}
[Fact]
public void Can_get_and_set_value_generation_on_property()
{
var modelBuilder = GetModelBuilder();
modelBuilder.Model.MySql().ValueGenerationStrategy = null;
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, ((IProperty)property).MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
property.MySql().ValueGenerationStrategy = null;
Assert.Null(property.MySql().ValueGenerationStrategy);
Assert.Equal(ValueGenerated.OnAdd, property.ValueGenerated);
}
[Fact]
public void Can_get_and_set_value_generation_on_nullable_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.NullableInt)
.Metadata;
Assert.Null(property.MySql().ValueGenerationStrategy);
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, property.MySql().ValueGenerationStrategy);
Assert.Equal(MySqlValueGenerationStrategy.SequenceHiLo, ((IProperty)property).MySql().ValueGenerationStrategy);
property.MySql().ValueGenerationStrategy = null;
Assert.Null(property.MySql().ValueGenerationStrategy);
}
[Fact]
public void Throws_setting_sequence_generation_for_invalid_type()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal(
MySqlStrings.SequenceBadType("Name", nameof(Customer), "string"),
Assert.Throws<ArgumentException>(
() => property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo).Message);
}
[Fact]
public void Throws_setting_identity_generation_for_invalid_type()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Name)
.Metadata;
Assert.Equal(
MySqlStrings.IdentityBadType("Name", nameof(Customer), "string"),
Assert.Throws<ArgumentException>(
() => property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.IdentityColumn).Message);
}
[Fact]
public void Can_get_and_set_sequence_name_on_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.MySql().HiLoSequenceName);
Assert.Null(((IProperty)property).MySql().HiLoSequenceName);
property.MySql().HiLoSequenceName = "Snook";
Assert.Equal("Snook", property.MySql().HiLoSequenceName);
Assert.Equal("Snook", ((IProperty)property).MySql().HiLoSequenceName);
property.MySql().HiLoSequenceName = null;
Assert.Null(property.MySql().HiLoSequenceName);
Assert.Null(((IProperty)property).MySql().HiLoSequenceName);
}
[Fact]
public void Can_get_and_set_sequence_schema_on_property()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
Assert.Null(property.MySql().HiLoSequenceSchema);
Assert.Null(((IProperty)property).MySql().HiLoSequenceSchema);
property.MySql().HiLoSequenceSchema = "Tasty";
Assert.Equal("Tasty", property.MySql().HiLoSequenceSchema);
Assert.Equal("Tasty", ((IProperty)property).MySql().HiLoSequenceSchema);
property.MySql().HiLoSequenceSchema = null;
Assert.Null(property.MySql().HiLoSequenceSchema);
Assert.Null(((IProperty)property).MySql().HiLoSequenceSchema);
}
[Fact]
public void TryGetSequence_returns_null_if_property_is_not_configured_for_sequence_value_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw");
Assert.Null(property.MySql().FindHiLoSequence());
Assert.Null(((IProperty)property).MySql().FindHiLoSequence());
property.MySql().HiLoSequenceName = "DaneelOlivaw";
Assert.Null(property.MySql().FindHiLoSequence());
Assert.Null(((IProperty)property).MySql().FindHiLoSequence());
modelBuilder.Model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.IdentityColumn;
Assert.Null(property.MySql().FindHiLoSequence());
Assert.Null(((IProperty)property).MySql().FindHiLoSequence());
modelBuilder.Model.MySql().ValueGenerationStrategy = null;
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.IdentityColumn;
Assert.Null(property.MySql().FindHiLoSequence());
Assert.Null(((IProperty)property).MySql().FindHiLoSequence());
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw");
property.MySql().HiLoSequenceName = "DaneelOlivaw";
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw");
modelBuilder.Model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
property.MySql().HiLoSequenceName = "DaneelOlivaw";
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw");
modelBuilder.Model.MySql().HiLoSequenceName = "DaneelOlivaw";
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_returns_sequence_property_is_marked_for_default_generation_and_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw");
modelBuilder.Model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
modelBuilder.Model.MySql().HiLoSequenceName = "DaneelOlivaw";
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw", "R");
property.MySql().HiLoSequenceName = "DaneelOlivaw";
property.MySql().HiLoSequenceSchema = "R";
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
Assert.Equal("R", property.MySql().FindHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).MySql().FindHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw", "R");
modelBuilder.Model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
property.MySql().HiLoSequenceName = "DaneelOlivaw";
property.MySql().HiLoSequenceSchema = "R";
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
Assert.Equal("R", property.MySql().FindHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).MySql().FindHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_property_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw", "R");
modelBuilder.Model.MySql().HiLoSequenceName = "DaneelOlivaw";
modelBuilder.Model.MySql().HiLoSequenceSchema = "R";
property.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
Assert.Equal("R", property.MySql().FindHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).MySql().FindHiLoSequence().Schema);
}
[Fact]
public void TryGetSequence_with_schema_returns_sequence_model_is_marked_for_sequence_generation_and_model_has_name()
{
var modelBuilder = GetModelBuilder();
var property = modelBuilder
.Entity<Customer>()
.Property(e => e.Id)
.ValueGeneratedOnAdd()
.Metadata;
modelBuilder.Model.MySql().GetOrAddSequence("DaneelOlivaw", "R");
modelBuilder.Model.MySql().ValueGenerationStrategy = MySqlValueGenerationStrategy.SequenceHiLo;
modelBuilder.Model.MySql().HiLoSequenceName = "DaneelOlivaw";
modelBuilder.Model.MySql().HiLoSequenceSchema = "R";
Assert.Equal("DaneelOlivaw", property.MySql().FindHiLoSequence().Name);
Assert.Equal("DaneelOlivaw", ((IProperty)property).MySql().FindHiLoSequence().Name);
Assert.Equal("R", property.MySql().FindHiLoSequence().Schema);
Assert.Equal("R", ((IProperty)property).MySql().FindHiLoSequence().Schema);
}
private static ModelBuilder GetModelBuilder() => MySqlTestHelpers.Instance.CreateConventionBuilder();
private class Customer
{
public int Id { get; set; }
public int? NullableInt { get; set; }
public string Name { get; set; }
public byte Byte { get; set; }
public byte? NullableByte { get; set; }
public byte[] ByteArray { get; set; }
}
private class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using NHunspellComponent.Spelling.Interfaces;
using NHunspellComponent.SupportClasses;
namespace Forms1
{
public class CustomPaintRichText : RichTextBox, IUnderlineableSpellingControl
{
public Dictionary<int, int> underlinedSections;
public Dictionary<int, int> protectedSections;
public Dictionary<int, int> ignoredSections;
public Dictionary<int, int> UnderlinedSections
{
get
{
if (underlinedSections == null)
underlinedSections = new Dictionary<int, int>();
return underlinedSections;
}
set { underlinedSections = value; }
}
public Dictionary<int, int> ProtectedSections
{
set { protectedSections = value; }
}
public Dictionary<int, int> IgnoredSections
{
set { ignoredSections = value; }
}
#region ISpellingControl Members
private bool spellingEnabled;
private bool spellingAutoEnabled;
private bool isPassWordProtected;
public bool IsSpellingEnabled
{
get { return spellingEnabled; }
set { spellingEnabled = value; }
}
public bool IsSpellingAutoEnabled
{
get { return spellingAutoEnabled; }
set
{
spellingAutoEnabled = value;
if (!spellingEnabled) spellingEnabled = value;
}
}
public bool IsPassWordProtected
{
get { return isPassWordProtected; }
set { isPassWordProtected = value; }
}
#endregion
/// <summary>
/// This is called when the textbox is being redrawn.
/// When it is, for the textbox to get refreshed, call it's default
/// paint method and then call our method
/// </summary>
/// <param name="m">The windows message</param>
/// <remarks></remarks>
protected override void WndProc(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case 15:
//This is the WM_PAINT message
//Invalidate the textBoxBase so that it gets refreshed properly
this.Invalidate();
//call the default win32 Paint method for the TextBoxBase first
base.WndProc(ref m);
//now use our code to draw the extra stuff
if (!this.ReadOnly && IsSpellingAutoEnabled)
{
this.CustomPaint();
}
break;
default:
base.WndProc(ref m);
break;
}
}
public void CustomPaint()
{
Bitmap tmpBitmap;
Graphics textBoxGraphics;
Graphics bufferGraphics;
//Create a bitmap with the same dimensions as the textbox
tmpBitmap = new Bitmap(this.Width, this.Height);
//Create the graphics object from this bitmpa...this is where we will draw the lines to start with
bufferGraphics = Graphics.FromImage(tmpBitmap);
bufferGraphics.Clip = new Region(this.ClientRectangle);
//Get the graphics object for the textbox. We use this to draw the bufferGraphics
textBoxGraphics = Graphics.FromHwnd(this.Handle);
// clear the graphics buffer
bufferGraphics.Clear(Color.Transparent);
foreach (int wordStart in UnderlinedSections.Keys)
{
if (ignoredSections != null && ignoredSections.ContainsKey(wordStart))
{
continue;
}
int wordEndIndex = wordStart + UnderlinedSections[wordStart] - 1;
Point start = this.GetPositionFromCharIndex(wordStart);
Point end = this.GetPositionFromCharIndex(wordEndIndex + 1);
int curIndex = wordStart;
int safetyDrewOnce = -1;
if (curIndex < Text.Length)
do
{
start = this.GetPositionFromCharIndex(curIndex);
//Determine the first line of waves to draw
while (curIndex <= wordEndIndex)
{
if (curIndex < Text.Length && this.GetPositionFromCharIndex(curIndex).Y == start.Y)
{
curIndex += 1;
}
else
{
curIndex--;
break;
}
}
end = this.GetPositionFromCharIndex(curIndex);
// The position above now points to the top left corner of the character.
// We need to account for the character height so the underlines go
// to the right place.
//end.X += 1;
int yOffset = TextBoxAPIHelper.GetBaselineOffsetAtCharIndex(this, wordStart);
start.Y += yOffset;
end.Y += yOffset;
//Add a new wavy line using the starting and ending point
DrawWave(bufferGraphics, start, end);
if (safetyDrewOnce != curIndex)
{
safetyDrewOnce = curIndex;
}
else
{
break;
}
curIndex += 1;
} //TODO: something with indeces
//Replace words in text with empty words.
while (curIndex <= wordEndIndex);
}
// Now we just draw our internal buffer on top of the TextBox.
// Everything should be at the right place.
textBoxGraphics.DrawImageUnscaled(tmpBitmap, 0, 0);
}
/// <summary>
/// Draws the wavy red line given a starting point and an ending point
/// </summary>
/// <param name="StartOfLine">A Point representing the starting point</param>
/// <param name="EndOfLine">A Point representing the ending point</param>
/// <remarks></remarks>
private void DrawWave(Graphics graphics, Point StartOfLine, Point EndOfLine)
{
//correction to draw line closer to text
StartOfLine.Y--;
EndOfLine.Y--;
Pen newPen = Pens.Red;
if ((EndOfLine.X - StartOfLine.X) > 4)
{
ArrayList pl = new ArrayList();
for (int i = StartOfLine.X; i <= (EndOfLine.X - 2); i += 4)
{
pl.Add(new Point(i, StartOfLine.Y));
pl.Add(new Point(i + 2, StartOfLine.Y + 2));
}
Point[] p = (Point[]) pl.ToArray(typeof (Point));
graphics.DrawLines(newPen, p);
}
else
{
graphics.DrawLine(newPen, StartOfLine, EndOfLine);
}
}
public void AddUnderlinedSection(int s, int l)
{
if (UnderlinedSections.ContainsKey(s))
{
underlinedSections.Remove(s);
}
underlinedSections.Add(s, l);
}
public void RemoveWordFromUnderliningList(int wordStart)
{
if (underlinedSections.ContainsKey(wordStart))
{
underlinedSections.Remove(wordStart);
//this.Invalidate();
}
}
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
int position = this.GetCharIndexFromPosition(e.Location);
if (position == Text.Length - 1)
{
position++;
}
if (position < this.SelectionStart ||
position > this.SelectionStart + this.SelectionLength)
{
this.Select(position, 0);
}
}
base.OnMouseDown(e);
}
internal void AddToIgnoreList(int start, int length)
{
if (ignoredSections != null && ignoredSections.ContainsKey(start))
{
ignoredSections.Remove(start);
}
if (ignoredSections != null)
ignoredSections.Add(start, length);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// An <code>wrapper</code> for a managed stream that implements all WinRT stream operations.
/// This class must not implement any WinRT stream interfaces directly.
/// We never create instances of this class directly; instead we use classes defined in
/// the region Interface adapters to implement WinRT ifaces and create instances of those types.
/// See comment in that region for technical details.
/// </summary>
internal abstract class NetFxToWinRtStreamAdapter : IDisposable
{
#region Construction
#region Interface adapters
// Instances of private types defined in this section will be returned from NetFxToWinRtStreamAdapter.Create(..).
// Depending on the capabilities of the .NET stream for which we need to construct the adapter, we need to return
// an object that can be QIed (COM speak for "cast") to a well-defined set of ifaces.
// E.g, if the specified stream CanRead, but not CanSeek and not CanWrite, then we *must* return an object that
// can be QIed to IInputStream, but *not* IRandomAccessStream and *not* IOutputStream.
// There are two ways to do that:
// - We could explicitly implement ICustomQueryInterface and respond to QI requests by analyzing the stream capabilities
// - We can use the runtime's ability to do that for us, based on the ifaces the concrete class implements (or does not).
// The latter is much more elegant, and likely also faster.
private class InputStream : NetFxToWinRtStreamAdapter, IInputStream, IDisposable
{
internal InputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class OutputStream : NetFxToWinRtStreamAdapter, IOutputStream, IDisposable
{
internal OutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class RandomAccessStream : NetFxToWinRtStreamAdapter, IRandomAccessStream, IInputStream, IOutputStream, IDisposable
{
internal RandomAccessStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class InputOutputStream : NetFxToWinRtStreamAdapter, IInputStream, IOutputStream, IDisposable
{
internal InputOutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
#endregion Interface adapters
// We may want to define different behaviour for different types of streams.
// For instance, ReadAsync treats MemoryStream special for performance reasons.
// The enum 'StreamReadOperationOptimization' describes the read optimization to employ for a
// given NetFxToWinRtStreamAdapter instance. In future, we might define other enums to follow a
// similar pattern, e.g. 'StreamWriteOperationOptimization' or 'StreamFlushOperationOptimization'.
private enum StreamReadOperationOptimization
{
AbstractStream = 0, MemoryStream
}
internal static NetFxToWinRtStreamAdapter Create(Stream stream)
{
if (stream == null)
throw new ArgumentNullException("stream");
StreamReadOperationOptimization readOptimization = StreamReadOperationOptimization.AbstractStream;
if (stream.CanRead)
readOptimization = DetermineStreamReadOptimization(stream);
NetFxToWinRtStreamAdapter adapter;
if (stream.CanSeek)
adapter = new RandomAccessStream(stream, readOptimization);
else if (stream.CanRead && stream.CanWrite)
adapter = new InputOutputStream(stream, readOptimization);
else if (stream.CanRead)
adapter = new InputStream(stream, readOptimization);
else if (stream.CanWrite)
adapter = new OutputStream(stream, readOptimization);
else
throw new ArgumentException(SR.Argument_NotSufficientCapabilitiesToConvertToWinRtStream);
return adapter;
}
private static StreamReadOperationOptimization DetermineStreamReadOptimization(Stream stream)
{
Contract.Requires(stream != null);
if (CanApplyReadMemoryStreamOptimization(stream))
return StreamReadOperationOptimization.MemoryStream;
return StreamReadOperationOptimization.AbstractStream;
}
private static bool CanApplyReadMemoryStreamOptimization(Stream stream)
{
MemoryStream memStream = stream as MemoryStream;
if (memStream == null)
return false;
ArraySegment<byte> arrSeg;
return memStream.TryGetBuffer(out arrSeg);
}
private NetFxToWinRtStreamAdapter(Stream stream, StreamReadOperationOptimization readOptimization)
{
Contract.Requires(stream != null);
Contract.Requires(stream.CanRead || stream.CanWrite || stream.CanSeek);
Contract.EndContractBlock();
Debug.Assert(!stream.CanRead || (stream.CanRead && this is IInputStream));
Debug.Assert(!stream.CanWrite || (stream.CanWrite && this is IOutputStream));
Debug.Assert(!stream.CanSeek || (stream.CanSeek && this is IRandomAccessStream));
_readOptimization = readOptimization;
_managedStream = stream;
}
#endregion Construction
#region Instance variables
private Stream _managedStream = null;
private bool _leaveUnderlyingStreamOpen = true;
private readonly StreamReadOperationOptimization _readOptimization;
#endregion Instance variables
#region Tools and Helpers
/// <summary>
/// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream.
/// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered
/// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are
/// finalized, they do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to
/// dispose the underlying stream.
/// </summary>
internal void SetWonInitializationRace()
{
_leaveUnderlyingStreamOpen = false;
}
public Stream GetManagedStream()
{
return _managedStream;
}
private Stream EnsureNotDisposed()
{
Stream str = _managedStream;
if (str == null)
{
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
ex.SetErrorCode(HResults.RO_E_CLOSED);
throw ex;
}
return str;
}
#endregion Tools and Helpers
#region Common public interface
/// <summary>Implements IDisposable.Dispose (IClosable.Close in WinRT)</summary>
void IDisposable.Dispose()
{
Stream str = _managedStream;
if (str == null)
return;
_managedStream = null;
if (!_leaveUnderlyingStreamOpen)
str.Dispose();
}
#endregion Common public interface
#region IInputStream public interface
public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException("buffer");
}
if (count < 0 || Int32.MaxValue < count)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("count");
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
if (buffer.Capacity < count)
{
ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead))
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException("options",
SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
IAsyncOperationWithProgress<IBuffer, UInt32> readAsyncOperation;
switch (_readOptimization)
{
case StreamReadOperationOptimization.MemoryStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count);
break;
case StreamReadOperationOptimization.AbstractStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options);
break;
// Use this pattern to add more optimisation options if necessary:
//case StreamReadOperationOptimization.XxxxStream:
// readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options);
// break;
default:
Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
readAsyncOperation = null;
break;
}
return readAsyncOperation;
}
#endregion IInputStream public interface
#region IOutputStream public interface
public IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync(IBuffer buffer)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException("buffer");
}
if (buffer.Capacity < buffer.Length)
{
ArgumentException ex = new ArgumentException(SR.Argument_BufferLengthExceedsCapacity);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<UInt32, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer);
}
public IAsyncOperation<Boolean> FlushAsync()
{
Contract.Ensures(Contract.Result<IAsyncOperation<Boolean>>() != null);
Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.FlushAsync_AbstractStream(str);
}
#endregion IOutputStream public interface
#region IRandomAccessStream public interface
#region IRandomAccessStream public interface: Not cloning related
public void Seek(UInt64 position)
{
if (position > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
Int64 pos = unchecked((Int64)position);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= pos && pos <= Int64.MaxValue, "Unexpected pos=" + pos + ".");
str.Seek(pos, SeekOrigin.Begin);
}
public bool CanRead
{
get
{
Stream str = EnsureNotDisposed();
return str.CanRead;
}
}
public bool CanWrite
{
get
{
Stream str = EnsureNotDisposed();
return str.CanWrite;
}
}
public UInt64 Position
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Position;
}
}
public UInt64 Size
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Length;
}
set
{
if (value > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSetSizeBeyondInt64MaxValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
if (!str.CanWrite)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetStreamSizeCannotWrite);
ex.SetErrorCode(HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
Int64 val = unchecked((Int64)value);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= val && val <= Int64.MaxValue, "Unexpected val=" + val + ".");
str.SetLength(val);
}
}
#endregion IRandomAccessStream public interface: Not cloning related
#region IRandomAccessStream public interface: Cloning related
// We do not want to support the cloning-related operation for now.
// They appear to mainly target corner-case scenarios in Windows itself,
// and are (mainly) a historical artefact of abandoned early designs
// for IRandonAccessStream.
// Cloning can be added in future, however, it would be quite complex
// to support it correctly for generic streams.
private static void ThrowCloningNotSuported(String methodName)
{
NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
nse.SetErrorCode(HResults.E_NOTIMPL);
throw nse;
}
public IRandomAccessStream CloneStream()
{
ThrowCloningNotSuported("CloneStream");
return null;
}
public IInputStream GetInputStreamAt(UInt64 position)
{
ThrowCloningNotSuported("GetInputStreamAt");
return null;
}
public IOutputStream GetOutputStreamAt(UInt64 position)
{
ThrowCloningNotSuported("GetOutputStreamAt");
return null;
}
#endregion IRandomAccessStream public interface: Cloning related
#endregion IRandomAccessStream public interface
} // class NetFxToWinRtStreamAdapter
} // namespace
// NetFxToWinRtStreamAdapter.cs
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Activities
{
using System;
using System.Activities.Runtime;
using System.Activities.Validation;
using System.Activities.XamlIntegration;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime;
using System.Windows.Markup;
using System.Xaml;
[ContentProperty("Implementation")]
public sealed class DynamicActivity : Activity, ICustomTypeDescriptor, IDynamicActivity
{
Activity runtimeImplementation;
DynamicActivityTypeDescriptor typeDescriptor;
Collection<Attribute> attributes;
public DynamicActivity()
: base()
{
this.typeDescriptor = new DynamicActivityTypeDescriptor(this);
}
public string Name
{
get
{
return this.typeDescriptor.Name;
}
set
{
this.typeDescriptor.Name = value;
}
}
[DependsOn("Name")]
public Collection<Attribute> Attributes
{
get
{
if (this.attributes == null)
{
this.attributes = new Collection<Attribute>();
}
return this.attributes;
}
}
[Browsable(false)]
[DependsOn("Attributes")]
public KeyedCollection<string, DynamicActivityProperty> Properties
{
get
{
return this.typeDescriptor.Properties;
}
}
[DependsOn("Properties")]
public new Collection<Constraint> Constraints
{
get
{
return base.Constraints;
}
}
[TypeConverter(typeof(ImplementationVersionConverter))]
[DefaultValue(null)]
public new Version ImplementationVersion
{
get
{
return base.ImplementationVersion;
}
set
{
base.ImplementationVersion = value;
}
}
[XamlDeferLoad(typeof(FuncDeferringLoader), typeof(Activity))]
[DefaultValue(null)]
[Browsable(false)]
[Ambient]
public new Func<Activity> Implementation
{
get
{
return base.Implementation;
}
set
{
base.Implementation = value;
}
}
KeyedCollection<string, DynamicActivityProperty> IDynamicActivity.Properties
{
get
{
return this.Properties;
}
}
internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
if (this.runtimeImplementation != null)
{
executor.ScheduleActivity(this.runtimeImplementation, instance, null, null, null);
}
}
sealed internal override void OnInternalCacheMetadata(bool createEmptyBindings)
{
Activity body = null;
if (this.Implementation != null)
{
body = this.Implementation();
}
if (body != null)
{
SetImplementationChildrenCollection(new Collection<Activity> { body });
}
// Always cache the last body that we returned
this.runtimeImplementation = body;
ReflectedInformation information = new ReflectedInformation(this);
SetImportedChildrenCollection(information.GetChildren());
SetVariablesCollection(information.GetVariables());
SetImportedDelegatesCollection(information.GetDelegates());
SetArgumentsCollection(information.GetArguments(), createEmptyBindings);
}
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return this.typeDescriptor.GetAttributes();
}
string ICustomTypeDescriptor.GetClassName()
{
return this.typeDescriptor.GetClassName();
}
string ICustomTypeDescriptor.GetComponentName()
{
return this.typeDescriptor.GetComponentName();
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return this.typeDescriptor.GetConverter();
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return this.typeDescriptor.GetDefaultEvent();
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return this.typeDescriptor.GetDefaultProperty();
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return this.typeDescriptor.GetEditor(editorBaseType);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return this.typeDescriptor.GetEvents(attributes);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return this.typeDescriptor.GetEvents();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return this.typeDescriptor.GetProperties();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return this.typeDescriptor.GetProperties(attributes);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this.typeDescriptor.GetPropertyOwner(pd);
}
}
[ContentProperty("Implementation")]
public sealed class DynamicActivity<TResult> : Activity<TResult>, ICustomTypeDescriptor, IDynamicActivity
{
Activity runtimeImplementation;
DynamicActivityTypeDescriptor typeDescriptor;
Collection<Attribute> attributes;
public DynamicActivity()
: base()
{
this.typeDescriptor = new DynamicActivityTypeDescriptor(this);
}
public string Name
{
get
{
return this.typeDescriptor.Name;
}
set
{
this.typeDescriptor.Name = value;
}
}
[DependsOn("Name")]
public Collection<Attribute> Attributes
{
get
{
if (this.attributes == null)
{
this.attributes = new Collection<Attribute>();
}
return this.attributes;
}
}
[Browsable(false)]
[DependsOn("Attributes")]
public KeyedCollection<string, DynamicActivityProperty> Properties
{
get
{
return this.typeDescriptor.Properties;
}
}
[DependsOn("Properties")]
public new Collection<Constraint> Constraints
{
get
{
return base.Constraints;
}
}
[TypeConverter(typeof(ImplementationVersionConverter))]
[DefaultValue(null)]
public new Version ImplementationVersion
{
get
{
return base.ImplementationVersion;
}
set
{
base.ImplementationVersion = value;
}
}
[XamlDeferLoad(typeof(FuncDeferringLoader), typeof(Activity))]
[DefaultValue(null)]
[Browsable(false)]
[Ambient]
public new Func<Activity> Implementation
{
get
{
return base.Implementation;
}
set
{
base.Implementation = value;
}
}
KeyedCollection<string, DynamicActivityProperty> IDynamicActivity.Properties
{
get
{
return this.Properties;
}
}
internal override void InternalExecute(ActivityInstance instance, ActivityExecutor executor, BookmarkManager bookmarkManager)
{
if (this.runtimeImplementation != null)
{
executor.ScheduleActivity(this.runtimeImplementation, instance, null, null, null);
}
}
sealed internal override void OnInternalCacheMetadataExceptResult(bool createEmptyBindings)
{
Activity body = null;
if (this.Implementation != null)
{
body = this.Implementation();
}
if (body != null)
{
SetImplementationChildrenCollection(new Collection<Activity> { body });
}
// Always cache the last body that we returned
this.runtimeImplementation = body;
ReflectedInformation information = new ReflectedInformation(this);
SetImportedChildrenCollection(information.GetChildren());
SetVariablesCollection(information.GetVariables());
SetImportedDelegatesCollection(information.GetDelegates());
SetArgumentsCollection(information.GetArguments(), createEmptyBindings);
}
AttributeCollection ICustomTypeDescriptor.GetAttributes()
{
return this.typeDescriptor.GetAttributes();
}
string ICustomTypeDescriptor.GetClassName()
{
return this.typeDescriptor.GetClassName();
}
string ICustomTypeDescriptor.GetComponentName()
{
return this.typeDescriptor.GetComponentName();
}
TypeConverter ICustomTypeDescriptor.GetConverter()
{
return this.typeDescriptor.GetConverter();
}
EventDescriptor ICustomTypeDescriptor.GetDefaultEvent()
{
return this.typeDescriptor.GetDefaultEvent();
}
PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty()
{
return this.typeDescriptor.GetDefaultProperty();
}
object ICustomTypeDescriptor.GetEditor(Type editorBaseType)
{
return this.typeDescriptor.GetEditor(editorBaseType);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes)
{
return this.typeDescriptor.GetEvents(attributes);
}
EventDescriptorCollection ICustomTypeDescriptor.GetEvents()
{
return this.typeDescriptor.GetEvents();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties()
{
return this.typeDescriptor.GetProperties();
}
PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes)
{
return this.typeDescriptor.GetProperties(attributes);
}
object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd)
{
return this.typeDescriptor.GetPropertyOwner(pd);
}
}
}
| |
// 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;
namespace System.Data
{
internal enum ValueType
{
Unknown = -1,
Null = 0,
Bool = 1,
Numeric = 2,
Str = 3,
Float = 4,
Decimal = 5,
Object = 6,
Date = 7,
}
/// <summary>
/// ExpressionParser: expression node types
/// </summary>
internal enum Nodes
{
Noop = 0,
Unop = 1, /* Unary operator */
UnopSpec = 2, /* Special unop: IFF does not eval args */
Binop = 3, /* Binary operator */
BinopSpec = 4, /* Special binop: BETWEEN, IN does not eval args */
Zop = 5, /* "0-ary operator" - intrinsic constant. */
Call = 6, /* Function call or rhs of IN or IFF */
Const = 7, /* Constant value */
Name = 8, /* Identifier */
Paren = 9, /* Parentheses */
Conv = 10, /* Type conversion */
}
internal sealed class ExpressionParser
{
/// <summary>
/// Operand situations for parser
/// </summary>
private const int Empty = 0; /* There was no previous operand */
private const int Scalar = 1; /* The previous operand was a constant or id */
private const int Expr = 2; /* The previous operand was a complex expression */
private struct ReservedWords
{
internal readonly string _word; // the word
internal readonly Tokens _token;
internal readonly int _op;
internal ReservedWords(string word, Tokens token, int op)
{
_word = word;
_token = token;
_op = op;
}
}
// this should be maintained as a invariantculture sorted array for binary searching
private static readonly ReservedWords[] s_reservedwords = new ReservedWords[] {
new ReservedWords("And", Tokens.BinaryOp, Operators.And),
/*
the following operator is not implemented in the current version of the
Expression language, but we need to add them to the Reserved words list
to prevent future compatibility problems.
*/
new ReservedWords("Between", Tokens.BinaryOp, Operators.Between),
new ReservedWords("Child", Tokens.Child, Operators.Noop),
new ReservedWords("False", Tokens.ZeroOp, Operators.False),
new ReservedWords("In", Tokens.BinaryOp, Operators.In),
new ReservedWords("Is", Tokens.BinaryOp, Operators.Is),
new ReservedWords("Like", Tokens.BinaryOp, Operators.Like),
new ReservedWords("Not", Tokens.UnaryOp, Operators.Not),
new ReservedWords("Null", Tokens.ZeroOp, Operators.Null),
new ReservedWords("Or", Tokens.BinaryOp, Operators.Or),
new ReservedWords("Parent", Tokens.Parent, Operators.Noop),
new ReservedWords("True", Tokens.ZeroOp, Operators.True),
};
/* the following is the Scanner local configuration, Default settings is US
* CONSIDER: should we read the user (or system) local settings?
* CONSIDER: make this configurable by the user, and system locale for the string compare
*/
private char _escape = '\\';
private char _decimalSeparator = '.';
//not used: private char ThousandSeparator = ',';
private char _listSeparator = ',';
//not used: private char DateSeparator = '/';
private char _exponentL = 'e';
private char _exponentU = 'E';
internal char[] _text;
internal int _pos = 0;
internal int _start = 0;
internal Tokens _token;
internal int _op = Operators.Noop;
internal OperatorInfo[] _ops = new OperatorInfo[MaxPredicates];
internal int _topOperator = 0;
internal int _topNode = 0;
private readonly DataTable _table;
private const int MaxPredicates = 100;
internal ExpressionNode[] _nodeStack = new ExpressionNode[MaxPredicates];
internal int _prevOperand;
internal ExpressionNode _expression = null;
internal ExpressionParser(DataTable table)
{
_table = table;
}
internal void LoadExpression(string data)
{
int length;
if (data == null)
{
length = 0;
_text = new char[length + 1];
}
else
{
length = data.Length;
_text = new char[length + 1];
data.CopyTo(0, _text, 0, length);
}
_text[length] = '\0';
if (_expression != null)
{
// free all nodes
_expression = null;
}
}
internal void StartScan()
{
_op = Operators.Noop;
_pos = 0;
_start = 0;
_topOperator = 0;
_ops[_topOperator++] = new OperatorInfo(Nodes.Noop, Operators.Noop, Operators.priStart);
}
// CONSIDER: configure the scanner : local info
internal ExpressionNode Parse()
{
// free all nodes
_expression = null;
StartScan();
int cParens = 0;
OperatorInfo opInfo;
while (_token != Tokens.EOS)
{
loop:
Scan();
switch (_token)
{
case Tokens.EOS:
// End of string: must be operand; force out expression;
// check for bomb; check nothing left on stack.
if (_prevOperand == Empty)
{
if (_topNode == 0)
{
// we have an empty expression
break;
}
// set error missing operator
// read the last operator info
opInfo = _ops[_topOperator - 1];
throw ExprException.MissingOperand(opInfo);
}
// collect all nodes
BuildExpression(Operators.priLow);
if (_topOperator != 1)
{
throw ExprException.MissingRightParen();
}
break;
case Tokens.Name:
case Tokens.Parent:
case Tokens.Numeric:
case Tokens.Decimal:
case Tokens.Float:
case Tokens.StringConst:
case Tokens.Date:
ExpressionNode node = null;
string str = null;
/* Constants and identifiers: create leaf node */
if (_prevOperand != Empty)
{
// set error missing operator
throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
}
if (_topOperator > 0)
{
// special check for IN without parentheses
opInfo = _ops[_topOperator - 1];
if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In && _token != Tokens.Parent)
{
throw ExprException.InWithoutParentheses();
}
}
_prevOperand = Scalar;
switch (_token)
{
case Tokens.Parent:
string relname;
string colname;
// parsing Parent[(relation_name)].column_name)
try
{
// expecting an '(' or '.'
Scan();
if (_token == Tokens.LeftParen)
{
//read the relation name
ScanToken(Tokens.Name);
relname = NameNode.ParseName(_text, _start, _pos);
ScanToken(Tokens.RightParen);
ScanToken(Tokens.Dot);
}
else
{
relname = null;
CheckToken(Tokens.Dot);
}
}
catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
{
throw ExprException.LookupArgument();
}
ScanToken(Tokens.Name);
colname = NameNode.ParseName(_text, _start, _pos);
opInfo = _ops[_topOperator - 1];
node = new LookupNode(_table, colname, relname);
break;
case Tokens.Name:
/* Qualify name now for nice error checking */
opInfo = _ops[_topOperator - 1];
/* Create tree element - */
// CONSIDER: Check for reserved proc names here
node = new NameNode(_table, _text, _start, _pos);
break;
case Tokens.Numeric:
str = new string(_text, _start, _pos - _start);
node = new ConstNode(_table, ValueType.Numeric, str);
break;
case Tokens.Decimal:
str = new string(_text, _start, _pos - _start);
node = new ConstNode(_table, ValueType.Decimal, str);
break;
case Tokens.Float:
str = new string(_text, _start, _pos - _start);
node = new ConstNode(_table, ValueType.Float, str);
break;
case Tokens.StringConst:
Debug.Assert(_text[_start] == '\'' && _text[_pos - 1] == '\'', "The expression contains an invalid string constant");
Debug.Assert(_pos - _start > 1, "The expression contains an invalid string constant");
// Store string without quotes..
str = new string(_text, _start + 1, _pos - _start - 2);
node = new ConstNode(_table, ValueType.Str, str);
break;
case Tokens.Date:
Debug.Assert(_text[_start] == '#' && _text[_pos - 1] == '#', "The expression contains invalid date constant.");
Debug.Assert(_pos - _start > 2, "The expression contains invalid date constant '{0}'.");
// Store date without delimiters(#s)..
str = new string(_text, _start + 1, _pos - _start - 2);
node = new ConstNode(_table, ValueType.Date, str);
break;
default:
Debug.Assert(false, "unhandled token");
break;
}
NodePush(node);
goto loop;
case Tokens.LeftParen:
cParens++;
if (_prevOperand == Empty)
{
// Check for ( following IN/IFF. if not, we have a normal (.
// Peek: take a look at the operators stack
Debug.Assert(_topOperator > 0, "Empty operator stack!!");
opInfo = _ops[_topOperator - 1];
if (opInfo._type == Nodes.Binop && opInfo._op == Operators.In)
{
/* IN - handle as procedure call */
node = new FunctionNode(_table, "In");
NodePush(node);
/* Push operator decriptor */
_ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
}
else
{ /* Normal ( */
/* Push operator decriptor */
_ops[_topOperator++] = new OperatorInfo(Nodes.Paren, Operators.Noop, Operators.priParen);
}
}
else
{
// This is a procedure call or () qualification
// Force out any dot qualifiers; check for bomb
BuildExpression(Operators.priProc);
_prevOperand = Empty;
ExpressionNode nodebefore = NodePeek();
if (nodebefore == null || nodebefore.GetType() != typeof(NameNode))
{
// this is more like an assert, so we not care about "nice" exception text..
throw ExprException.SyntaxError();
}
/* Get the proc name */
NameNode name = (NameNode)NodePop();
// Make sure that we can bind the name as a Function
// then get the argument count and types, and parse arguments..
node = new FunctionNode(_table, name._name);
// check to see if this is an aggregate function
Aggregate agg = (Aggregate)(int)((FunctionNode)node).Aggregate;
if (agg != Aggregate.None)
{
node = ParseAggregateArgument((FunctionId)(int)agg);
NodePush(node);
_prevOperand = Expr;
goto loop;
}
NodePush(node);
_ops[_topOperator++] = new OperatorInfo(Nodes.Call, Operators.Noop, Operators.priParen);
}
goto loop;
case Tokens.RightParen:
{
/* Right parentheses: Build expression if we have an operand. */
if (_prevOperand != Empty)
{
BuildExpression(Operators.priLow);
}
/* We must have Tokens.LeftParen on stack. If no operand, must be procedure call. */
if (_topOperator <= 1)
{
// set error, syntax: too many right parens..
throw ExprException.TooManyRightParentheses();
}
Debug.Assert(_topOperator > 1, "melformed operator stack.");
_topOperator--;
opInfo = _ops[_topOperator];
if (_prevOperand == Empty && opInfo._type != Nodes.Call)
{
// set error, syntax: missing operand.
throw ExprException.MissingOperand(opInfo);
}
Debug.Assert(opInfo._priority == Operators.priParen, "melformed operator stack.");
if (opInfo._type == Nodes.Call)
{
/* add argument to the function call. */
if (_prevOperand != Empty)
{
// read last function argument
ExpressionNode argument = NodePop();
/* Get the procedure name and append argument */
Debug.Assert(_topNode > 0 && NodePeek().GetType() == typeof(FunctionNode), "The function node should be created on '('");
FunctionNode func = (FunctionNode)NodePop();
func.AddArgument(argument);
func.Check();
NodePush(func);
}
}
else
{
/* Normal parentheses: create tree node */
// Construct & Put the Nodes.Paren node on node stack
node = NodePop();
node = new UnaryNode(_table, Operators.Noop, node);
NodePush(node);
}
_prevOperand = Expr;
cParens--;
goto loop;
}
case Tokens.ListSeparator:
{
/* Comma encountered: Must be operand; force out subexpression */
if (_prevOperand == Empty)
{
throw ExprException.MissingOperandBefore(",");
}
/* We are be in a procedure call */
/* build next argument */
BuildExpression(Operators.priLow);
opInfo = _ops[_topOperator - 1];
if (opInfo._type != Nodes.Call)
throw ExprException.SyntaxError();
ExpressionNode argument2 = NodePop();
/* Get the procedure name */
FunctionNode func = (FunctionNode)NodePop();
func.AddArgument(argument2);
NodePush(func);
_prevOperand = Empty;
goto loop;
}
case Tokens.BinaryOp:
if (_prevOperand == Empty)
{
/* Check for unary plus/minus */
if (_op == Operators.Plus)
{
_op = Operators.UnaryPlus;
// fall through to UnaryOperator;
}
else if (_op == Operators.Minus)
{
/* Unary minus */
_op = Operators.Negative;
// fall through to UnaryOperator;
}
else
{
// Error missing operand:
throw ExprException.MissingOperandBefore(Operators.ToString(_op));
}
}
else
{
_prevOperand = Empty;
/* CNSIDER: If we are going to support BETWEEN Translate AND to special BetweenAnd if it is. */
/* Force out to appropriate precedence; push operator. */
BuildExpression(Operators.Priority(_op));
// PushOperator descriptor
_ops[_topOperator++] = new OperatorInfo(Nodes.Binop, _op, Operators.Priority(_op));
goto loop;
}
goto
case Tokens.UnaryOp; // fall through to UnaryOperator;
case Tokens.UnaryOp:
/* Must be no operand. Push it. */
_ops[_topOperator++] = new OperatorInfo(Nodes.Unop, _op, Operators.Priority(_op));
goto loop;
case Tokens.ZeroOp:
// check the we have operator on the stack
if (_prevOperand != Empty)
{
// set error missing operator
throw ExprException.MissingOperator(new string(_text, _start, _pos - _start));
}
// PushOperator descriptor
_ops[_topOperator++] = new OperatorInfo(Nodes.Zop, _op, Operators.priMax);
_prevOperand = Expr;
goto loop;
case Tokens.Dot:
//if there is a name on the stack append it.
ExpressionNode before = NodePeek();
if (before != null && before.GetType() == typeof(NameNode))
{
Scan();
if (_token == Tokens.Name)
{
NameNode nameBefore = (NameNode)NodePop();
string newName = nameBefore._name + "." + NameNode.ParseName(_text, _start, _pos);
NodePush(new NameNode(_table, newName));
goto loop;
}
}
// fall through to default
goto default;
default:
throw ExprException.UnknownToken(new string(_text, _start, _pos - _start), _start + 1);
}
}
goto end_loop;
end_loop:
Debug.Assert(_topNode == 1 || _topNode == 0, "Invalid Node Stack");
_expression = _nodeStack[0];
return _expression;
}
/// <summary>
/// Parse the argument to an Aggregate function. The syntax is
/// Func(child[(relation_name)].column_name)
/// When the function is called we have already parsed the Aggregate name, and open paren
/// </summary>
private ExpressionNode ParseAggregateArgument(FunctionId aggregate)
{
Debug.Assert(_token == Tokens.LeftParen, "ParseAggregateArgument(): Invalid argument, token <> '('");
bool child;
string relname;
string colname;
Scan();
try
{
if (_token != Tokens.Child)
{
if (_token != Tokens.Name)
throw ExprException.AggregateArgument();
colname = NameNode.ParseName(_text, _start, _pos);
ScanToken(Tokens.RightParen);
return new AggregateNode(_table, aggregate, colname);
}
child = (_token == Tokens.Child);
_prevOperand = Scalar;
// expecting an '(' or '.'
Scan();
if (_token == Tokens.LeftParen)
{
//read the relation name
ScanToken(Tokens.Name);
relname = NameNode.ParseName(_text, _start, _pos);
ScanToken(Tokens.RightParen);
ScanToken(Tokens.Dot);
}
else
{
relname = null;
CheckToken(Tokens.Dot);
}
ScanToken(Tokens.Name);
colname = NameNode.ParseName(_text, _start, _pos);
ScanToken(Tokens.RightParen);
}
catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e))
{
throw ExprException.AggregateArgument();
}
return new AggregateNode(_table, aggregate, colname, !child, relname);
}
/// <summary>
/// NodePop - Pop an operand node from the node stack.
/// </summary>
private ExpressionNode NodePop()
{
Debug.Assert(_topNode > 0, "NodePop(): Corrupted node stack");
ExpressionNode node = _nodeStack[--_topNode];
Debug.Assert(null != node, "null NodePop");
return node;
}
/// <summary>
/// NodePeek - Peek at the top node.
/// </summary>
private ExpressionNode NodePeek()
{
if (_topNode <= 0)
return null;
return _nodeStack[_topNode - 1];
}
/// <summary>
/// Push an operand node onto the node stack
/// </summary>
private void NodePush(ExpressionNode node)
{
Debug.Assert(null != node, "null NodePush");
if (_topNode >= MaxPredicates - 2)
{
throw ExprException.ExpressionTooComplex();
}
_nodeStack[_topNode++] = node;
}
/// <summary>
/// Builds expression tree for higher-precedence operator to be used as left
/// operand of current operator. May cause errors - always do ErrorCheck() upin return.
/// </summary>
private void BuildExpression(int pri)
{
ExpressionNode expr = null;
Debug.Assert(pri > Operators.priStart && pri <= Operators.priMax, "Invalid priority value");
/* For all operators of higher or same precedence (we are always
left-associative) */
while (true)
{
Debug.Assert(_topOperator > 0, "Empty operator stack!!");
OperatorInfo opInfo = _ops[_topOperator - 1];
if (opInfo._priority < pri)
goto end_loop;
Debug.Assert(opInfo._priority >= pri, "Invalid prioriry value");
_topOperator--;
ExpressionNode nodeLeft;
ExpressionNode nodeRight;
switch (opInfo._type)
{
case Nodes.Binop:
{
// get right, left operands. Bind them.
nodeRight = NodePop();
nodeLeft = NodePop();
/* This is the place to do type and other checks */
switch (opInfo._op)
{
case Operators.Between:
case Operators.BetweenAnd:
case Operators.BitwiseAnd:
case Operators.BitwiseOr:
case Operators.BitwiseXor:
case Operators.BitwiseNot:
throw ExprException.UnsupportedOperator(opInfo._op);
case Operators.Is:
case Operators.Or:
case Operators.And:
case Operators.EqualTo:
case Operators.NotEqual:
case Operators.Like:
case Operators.LessThen:
case Operators.LessOrEqual:
case Operators.GreaterThen:
case Operators.GreaterOrEqual:
case Operators.In:
break;
default:
Debug.Assert(opInfo._op == Operators.Plus ||
opInfo._op == Operators.Minus ||
opInfo._op == Operators.Multiply ||
opInfo._op == Operators.Divide ||
opInfo._op == Operators.Modulo,
"Invalud Binary operation");
break;
}
Debug.Assert(nodeLeft != null, "Invalid left operand");
Debug.Assert(nodeRight != null, "Invalid right operand");
if (opInfo._op == Operators.Like)
{
expr = new LikeNode(_table, opInfo._op, nodeLeft, nodeRight);
}
else
{
expr = new BinaryNode(_table, opInfo._op, nodeLeft, nodeRight);
}
break;
}
case Nodes.Unop:
/* Unary operator: Pop and bind right op. */
nodeLeft = null;
nodeRight = NodePop();
/* Check for special cases */
switch (opInfo._op)
{
case Operators.Not:
break;
case Operators.BitwiseNot:
throw ExprException.UnsupportedOperator(opInfo._op);
case Operators.Negative:
break;
}
Debug.Assert(nodeLeft == null, "Invalid left operand");
Debug.Assert(nodeRight != null, "Invalid right operand");
expr = new UnaryNode(_table, opInfo._op, nodeRight);
break;
case Nodes.Zop:
/* Intrinsic constant: just create node. */
expr = new ZeroOpNode(opInfo._op);
break;
default:
Debug.Assert(false, "Unhandled operator type");
goto end_loop;
}
Debug.Assert(expr != null, "Failed to create expression");
NodePush(expr);
// countinue while loop;
}
end_loop:
;
}
internal void CheckToken(Tokens token)
{
if (_token != token)
{
throw ExprException.UnknownToken(token, _token, _pos);
}
}
internal Tokens Scan()
{
char ch;
char[] text = _text;
_token = Tokens.None;
while (true)
{
loop:
_start = _pos;
_op = Operators.Noop;
ch = text[_pos++];
switch (ch)
{
case (char)0:
_token = Tokens.EOS;
goto end_loop;
case ' ':
case '\t':
case '\n':
case '\r':
ScanWhite();
goto loop;
case '(':
_token = Tokens.LeftParen;
goto end_loop;
case ')':
_token = Tokens.RightParen;
goto end_loop;
case '#':
ScanDate();
CheckToken(Tokens.Date);
goto end_loop;
case '\'':
ScanString('\'');
CheckToken(Tokens.StringConst);
goto end_loop;
case '=':
_token = Tokens.BinaryOp;
_op = Operators.EqualTo;
goto end_loop;
case '>':
_token = Tokens.BinaryOp;
ScanWhite();
if (text[_pos] == '=')
{
_pos++;
_op = Operators.GreaterOrEqual;
}
else
_op = Operators.GreaterThen;
goto end_loop;
case '<':
_token = Tokens.BinaryOp;
ScanWhite();
if (text[_pos] == '=')
{
_pos++;
_op = Operators.LessOrEqual;
}
else if (text[_pos] == '>')
{
_pos++;
_op = Operators.NotEqual;
}
else
_op = Operators.LessThen;
goto end_loop;
case '+':
_token = Tokens.BinaryOp;
_op = Operators.Plus;
goto end_loop;
case '-':
_token = Tokens.BinaryOp;
_op = Operators.Minus;
goto end_loop;
case '*':
_token = Tokens.BinaryOp;
_op = Operators.Multiply;
goto end_loop;
case '/':
_token = Tokens.BinaryOp;
_op = Operators.Divide;
goto end_loop;
case '%':
_token = Tokens.BinaryOp;
_op = Operators.Modulo;
goto end_loop;
/* Beginning of bitwise operators */
case '&':
_token = Tokens.BinaryOp;
_op = Operators.BitwiseAnd;
goto end_loop;
case '|':
_token = Tokens.BinaryOp;
_op = Operators.BitwiseOr;
goto end_loop;
case '^':
_token = Tokens.BinaryOp;
_op = Operators.BitwiseXor;
goto end_loop;
case '~':
_token = Tokens.BinaryOp;
_op = Operators.BitwiseNot;
goto end_loop;
/* we have bracketed identifier */
case '[':
// BUG: special case
ScanName(']', _escape, "]\\");
CheckToken(Tokens.Name);
goto end_loop;
case '`':
ScanName('`', '`', "`");
CheckToken(Tokens.Name);
goto end_loop;
default:
/* Check for list separator */
if (ch == _listSeparator)
{
_token = Tokens.ListSeparator;
goto end_loop;
}
if (ch == '.')
{
if (_prevOperand == Empty)
{
ScanNumeric();
}
else
{
_token = Tokens.Dot;
}
goto end_loop;
}
/* Check for binary constant */
if (ch == '0' && (text[_pos] == 'x' || text[_pos] == 'X'))
{
ScanBinaryConstant();
_token = Tokens.BinaryConst;
goto end_loop;
}
/* Check for number: digit is always good; . or - only if osNil. */
if (IsDigit(ch))
{
ScanNumeric();
goto end_loop;
}
/* Check for reserved word */
ScanReserved();
if (_token != Tokens.None)
{
goto end_loop;
}
/* Alpha means identifier */
if (IsAlphaNumeric(ch))
{
ScanName();
if (_token != Tokens.None)
{
CheckToken(Tokens.Name);
goto end_loop;
}
}
/* Don't understand that banter at all. */
_token = Tokens.Unknown;
throw ExprException.UnknownToken(new string(text, _start, _pos - _start), _start + 1);
}
}
end_loop:
return _token;
}
/// <summary>
/// ScanNumeric - parse number.
/// In format: [digit|.]*{[e|E]{[+|-]}{digit*}}
/// Further checking is done by constant parser.
/// </summary>
private void ScanNumeric()
{
char[] text = _text;
bool fDot = false;
bool fSientific = false;
Debug.Assert(_pos != 0, "We have at least one digit in the buffer, ScanNumeric()");
Debug.Assert(IsDigit(text[_pos - 1]), "We have at least one digit in the buffer, ScanNumeric(), not a digit");
while (IsDigit(text[_pos]))
{
_pos++;
}
if (text[_pos] == _decimalSeparator)
{
fDot = true;
_pos++;
}
while (IsDigit(text[_pos]))
{
_pos++;
}
if (text[_pos] == _exponentL || text[_pos] == _exponentU)
{
fSientific = true;
_pos++;
if (text[_pos] == '-' || text[_pos] == '+')
{
_pos++;
}
while (IsDigit(text[_pos]))
{
_pos++;
}
}
if (fSientific)
_token = Tokens.Float;
else if (fDot)
_token = Tokens.Decimal;
else
_token = Tokens.Numeric;
}
/// <summary>
/// Just a string of alphanumeric characters.
/// </summary>
private void ScanName()
{
char[] text = _text;
while (IsAlphaNumeric(text[_pos]))
_pos++;
_token = Tokens.Name;
}
/// <summary>
/// recognize bracketed identifiers.
/// Special case: we are using '\' character to escape '[' and ']' only, so '\' by itself is not an escape
/// </summary>
private void ScanName(char chEnd, char esc, string charsToEscape)
{
char[] text = _text;
Debug.Assert(chEnd != '\0', "Invalid bracket value");
Debug.Assert(esc != '\0', "Invalid escape value");
do
{
if (text[_pos] == esc)
{
if (_pos + 1 < text.Length && charsToEscape.IndexOf(text[_pos + 1]) >= 0)
{
_pos++;
}
}
_pos++;
} while (_pos < text.Length && text[_pos] != chEnd);
if (_pos >= text.Length)
{
throw ExprException.InvalidNameBracketing(new string(text, _start, (_pos - 1) - _start));
}
Debug.Assert(text[_pos] == chEnd, "Invalid bracket value");
_pos++;
_token = Tokens.Name;
}
/// <summary>
/// Just read the string between '#' signs, and parse it later
/// </summary>
private void ScanDate()
{
char[] text = _text;
do _pos++; while (_pos < text.Length && text[_pos] != '#');
if (_pos >= text.Length || text[_pos] != '#')
{
// Bad date constant
if (_pos >= text.Length)
throw ExprException.InvalidDate(new string(text, _start, (_pos - 1) - _start));
else
throw ExprException.InvalidDate(new string(text, _start, _pos - _start));
}
else
{
_token = Tokens.Date;
}
_pos++;
}
private void ScanBinaryConstant()
{
char[] text = _text;
}
private void ScanReserved()
{
char[] text = _text;
if (IsAlpha(text[_pos]))
{
ScanName();
Debug.Assert(_token == Tokens.Name, "Exprecing an identifier.");
Debug.Assert(_pos > _start, "Exprecing an identifier.");
string name = new string(text, _start, _pos - _start);
Debug.Assert(name != null, "Make sure the arguments for Compare method are OK");
CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo;
// binary search reserved words
int lo = 0;
int hi = s_reservedwords.Length - 1;
do
{
int i = (lo + hi) / 2;
Debug.Assert(s_reservedwords[i]._word != null, "Make sure the arguments for Compare method are OK");
int c = comparer.Compare(s_reservedwords[i]._word, name, CompareOptions.IgnoreCase);
if (c == 0)
{
// we found the reserved word..
_token = s_reservedwords[i]._token;
_op = s_reservedwords[i]._op;
return;
}
if (c < 0)
{
lo = i + 1;
}
else
{
hi = i - 1;
}
} while (lo <= hi);
Debug.Assert(_token == Tokens.Name, "Exprecing an identifier.");
}
}
private void ScanString(char escape)
{
char[] text = _text;
while (_pos < text.Length)
{
char ch = text[_pos++];
if (ch == escape && _pos < text.Length && text[_pos] == escape)
{
_pos++;
}
else if (ch == escape)
break;
}
if (_pos >= text.Length)
{
throw ExprException.InvalidString(new string(text, _start, (_pos - 1) - _start));
}
_token = Tokens.StringConst;
}
// scan the next token, and error if it doesn't match the requested token
internal void ScanToken(Tokens token)
{
Scan();
CheckToken(token);
}
private void ScanWhite()
{
char[] text = _text;
while (_pos < text.Length && IsWhiteSpace(text[_pos]))
{
_pos++;
}
}
/// <summary>
/// is the character a whitespace character?
/// Consider using CharacterInfo().IsWhiteSpace(ch) (System.Globalization)
/// </summary>
private bool IsWhiteSpace(char ch)
{
return ch <= 32 && ch != '\0';
}
/// <summary>
/// is the character an alphanumeric?
/// </summary>
private bool IsAlphaNumeric(char ch)
{
//single comparison
switch (ch)
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '_':
case '$':
return true;
default:
if (ch > 0x7f)
return true;
return false;
}
}
private bool IsDigit(char ch)
{
//single comparison
switch (ch)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return true;
default:
return false;
}
}
/// <summary>
/// is the character an alpha?
/// </summary>
private bool IsAlpha(char ch)
{
//single comparison
switch (ch)
{
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'S':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
case '_':
return true;
default:
return false;
}
}
}
internal enum Tokens
{
None = 0,
Name = 1, /* Identifier */
Numeric = 2,
Decimal = 3,
Float = 4,
BinaryConst = 5, /* Binary Constant e.g. 0x12ef */
StringConst = 6,
Date = 7,
ListSeparator = 8, /* List Tokens.ListSeparator/Comma */
LeftParen = 9, /* '('; */
RightParen = 10, /* ')'; */
ZeroOp = 11, /* 0-array operator like "NULL" */
UnaryOp = 12,
BinaryOp = 13,
Child = 14,
Parent = 15,
Dot = 16,
Unknown = 17, /* do not understend the token */
EOS = 18, /* End of string */
}
/// <summary>
/// Operator stack element
/// </summary>
internal sealed class OperatorInfo
{
internal Nodes _type = 0;
internal int _op = 0;
internal int _priority = 0;
internal OperatorInfo(Nodes type, int op, int pri)
{
_type = type;
_op = op;
_priority = pri;
}
}
}
| |
// 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!
namespace Google.Cloud.Compute.V1.Snippets
{
using Google.Api.Gax;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lro = Google.LongRunning;
/// <summary>Generated snippets.</summary>
public sealed class AllGeneratedSslCertificatesClientSnippets
{
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedListRequestObject()
{
// Snippet: AggregatedList(AggregatedListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
AggregatedListSslCertificatesRequest request = new AggregatedListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedList(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, SslCertificatesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListRequestObjectAsync()
{
// Snippet: AggregatedListAsync(AggregatedListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
AggregatedListSslCertificatesRequest request = new AggregatedListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
IncludeAllScopes = false,
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, SslCertificatesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedList</summary>
public void AggregatedList()
{
// Snippet: AggregatedList(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedList(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (KeyValuePair<string, SslCertificatesScopedList> item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateAggregatedList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for AggregatedListAsync</summary>
public async Task AggregatedListAsync()
{
// Snippet: AggregatedListAsync(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SslCertificateAggregatedList, KeyValuePair<string, SslCertificatesScopedList>> response = sslCertificatesClient.AggregatedListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((KeyValuePair<string, SslCertificatesScopedList> item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateAggregatedList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<KeyValuePair<string, SslCertificatesScopedList>> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (KeyValuePair<string, SslCertificatesScopedList> item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void DeleteRequestObject()
{
// Snippet: Delete(DeleteSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
DeleteSslCertificateRequest request = new DeleteSslCertificateRequest
{
RequestId = "",
SslCertificate = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Delete(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteRequestObjectAsync()
{
// Snippet: DeleteAsync(DeleteSslCertificateRequest, CallSettings)
// Additional: DeleteAsync(DeleteSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
DeleteSslCertificateRequest request = new DeleteSslCertificateRequest
{
RequestId = "",
SslCertificate = "",
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.DeleteAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Delete</summary>
public void Delete()
{
// Snippet: Delete(string, string, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Delete(project, sslCertificate);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceDelete(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteAsync</summary>
public async Task DeleteAsync()
{
// Snippet: DeleteAsync(string, string, CallSettings)
// Additional: DeleteAsync(string, string, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.DeleteAsync(project, sslCertificate);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceDeleteAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Get</summary>
public void GetRequestObject()
{
// Snippet: Get(GetSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
GetSslCertificateRequest request = new GetSslCertificateRequest
{
SslCertificate = "",
Project = "",
};
// Make the request
SslCertificate response = sslCertificatesClient.Get(request);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetRequestObjectAsync()
{
// Snippet: GetAsync(GetSslCertificateRequest, CallSettings)
// Additional: GetAsync(GetSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
GetSslCertificateRequest request = new GetSslCertificateRequest
{
SslCertificate = "",
Project = "",
};
// Make the request
SslCertificate response = await sslCertificatesClient.GetAsync(request);
// End snippet
}
/// <summary>Snippet for Get</summary>
public void Get()
{
// Snippet: Get(string, string, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
SslCertificate response = sslCertificatesClient.Get(project, sslCertificate);
// End snippet
}
/// <summary>Snippet for GetAsync</summary>
public async Task GetAsync()
{
// Snippet: GetAsync(string, string, CallSettings)
// Additional: GetAsync(string, string, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
string sslCertificate = "";
// Make the request
SslCertificate response = await sslCertificatesClient.GetAsync(project, sslCertificate);
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void InsertRequestObject()
{
// Snippet: Insert(InsertSslCertificateRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
InsertSslCertificateRequest request = new InsertSslCertificateRequest
{
RequestId = "",
SslCertificateResource = new SslCertificate(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Insert(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertRequestObjectAsync()
{
// Snippet: InsertAsync(InsertSslCertificateRequest, CallSettings)
// Additional: InsertAsync(InsertSslCertificateRequest, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
InsertSslCertificateRequest request = new InsertSslCertificateRequest
{
RequestId = "",
SslCertificateResource = new SslCertificate(),
Project = "",
};
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.InsertAsync(request);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for Insert</summary>
public void Insert()
{
// Snippet: Insert(string, SslCertificate, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
SslCertificate sslCertificateResource = new SslCertificate();
// Make the request
lro::Operation<Operation, Operation> response = sslCertificatesClient.Insert(project, sslCertificateResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = sslCertificatesClient.PollOnceInsert(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for InsertAsync</summary>
public async Task InsertAsync()
{
// Snippet: InsertAsync(string, SslCertificate, CallSettings)
// Additional: InsertAsync(string, SslCertificate, CancellationToken)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
SslCertificate sslCertificateResource = new SslCertificate();
// Make the request
lro::Operation<Operation, Operation> response = await sslCertificatesClient.InsertAsync(project, sslCertificateResource);
// Poll until the returned long-running operation is complete
lro::Operation<Operation, Operation> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Operation result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
lro::Operation<Operation, Operation> retrievedResponse = await sslCertificatesClient.PollOnceInsertAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Operation retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for List</summary>
public void ListRequestObject()
{
// Snippet: List(ListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
ListSslCertificatesRequest request = new ListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.List(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (SslCertificate item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListRequestObjectAsync()
{
// Snippet: ListAsync(ListSslCertificatesRequest, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
ListSslCertificatesRequest request = new ListSslCertificatesRequest
{
OrderBy = "",
Project = "",
Filter = "",
ReturnPartialSuccess = false,
};
// Make the request
PagedAsyncEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.ListAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SslCertificate item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for List</summary>
public void List()
{
// Snippet: List(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = SslCertificatesClient.Create();
// Initialize request argument(s)
string project = "";
// Make the request
PagedEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.List(project);
// Iterate over all response items, lazily performing RPCs as required
foreach (SslCertificate item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (SslCertificateList page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListAsync</summary>
public async Task ListAsync()
{
// Snippet: ListAsync(string, string, int?, CallSettings)
// Create client
SslCertificatesClient sslCertificatesClient = await SslCertificatesClient.CreateAsync();
// Initialize request argument(s)
string project = "";
// Make the request
PagedAsyncEnumerable<SslCertificateList, SslCertificate> response = sslCertificatesClient.ListAsync(project);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((SslCertificate item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((SslCertificateList page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (SslCertificate item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<SslCertificate> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (SslCertificate item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System;
using System.Linq;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using Subtext.Framework.Configuration;
using Subtext.Framework.Routing;
using Subtext.Framework.Text;
using Subtext.Framework.Properties;
namespace Subtext.Framework.Web
{
/// <summary>
/// Static containing helper methods for HTTP operations.
/// </summary>
public static class HttpHelper
{
private const int DefaultTimeout = 60000;
private static readonly string UserAgent = string.Format("{0} ({1}; .NET CLR {2})", VersionInfo.UserAgent, Environment.OSVersion, Environment.Version);
private const string Referer = @"http://SubtextProject.com/Services/default.htm";
/// <summary>
/// Sets the file not found response.
/// </summary>
public static void SetFileNotFoundResponse()
{
if(HttpContext.Current != null && HttpContext.Current.Response != null)
{
SetFileNotFoundResponse(Config.GetFileNotFoundPage());
}
}
/// <param name="fileNotFoundPage">The file not found page.</param>
private static void SetFileNotFoundResponse(string fileNotFoundPage)
{
HttpContext.Current.Response.StatusCode = 404;
if(fileNotFoundPage != null)
{
HttpContext.Current.Response.Redirect(fileNotFoundPage, true);
}
}
public static void RedirectPermanent(this HttpResponseBase response, string url)
{
response.StatusCode = 301;
response.StatusDescription = "301 Moved Permanently";
response.RedirectLocation = url;
response.End();
}
/// <summary>
/// Gets if modified since date.
/// </summary>
/// <returns></returns>
public static DateTime GetIfModifiedSinceDateUtc(HttpRequestBase request)
{
if(request != null)
{
string ifModified = request.Headers["If-Modified-Since"];
if(!string.IsNullOrEmpty(ifModified))
{
return DateTimeHelper.ParseUnknownFormatUtc(ifModified);
}
}
return NullValue.NullDateTime;
}
/// <summary>
/// Creates an <see cref="HttpWebRequest" /> for the specified URL..
/// </summary>
/// <param name="url">The URL.</param>
/// <returns></returns>
public static HttpWebRequest CreateRequest(Uri url)
{
WebRequest req = WebRequest.Create(url);
SetProxy(req);
var wreq = req as HttpWebRequest;
if(null != wreq)
{
wreq.UserAgent = UserAgent;
wreq.Referer = Referer;
wreq.Timeout = DefaultTimeout;
}
return wreq;
}
/// <summary>
/// Returns an <see cref="HttpWebResponse" /> for the specified URL.
/// </summary>
/// <param name="url">The URL.</param>
/// <returns></returns>
public static HttpWebResponse GetResponse(Uri url)
{
HttpWebRequest request = CreateRequest(url);
return (HttpWebResponse)request.GetResponse();
}
/// <summary>
/// Returns the text of the page specified by the URL..
/// </summary>
/// <param name="url">The URL.</param>
/// <returns></returns>
public static string GetPageText(Uri url)
{
HttpWebResponse response = GetResponse(url);
using(Stream s = response.GetResponseStream())
{
string enc = response.ContentEncoding;
if(enc == null || enc.Trim().Length == 0)
{
enc = "us-ascii";
}
Encoding encode = Encoding.GetEncoding(enc);
using(var sr = new StreamReader(s, encode))
{
return sr.ReadToEnd();
}
}
}
/// <summary>
/// Returns the IP Address of the user making the current request.
/// </summary>
/// <param name="context">The context.</param>
/// <returns></returns>
public static IPAddress GetUserIpAddress(HttpContextBase context)
{
if(context == null)
{
return IPAddress.None;
}
string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if(String.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.UserHostAddress;
}
else
{
// Requests behind a proxy might contain multiple IP
// addresses in the forwarding header.
if(result.IndexOf(",", StringComparison.Ordinal) > 0)
{
result = StringHelper.LeftBefore(result, ",");
}
}
IPAddress ipAddress;
if(IPAddress.TryParse(result, out ipAddress))
{
return ipAddress;
}
return IPAddress.None;
}
/// <summary>
/// Combines Two Web Paths much like the Path.Combine method.
/// </summary>
/// <param name="uriOne">The URI one.</param>
/// <param name="uriTwo">The URI two.</param>
/// <returns></returns>
public static string CombineWebPaths(string uriOne, string uriTwo)
{
string newUri = (uriOne + uriTwo);
return newUri.Replace("//", "/");
}
/// <summary>
/// Determines whether the request is for a static file.
/// </summary>
/// <returns>
/// <c>true</c> if [is static file request]; otherwise, <c>false</c>.
/// </returns>
public static bool IsStaticFileRequest(this HttpRequestBase request)
{
if(request == null)
{
throw new ArgumentNullException("request");
}
return request.Url.IsStaticFileRequest();
}
/// <summary>
/// Determines whether the request is for a static file.
/// </summary>
/// <returns>
/// <c>true</c> if [is static file request]; otherwise, <c>false</c>.
/// </returns>
public static bool IsStaticFileRequest(this Uri url)
{
string filePath = url.AbsolutePath;
return filePath.EndsWith(".css", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".js", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".txt", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".html", StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(".htm", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Sets the proxy on the request if a proxy is configured in Web.config.
/// </summary>
/// <param name="request"></param>
public static void SetProxy(WebRequest request)
{
IWebProxy proxy = GetProxy();
if(proxy != null)
{
request.Proxy = proxy;
}
}
internal static IWebProxy GetProxy()
{
if(String.IsNullOrEmpty(ConfigurationManager.AppSettings["ProxyHost"]))
{
return null;
}
string proxyHost = ConfigurationManager.AppSettings["ProxyHost"];
int proxyPort;
IWebProxy proxy = int.TryParse(ConfigurationManager.AppSettings["ProxyPort"], out proxyPort) ? new WebProxy(proxyHost, proxyPort) : new WebProxy(proxyHost);
if(!String.IsNullOrEmpty(ConfigurationManager.AppSettings["ProxyUsername"]))
{
proxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["ProxyUsername"],
ConfigurationManager.AppSettings["ProxyPassword"]);
}
return proxy;
}
/// <summary>
/// If the URL is is the format ~/SomePath, this
/// method expands the tilde using the app path.
/// </summary>
/// <param name="path"></param>
public static string ExpandTildePath(string path)
{
if(String.IsNullOrEmpty(path))
{
return string.Empty;
}
string reference = path;
if(reference.Substring(0, 2) == "~/")
{
string appPath = HttpContext.Current.Request.ApplicationPath ?? string.Empty;
if(appPath.EndsWith("/", StringComparison.Ordinal))
{
appPath = appPath.Left(appPath.Length - 1);
}
return appPath + reference.Substring(1);
}
return path;
}
/// <summary>
/// If the URL is is the format ~/SomePath, this
/// method expands the tilde using the app path.
/// </summary>
public static VirtualPath ExpandTildePath(this HttpContextBase httpContext, string path)
{
if(String.IsNullOrEmpty(path))
{
return string.Empty;
}
string reference = path;
if(reference.Substring(0, 2) == "~/")
{
string appPath = httpContext.Request.ApplicationPath ?? string.Empty;
if(appPath.EndsWith("/", StringComparison.Ordinal))
{
appPath = appPath.Left(appPath.Length - 1);
}
return appPath + reference.Substring(1);
}
return path;
}
/// <summary>
/// gets the bytes for the posted file
/// </summary>
/// <returns></returns>
public static byte[] GetFileStream(this HttpPostedFile httpPostedFile)
{
if(httpPostedFile != null)
{
int contentLength = httpPostedFile.ContentLength;
var input = new byte[contentLength];
Stream file = httpPostedFile.InputStream;
file.Read(input, 0, contentLength);
return input;
}
return null;
}
/// <summary>
/// Returns a MimeType from a URL
/// </summary>
/// <param name="fullUrl">The URL to check for a mime type</param>
/// <returns>A string representation of the mimetype</returns>
public static string GetMimeType(this string fullUrl)
{
string extension = Path.GetExtension(fullUrl);
if(string.IsNullOrEmpty(extension))
{
return string.Empty;
}
switch(extension.ToUpperInvariant())
{
case ".PNG":
return "image/png";
case ".JPG":
case ".JPEG":
return "image/jpeg";
case ".BMP":
return "image/bmp";
case ".GIF":
return "image/gif";
default:
return "none";
}
}
public static string GetSafeFileName(this string text)
{
if(string.IsNullOrEmpty(text))
{
throw new ArgumentNullException("text");
}
var badChars = Path.GetInvalidFileNameChars();
foreach(var badChar in badChars)
{
if(text.Contains(badChar))
{
text = text.Replace(string.Format("{0}", badChar), string.Empty);
}
}
return text;
}
/// <summary>
/// From Jason Block @ http://www.angrycoder.com/article.aspx?cid=5&y=2003&m=4&d=15
/// Basically, it's [Request.UrlReferrer] doing a lazy initialization of its internal
/// _referrer field, which is a Uri-type class. That is, it's not created until it's
/// needed. The point is that there are a couple of spots where the UriFormatException
/// could leak through. One is in the call to GetKnownRequestHeader(). _wr is a field
/// of type HttpWorkerRequest. 36 is the value of the HeaderReferer constant - since
/// that's being blocked in this case, it may cause that exception to occur. However,
/// HttpWorkerRequest is an abstract class, and it took a trip to the debugger to find
/// out that _wr is set to a System.Web.Hosting.ISAPIWorkerRequestOutOfProc object.
/// This descends from System.Web.Hosting.ISAPIWorkerRequest, and its implementation
/// of GetKnownRequestHeader() didn't seem to be the source of the problem.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static Uri GetUriReferrerSafe(this HttpRequestBase request)
{
try
{
return request.UrlReferrer;
}
catch(UriFormatException)
{
return null;
}
}
public static void HandleFileNotFound(this HttpContextBase httpContext, bool usingIntegratedPipeline)
{
var response = httpContext.Response;
var request = httpContext.Request;
string url = request.GetFileNotFoundRedirectUrl(usingIntegratedPipeline);
if(!String.IsNullOrEmpty(url))
{
response.Redirect(url, true);
}
else
{
response.StatusCode = 404;
response.StatusDescription = Resources.FileNotFound;
}
}
public static string GetFileNotFoundRedirectUrl(this HttpRequestBase request, bool usingIntegratedPipeline)
{
if(usingIntegratedPipeline || (request.QueryString == null || request.QueryString.Count == 0))
{
return null;
}
string key = request.QueryString.Keys[0];
if(key != null && key.Equals("referrer", StringComparison.InvariantCultureIgnoreCase))
return null;
string queryString = request.QueryString[0];
if(string.IsNullOrEmpty(queryString))
{
return null;
}
if(!queryString.Contains(";"))
{
return null;
}
string urlText = queryString.RightAfter(";");
if(String.IsNullOrEmpty(urlText))
{
return null;
}
Uri uri = urlText.ParseUri();
if(uri == null)
{
return null;
}
string extension = Path.GetExtension(uri.AbsolutePath);
if(string.IsNullOrEmpty(extension))
{
string uriAbsolutePath = uri.AbsolutePath;
if(!uriAbsolutePath.EndsWith("/"))
{
uriAbsolutePath += "/";
}
return uriAbsolutePath + "default.aspx";
}
return null;
}
/// <summary>
/// Strips the surrounding slashes from the specified string.
/// </summary>
/// <param name="target">The target.</param>
/// <returns></returns>
public static string StripSurroundingSlashes(string target)
{
if(target == null)
{
throw new ArgumentNullException("target");
}
if(target.EndsWith("/"))
{
target = target.Remove(target.Length - 1, 1);
}
if(target.StartsWith("/"))
{
target = target.Remove(0, 1);
}
return target;
}
}
}
| |
using System.Collections.Generic;
using Microsoft.Xna.Framework.Input;
namespace Nez
{
/// <summary>
/// A virtual input that is represented as a boolean. As well as simply checking the current button state, you can ask whether
/// it was just pressed or released this frame. You can also keep the button press stored in a buffer for a limited time, or
/// until it is consumed by calling consumeBuffer()
/// </summary>
public class VirtualButton : VirtualInput
{
public List<Node> Nodes;
public float BufferTime;
public float FirstRepeatTime;
public float MultiRepeatTime;
public bool IsRepeating { get; private set; }
float _bufferCounter;
float _repeatCounter;
bool _willRepeat;
public VirtualButton(float bufferTime)
{
Nodes = new List<Node>();
BufferTime = bufferTime;
}
public VirtualButton() : this(0)
{
}
public VirtualButton(float bufferTime, params Node[] nodes)
{
Nodes = new List<Node>(nodes);
BufferTime = bufferTime;
}
public VirtualButton(params Node[] nodes) : this(0, nodes)
{
}
public void SetRepeat(float repeatTime)
{
SetRepeat(repeatTime, repeatTime);
}
public void SetRepeat(float firstRepeatTime, float multiRepeatTime)
{
FirstRepeatTime = firstRepeatTime;
MultiRepeatTime = multiRepeatTime;
_willRepeat = firstRepeatTime > 0;
if (!_willRepeat)
IsRepeating = false;
}
public override void Update()
{
_bufferCounter -= Time.UnscaledDeltaTime;
IsRepeating = false;
var check = false;
for (var i = 0; i < Nodes.Count; i++)
{
Nodes[i].Update();
if (Nodes[i].IsPressed)
{
_bufferCounter = BufferTime;
check = true;
}
else if (Nodes[i].IsDown)
{
check = true;
}
}
if (!check)
{
_repeatCounter = 0;
_bufferCounter = 0;
}
else if (_willRepeat)
{
if (_repeatCounter == 0)
{
_repeatCounter = FirstRepeatTime;
}
else
{
_repeatCounter -= Time.UnscaledDeltaTime;
if (_repeatCounter <= 0)
{
IsRepeating = true;
_repeatCounter = MultiRepeatTime;
}
}
}
}
public bool IsDown
{
get
{
foreach (var node in Nodes)
if (node.IsDown)
return true;
return false;
}
}
public bool IsPressed
{
get
{
if (_bufferCounter > 0 || IsRepeating)
return true;
foreach (var node in Nodes)
if (node.IsPressed)
return true;
return false;
}
}
public bool IsReleased
{
get
{
foreach (var node in Nodes)
if (node.IsReleased)
return true;
return false;
}
}
public void ConsumeBuffer()
{
_bufferCounter = 0;
}
#region Node management
/// <summary>
/// adds a keyboard key to this VirtualButton
/// </summary>
/// <returns>The keyboard key.</returns>
/// <param name="key">Key.</param>
public VirtualButton AddKeyboardKey(Keys key)
{
Nodes.Add(new KeyboardKey(key));
return this;
}
/// <summary>
/// adds a keyboard key with modifier to this VirtualButton. modifier must be in the down state for isPressed/isDown to be true.
/// </summary>
/// <returns>The keyboard key.</returns>
/// <param name="key">Key.</param>
/// <param name="modifier">Modifier.</param>
public VirtualButton AddKeyboardKey(Keys key, Keys modifier)
{
Nodes.Add(new KeyboardModifiedKey(key, modifier));
return this;
}
/// <summary>
/// adds a GamePad buttons press to this VirtualButton
/// </summary>
/// <returns>The game pad button.</returns>
/// <param name="gamepadIndex">Gamepad index.</param>
/// <param name="button">Button.</param>
public VirtualButton AddGamePadButton(int gamepadIndex, Buttons button)
{
Nodes.Add(new GamePadButton(gamepadIndex, button));
return this;
}
/// <summary>
/// adds a GamePad left trigger press to this VirtualButton
/// </summary>
/// <returns>The game pad left trigger.</returns>
/// <param name="gamepadIndex">Gamepad index.</param>
/// <param name="threshold">Threshold.</param>
public VirtualButton AddGamePadLeftTrigger(int gamepadIndex, float threshold)
{
Nodes.Add(new GamePadLeftTrigger(gamepadIndex, threshold));
return this;
}
/// <summary>
/// adds a GamePad right trigger press to this VirtualButton
/// </summary>
/// <returns>The game pad right trigger.</returns>
/// <param name="gamepadIndex">Gamepad index.</param>
/// <param name="threshold">Threshold.</param>
public VirtualButton AddGamePadRightTrigger(int gamepadIndex, float threshold)
{
Nodes.Add(new GamePadRightTrigger(gamepadIndex, threshold));
return this;
}
/// <summary>
/// adds a GamePad DPad press to this VirtualButton
/// </summary>
/// <returns>The game pad DP ad.</returns>
/// <param name="gamepadIndex">Gamepad index.</param>
/// <param name="direction">Direction.</param>
public VirtualButton AddGamePadDPad(int gamepadIndex, Direction direction)
{
switch (direction)
{
case Direction.Up:
Nodes.Add(new GamePadDPadUp(gamepadIndex));
break;
case Direction.Down:
Nodes.Add(new GamePadDPadDown(gamepadIndex));
break;
case Direction.Left:
Nodes.Add(new GamePadDPadLeft(gamepadIndex));
break;
case Direction.Right:
Nodes.Add(new GamePadDPadRight(gamepadIndex));
break;
}
return this;
}
/// <summary>
/// adds a left mouse click to this VirtualButton
/// </summary>
/// <returns>The mouse left button.</returns>
public VirtualButton AddMouseLeftButton()
{
Nodes.Add(new MouseLeftButton());
return this;
}
/// <summary>
/// adds a right mouse click to this VirtualButton
/// </summary>
/// <returns>The mouse right button.</returns>
public VirtualButton AddMouseRightButton()
{
Nodes.Add(new MouseRightButton());
return this;
}
/// <summary>
/// adds a right mouse click to this VirtualButton
/// </summary>
/// <returns>The mouse right button.</returns>
public VirtualButton AddMouseMiddleButton()
{
Nodes.Add(new MouseMiddleButton());
return this;
}
/// <summary>
/// adds a right mouse click to this VirtualButton
/// </summary>
/// <returns>The mouse right button.</returns>
public VirtualButton AddMouseFirstExtendedButton()
{
Nodes.Add(new MouseFirstExtendedButton());
return this;
}
/// <summary>
/// adds a right mouse click to this VirtualButton
/// </summary>
/// <returns>The mouse right button.</returns>
public VirtualButton AddMouseSecondExtendedButton()
{
Nodes.Add(new MouseSecondExtendedButton());
return this;
}
#endregion
public static implicit operator bool(VirtualButton button)
{
return button.IsDown;
}
#region Node types
public abstract class Node : VirtualInputNode
{
public abstract bool IsDown { get; }
public abstract bool IsPressed { get; }
public abstract bool IsReleased { get; }
}
#region Keyboard
public class KeyboardKey : Node
{
public Keys Key;
public KeyboardKey(Keys key)
{
Key = key;
}
public override bool IsDown => Input.IsKeyDown(Key);
public override bool IsPressed => Input.IsKeyPressed(Key);
public override bool IsReleased => Input.IsKeyReleased(Key);
}
/// <summary>
/// works like KeyboardKey except the modifier key must also be down for isDown/isPressed to be true. isReleased checks only key.
/// </summary>
public class KeyboardModifiedKey : Node
{
public Keys Key;
public Keys Modifier;
public KeyboardModifiedKey(Keys key, Keys modifier)
{
Key = key;
Modifier = modifier;
}
public override bool IsDown => Input.IsKeyDown(Modifier) && Input.IsKeyDown(Key);
public override bool IsPressed => Input.IsKeyDown(Modifier) && Input.IsKeyPressed(Key);
public override bool IsReleased => Input.IsKeyReleased(Key);
}
#endregion
#region GamePad Buttons and Triggers
public class GamePadButton : Node
{
public int GamepadIndex;
public Buttons Button;
public GamePadButton(int gamepadIndex, Buttons button)
{
GamepadIndex = gamepadIndex;
Button = button;
}
public override bool IsDown => Input.GamePads[GamepadIndex].IsButtonDown(Button);
public override bool IsPressed => Input.GamePads[GamepadIndex].IsButtonPressed(Button);
public override bool IsReleased => Input.GamePads[GamepadIndex].IsButtonReleased(Button);
}
public class GamePadLeftTrigger : Node
{
public int GamepadIndex;
public float Threshold;
public GamePadLeftTrigger(int gamepadIndex, float threshold)
{
GamepadIndex = gamepadIndex;
Threshold = threshold;
}
public override bool IsDown => Input.GamePads[GamepadIndex].IsLeftTriggerDown(Threshold);
public override bool IsPressed => Input.GamePads[GamepadIndex].IsLeftTriggerPressed(Threshold);
public override bool IsReleased => Input.GamePads[GamepadIndex].IsLeftTriggerReleased(Threshold);
}
public class GamePadRightTrigger : Node
{
public int GamepadIndex;
public float Threshold;
public GamePadRightTrigger(int gamepadIndex, float threshold)
{
GamepadIndex = gamepadIndex;
Threshold = threshold;
}
public override bool IsDown => Input.GamePads[GamepadIndex].IsRightTriggerDown(Threshold);
public override bool IsPressed => Input.GamePads[GamepadIndex].IsRightTriggerPressed(Threshold);
public override bool IsReleased => Input.GamePads[GamepadIndex].IsRightTriggerReleased(Threshold);
}
#endregion
#region GamePad DPad
public class GamePadDPadRight : Node
{
public int GamepadIndex;
public GamePadDPadRight(int gamepadIndex)
{
GamepadIndex = gamepadIndex;
}
public override bool IsDown => Input.GamePads[GamepadIndex].DpadRightDown;
public override bool IsPressed => Input.GamePads[GamepadIndex].DpadRightPressed;
public override bool IsReleased => Input.GamePads[GamepadIndex].DpadRightReleased;
}
public class GamePadDPadLeft : Node
{
public int GamepadIndex;
public GamePadDPadLeft(int gamepadIndex)
{
GamepadIndex = gamepadIndex;
}
public override bool IsDown => Input.GamePads[GamepadIndex].DpadLeftDown;
public override bool IsPressed => Input.GamePads[GamepadIndex].DpadLeftPressed;
public override bool IsReleased => Input.GamePads[GamepadIndex].DpadLeftReleased;
}
public class GamePadDPadUp : Node
{
public int GamepadIndex;
public GamePadDPadUp(int gamepadIndex)
{
GamepadIndex = gamepadIndex;
}
public override bool IsDown => Input.GamePads[GamepadIndex].DpadUpDown;
public override bool IsPressed => Input.GamePads[GamepadIndex].DpadUpPressed;
public override bool IsReleased => Input.GamePads[GamepadIndex].DpadUpReleased;
}
public class GamePadDPadDown : Node
{
public int GamepadIndex;
public GamePadDPadDown(int gamepadIndex)
{
GamepadIndex = gamepadIndex;
}
public override bool IsDown => Input.GamePads[GamepadIndex].DpadDownDown;
public override bool IsPressed => Input.GamePads[GamepadIndex].DpadDownPressed;
public override bool IsReleased => Input.GamePads[GamepadIndex].DpadDownReleased;
}
#endregion
#region Mouse
public class MouseLeftButton : Node
{
public override bool IsDown => Input.LeftMouseButtonDown;
public override bool IsPressed => Input.LeftMouseButtonPressed;
public override bool IsReleased => Input.LeftMouseButtonReleased;
}
public class MouseRightButton : Node
{
public override bool IsDown => Input.RightMouseButtonDown;
public override bool IsPressed => Input.RightMouseButtonPressed;
public override bool IsReleased => Input.RightMouseButtonReleased;
}
public class MouseMiddleButton : Node
{
public override bool IsDown => Input.MiddleMouseButtonDown;
public override bool IsPressed => Input.MiddleMouseButtonPressed;
public override bool IsReleased => Input.MiddleMouseButtonReleased;
}
public class MouseFirstExtendedButton : Node
{
public override bool IsDown => Input.FirstExtendedMouseButtonDown;
public override bool IsPressed => Input.FirstExtendedMouseButtonPressed;
public override bool IsReleased => Input.FirstExtendedMouseButtonReleased;
}
public class MouseSecondExtendedButton : Node
{
public override bool IsDown => Input.SecondExtendedMouseButtonDown;
public override bool IsPressed => Input.SecondExtendedMouseButtonPressed;
public override bool IsReleased => Input.SecondExtendedMouseButtonReleased;
}
#endregion
#endregion
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.38.0
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Google Fonts Developer API Version v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/fonts/docs/developer_api'>Google Fonts Developer API</a>
* <tr><th>API Version<td>v1
* <tr><th>API Rev<td>20160302 (426)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/fonts/docs/developer_api'>
* https://developers.google.com/fonts/docs/developer_api</a>
* <tr><th>Discovery Name<td>webfonts
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Google Fonts Developer API can be found at
* <a href='https://developers.google.com/fonts/docs/developer_api'>https://developers.google.com/fonts/docs/developer_api</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Webfonts.v1
{
/// <summary>The Webfonts Service.</summary>
public class WebfontsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public WebfontsService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public WebfontsService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
webfonts = new WebfontsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "webfonts"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/webfonts/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "webfonts/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch/webfonts/v1"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch/webfonts/v1"; }
}
#endif
private readonly WebfontsResource webfonts;
/// <summary>Gets the Webfonts resource.</summary>
public virtual WebfontsResource Webfonts
{
get { return webfonts; }
}
}
///<summary>A base abstract class for Webfonts requests.</summary>
public abstract class WebfontsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new WebfontsBaseServiceRequest instance.</summary>
protected WebfontsBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40
/// characters.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Deprecated. Please use quotaUser instead.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Webfonts parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "webfonts" collection of methods.</summary>
public class WebfontsResource
{
private const string Resource = "webfonts";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public WebfontsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API</summary>
public virtual ListRequest List()
{
return new ListRequest(service);
}
/// <summary>Retrieves the list of fonts currently served by the Google Fonts Developer API</summary>
public class ListRequest : WebfontsBaseServiceRequest<Google.Apis.Webfonts.v1.Data.WebfontList>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service)
: base(service)
{
InitParameters();
}
/// <summary>Enables sorting of the list</summary>
[Google.Apis.Util.RequestParameterAttribute("sort", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<SortEnum> Sort { get; set; }
/// <summary>Enables sorting of the list</summary>
public enum SortEnum
{
/// <summary>Sort alphabetically</summary>
[Google.Apis.Util.StringValueAttribute("alpha")]
Alpha,
/// <summary>Sort by date added</summary>
[Google.Apis.Util.StringValueAttribute("date")]
Date,
/// <summary>Sort by popularity</summary>
[Google.Apis.Util.StringValueAttribute("popularity")]
Popularity,
/// <summary>Sort by number of styles</summary>
[Google.Apis.Util.StringValueAttribute("style")]
Style,
/// <summary>Sort by trending</summary>
[Google.Apis.Util.StringValueAttribute("trending")]
Trending,
}
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "webfonts"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"sort", new Google.Apis.Discovery.Parameter
{
Name = "sort",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.Webfonts.v1.Data
{
public class Webfont : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The category of the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("category")]
public virtual string Category { get; set; }
/// <summary>The name of the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("family")]
public virtual string Family { get; set; }
/// <summary>The font files (with all supported scripts) for each one of the available variants, as a key :
/// value map.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("files")]
public virtual System.Collections.Generic.IDictionary<string,string> Files { get; set; }
/// <summary>This kind represents a webfont object in the webfonts service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The date (format "yyyy-MM-dd") the font was modified for the last time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("lastModified")]
public virtual string LastModified { get; set; }
/// <summary>The scripts supported by the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("subsets")]
public virtual System.Collections.Generic.IList<string> Subsets { get; set; }
/// <summary>The available variants for the font.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("variants")]
public virtual System.Collections.Generic.IList<string> Variants { get; set; }
/// <summary>The font version.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("version")]
public virtual string Version { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class WebfontList : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The list of fonts currently served by the Google Fonts API.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Webfont> Items { get; set; }
/// <summary>This kind represents a list of webfont objects in the webfonts service.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
// ***********************************************************************
// Copyright (c) 2007-2014 Charlie Poole, Rob Prouse
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System.Text;
namespace NUnit.Framework.Interfaces
{
/// <summary>
/// The ResultState class represents the outcome of running a test.
/// It contains two pieces of information. The Status of the test
/// is an enum indicating whether the test passed, failed, was
/// skipped or was inconclusive. The Label provides a more
/// detailed breakdown for use by client runners.
/// </summary>
public class ResultState
{
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
public ResultState(TestStatus status) : this (status, string.Empty, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
public ResultState(TestStatus status, string label) : this (status, label, FailureSite.Test)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, FailureSite site) : this(status, string.Empty, site)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ResultState"/> class.
/// </summary>
/// <param name="status">The TestStatus.</param>
/// <param name="label">The label.</param>
/// <param name="site">The stage at which the result was produced</param>
public ResultState(TestStatus status, string label, FailureSite site)
{
Status = status;
Label = label == null ? string.Empty : label;
Site = site;
}
#endregion
#region Predefined ResultStates
/// <summary>
/// The result is inconclusive
/// </summary>
public readonly static ResultState Inconclusive = new ResultState(TestStatus.Inconclusive);
/// <summary>
/// The test has been skipped.
/// </summary>
public readonly static ResultState Skipped = new ResultState(TestStatus.Skipped);
/// <summary>
/// The test has been ignored.
/// </summary>
public readonly static ResultState Ignored = new ResultState(TestStatus.Skipped, "Ignored");
/// <summary>
/// The test was skipped because it is explicit
/// </summary>
public readonly static ResultState Explicit = new ResultState(TestStatus.Skipped, "Explicit");
/// <summary>
/// The test succeeded
/// </summary>
public readonly static ResultState Success = new ResultState(TestStatus.Passed);
/// <summary>
/// The test issued a warning
/// </summary>
public readonly static ResultState Warning = new ResultState(TestStatus.Warning);
/// <summary>
/// The test failed
/// </summary>
public readonly static ResultState Failure = new ResultState(TestStatus.Failed);
/// <summary>
/// The test encountered an unexpected exception
/// </summary>
public readonly static ResultState Error = new ResultState(TestStatus.Failed, "Error");
/// <summary>
/// The test was cancelled by the user
/// </summary>
public readonly static ResultState Cancelled = new ResultState(TestStatus.Failed, "Cancelled");
/// <summary>
/// The test was not runnable.
/// </summary>
public readonly static ResultState NotRunnable = new ResultState(TestStatus.Failed, "Invalid");
/// <summary>
/// A suite failed because one or more child tests failed or had errors
/// </summary>
public readonly static ResultState ChildFailure = ResultState.Failure.WithSite(FailureSite.Child);
/// <summary>
/// A suite failed in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpFailure = ResultState.Failure.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeSetUp
/// </summary>
public readonly static ResultState SetUpError = ResultState.Error.WithSite(FailureSite.SetUp);
/// <summary>
/// A suite had an unexpected exception in its OneTimeDown
/// </summary>
public readonly static ResultState TearDownError = ResultState.Error.WithSite(FailureSite.TearDown);
#endregion
#region Properties
/// <summary>
/// Gets the TestStatus for the test.
/// </summary>
/// <value>The status.</value>
public TestStatus Status { get; private set; }
/// <summary>
/// Gets the label under which this test result is
/// categorized, if any.
/// </summary>
public string Label { get; private set; }
/// <summary>
/// Gets the stage of test execution in which
/// the failure or other result took place.
/// </summary>
public FailureSite Site { get; private set; }
/// <summary>
/// Get a new ResultState, which is the same as the current
/// one but with the FailureSite set to the specified value.
/// </summary>
/// <param name="site">The FailureSite to use</param>
/// <returns>A new ResultState</returns>
public ResultState WithSite(FailureSite site)
{
return new ResultState(this.Status, this.Label, site);
}
/// <summary>
/// Test whether this ResultState has the same Status and Label
/// as another one. In other words, the whether two are equal
/// ignoring the Site.
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Matches(ResultState other)
{
return Status == other.Status && Label == other.Label;
}
#endregion
#region Equals Override
/// <summary>
/// Determines whether the specified <see cref="System.Object" />, is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
var other = obj as ResultState;
if (other == null) return false;
return Status.Equals(other.Status) && Label.Equals(other.Label) && Site.Equals(other.Site);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return (int)Status << 8 + (int)Site ^ Label.GetHashCode(); ;
}
#endregion
#region ToString Override
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var sb = new StringBuilder(Status.ToString());
if (Label != null && Label.Length > 0)
sb.AppendFormat(":{0}", Label);
if (Site != FailureSite.Test)
sb.AppendFormat("({0})", Site.ToString());
return sb.ToString();
}
#endregion
}
/// <summary>
/// The FailureSite enum indicates the stage of a test
/// in which an error or failure occurred.
/// </summary>
public enum FailureSite
{
/// <summary>
/// Failure in the test itself
/// </summary>
Test,
/// <summary>
/// Failure in the SetUp method
/// </summary>
SetUp,
/// <summary>
/// Failure in the TearDown method
/// </summary>
TearDown,
/// <summary>
/// Failure of a parent test
/// </summary>
Parent,
/// <summary>
/// Failure of a child test
/// </summary>
Child
}
}
| |
// 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.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.IIS.FunctionalTests.Utilities;
using Microsoft.AspNetCore.Testing;
using Xunit;
namespace Microsoft.AspNetCore.Server.IIS.FunctionalTests
{
[Collection(PublishedSitesCollection.Name)]
public class ShadowCopyTests : IISFunctionalTestBase
{
public ShadowCopyTests(PublishedSitesFixture fixture) : base(fixture)
{
}
[ConditionalFact]
public async Task ShadowCopyDoesNotLockFiles()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
var directoryInfo = new DirectoryInfo(deploymentResult.ContentRoot);
// Verify that we can delete all files in the content root (nothing locked)
foreach (var fileInfo in directoryInfo.GetFiles())
{
fileInfo.Delete();
}
foreach (var dirInfo in directoryInfo.GetDirectories())
{
dirInfo.Delete(recursive: true);
}
}
[ConditionalFact]
public async Task ShadowCopyRelativeInSameDirectoryWorks()
{
var directoryName = Path.GetRandomFileName();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directoryName;
var deploymentResult = await DeployAsync(deploymentParameters);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
var directoryInfo = new DirectoryInfo(deploymentResult.ContentRoot);
// Verify that we can delete all files in the content root (nothing locked)
foreach (var fileInfo in directoryInfo.GetFiles())
{
fileInfo.Delete();
}
var tempDirectoryPath = Path.Combine(deploymentResult.ContentRoot, directoryName);
foreach (var dirInfo in directoryInfo.GetDirectories())
{
if (!tempDirectoryPath.Equals(dirInfo.FullName))
{
dirInfo.Delete(recursive: true);
}
}
}
[ConditionalFact]
public async Task ShadowCopyRelativeOutsideDirectoryWorks()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = $"..\\{directory.DirectoryInfo.Name}";
deploymentParameters.ApplicationPath = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
// Check if directory can be deleted.
// Can't delete the folder but can delete all content in it.
Assert.True(response.IsSuccessStatusCode);
var directoryInfo = new DirectoryInfo(deploymentResult.ContentRoot);
// Verify that we can delete all files in the content root (nothing locked)
foreach (var fileInfo in directoryInfo.GetFiles())
{
fileInfo.Delete();
}
foreach (var dirInfo in directoryInfo.GetDirectories())
{
dirInfo.Delete(recursive: true);
}
StopServer();
deploymentResult.AssertWorkerProcessStop();
}
[ConditionalFact]
public async Task ShadowCopySingleFileChangedWorks()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
DirectoryCopy(deploymentResult.ContentRoot, directory.DirectoryPath, copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
// Rewrite file
var dirInfo = new DirectoryInfo(deploymentResult.ContentRoot);
string dllPath = "";
foreach (var file in dirInfo.EnumerateFiles())
{
if (file.Extension == ".dll")
{
dllPath = file.FullName;
break;
}
}
var fileContents = File.ReadAllBytes(dllPath);
File.WriteAllBytes(dllPath, fileContents);
await deploymentResult.AssertRecycledAsync();
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
}
[ConditionalFact]
public async Task ShadowCopyE2EWorksWithFolderPresent()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "0"), copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
using var secondTempDir = TempDirectory.Create();
// copy back and forth to cause file change notifications.
DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true);
await deploymentResult.AssertRecycledAsync();
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
}
[ConditionalFact]
public async Task ShadowCopyE2EWorksWithOldFoldersPresent()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
// Start with 1 to exercise the incremental logic
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "1"), copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
using var secondTempDir = TempDirectory.Create();
// copy back and forth to cause file change notifications.
DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true);
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "0")), "Expected 0 shadow copy directory to be skipped");
// Depending on timing, this could result in a shutdown failure, but sometimes it succeeds, handle both situations
if (!response.IsSuccessStatusCode)
{
Assert.True(response.ReasonPhrase == "Application Shutting Down" || response.ReasonPhrase == "Server has been shutdown");
}
// This shutdown should trigger a copy to the next highest directory, which will be 2
await deploymentResult.AssertRecycledAsync();
Assert.True(Directory.Exists(Path.Combine(directory.DirectoryPath, "2")), "Expected 2 shadow copy directory");
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
}
[ConditionalFact]
public async Task ShadowCopyCleansUpOlderFolders()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = directory.DirectoryPath;
var deploymentResult = await DeployAsync(deploymentParameters);
// Start with a bunch of junk
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "1"), copySubDirs: true);
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "3"), copySubDirs: true);
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "10"), copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
using var secondTempDir = TempDirectory.Create();
// copy back and forth to cause file change notifications.
DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true);
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "0")), "Expected 0 shadow copy directory to be skipped");
// Depending on timing, this could result in a shutdown failure, but sometimes it succeeds, handle both situations
if (!response.IsSuccessStatusCode)
{
Assert.True(response.ReasonPhrase == "Application Shutting Down" || response.ReasonPhrase == "Server has been shutdown");
}
// This shutdown should trigger a copy to the next highest directory, which will be 11
await deploymentResult.AssertRecycledAsync();
Assert.True(Directory.Exists(Path.Combine(directory.DirectoryPath, "11")), "Expected 11 shadow copy directory");
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
// Verify old directories were cleaned up
Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "1")), "Expected 1 shadow copy directory to be deleted");
Assert.False(Directory.Exists(Path.Combine(directory.DirectoryPath, "3")), "Expected 3 shadow copy directory to be deleted");
}
[ConditionalFact]
public async Task ShadowCopyIgnoresItsOwnDirectoryWithRelativePathSegmentWhenCopying()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = "./ShadowCopy/../ShadowCopy/";
var deploymentResult = await DeployAsync(deploymentParameters);
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "0"), copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
using var secondTempDir = TempDirectory.Create();
// copy back and forth to cause file change notifications.
DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true, ignoreDirectory: "ShadowCopy");
await deploymentResult.AssertRecycledAsync();
Assert.True(Directory.Exists(Path.Combine(deploymentResult.ContentRoot, "ShadowCopy")));
// Make sure folder isn't being recursively copied
Assert.False(Directory.Exists(Path.Combine(deploymentResult.ContentRoot, "ShadowCopy", "0", "ShadowCopy")));
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
}
[ConditionalFact]
public async Task ShadowCopyIgnoresItsOwnDirectoryWhenCopying()
{
using var directory = TempDirectory.Create();
var deploymentParameters = Fixture.GetBaseDeploymentParameters();
deploymentParameters.HandlerSettings["experimentalEnableShadowCopy"] = "true";
deploymentParameters.HandlerSettings["shadowCopyDirectory"] = "./ShadowCopy";
var deploymentResult = await DeployAsync(deploymentParameters);
DirectoryCopy(deploymentResult.ContentRoot, Path.Combine(directory.DirectoryPath, "0"), copySubDirs: true);
var response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
using var secondTempDir = TempDirectory.Create();
// copy back and forth to cause file change notifications.
DirectoryCopy(deploymentResult.ContentRoot, secondTempDir.DirectoryPath, copySubDirs: true);
DirectoryCopy(secondTempDir.DirectoryPath, deploymentResult.ContentRoot, copySubDirs: true, ignoreDirectory: "ShadowCopy");
await deploymentResult.AssertRecycledAsync();
Assert.True(Directory.Exists(Path.Combine(deploymentResult.ContentRoot, "ShadowCopy")));
// Make sure folder isn't being recursively copied
Assert.False(Directory.Exists(Path.Combine(deploymentResult.ContentRoot, "ShadowCopy", "0", "ShadowCopy")));
response = await deploymentResult.HttpClient.GetAsync("Wow!");
Assert.True(response.IsSuccessStatusCode);
}
public class TempDirectory : IDisposable
{
public static TempDirectory Create()
{
var directoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var directoryInfo = Directory.CreateDirectory(directoryPath);
return new TempDirectory(directoryInfo);
}
public TempDirectory(DirectoryInfo directoryInfo)
{
DirectoryInfo = directoryInfo;
DirectoryPath = directoryInfo.FullName;
}
public string DirectoryPath { get; }
public DirectoryInfo DirectoryInfo { get; }
public void Dispose()
{
DeleteDirectory(DirectoryPath);
}
private static void DeleteDirectory(string directoryPath)
{
foreach (var subDirectoryPath in Directory.EnumerateDirectories(directoryPath))
{
DeleteDirectory(subDirectoryPath);
}
try
{
foreach (var filePath in Directory.EnumerateFiles(directoryPath))
{
var fileInfo = new FileInfo(filePath)
{
Attributes = FileAttributes.Normal
};
fileInfo.Delete();
}
Directory.Delete(directoryPath);
}
catch (Exception e)
{
Console.WriteLine($@"Failed to delete directory {directoryPath}: {e.Message}");
}
}
}
// copied from https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, string ignoreDirectory = "")
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
Directory.CreateDirectory(destDirName);
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string tempPath = Path.Combine(destDirName, file.Name);
file.CopyTo(tempPath, true);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
if (string.Equals(subdir.Name, ignoreDirectory))
{
continue;
}
string tempPath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, tempPath, copySubDirs);
}
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
using System;
using System.Runtime.InteropServices;
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\DirectionalLightComponent.h:18
namespace UnrealEngine
{
[ManageType("ManageDirectionalLightComponent")]
public partial class ManageDirectionalLightComponent : UDirectionalLightComponent, IManageWrapper
{
public ManageDirectionalLightComponent(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_UpdateLightGUIDs(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_DetachFromParent(IntPtr self, bool bMaintainWorldPosition, bool bCallModify);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnAttachmentChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnHiddenInGameChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnVisibilityChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PropagateLightingScenarioChange(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_UpdateBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_UpdatePhysicsVolume(IntPtr self, bool bTriggerNotifiers);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_Activate(IntPtr self, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_CreateRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_Deactivate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_DestroyComponent(IntPtr self, bool bPromoteChildren);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_DestroyRenderState_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_InitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_InvalidateLightingCacheDetailed(IntPtr self, bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnActorEnableCollisionChanged(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnComponentCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnComponentDestroyed(IntPtr self, bool bDestroyingHierarchy);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnCreatePhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnDestroyPhysicsState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnRegister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnRep_IsActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnUnregister(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_RegisterComponentTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SendRenderDynamicData_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SendRenderTransform_Concurrent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SetActive(IntPtr self, bool bNewActive, bool bReset);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SetAutoActivate(IntPtr self, bool bNewAutoActivate);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SetComponentTickEnabled(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_SetComponentTickEnabledAsync(IntPtr self, bool bEnabled);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_ToggleActive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_UninitializeComponent(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__UDirectionalLightComponent_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Update/reset light GUIDs.
/// </summary>
public override void UpdateLightGUIDs()
=> E__Supper__UDirectionalLightComponent_UpdateLightGUIDs(this);
/// <summary>
/// DEPRECATED - Use DetachFromComponent() instead
/// </summary>
public override void DetachFromParentDeprecated(bool bMaintainWorldPosition, bool bCallModify)
=> E__Supper__UDirectionalLightComponent_DetachFromParent(this, bMaintainWorldPosition, bCallModify);
/// <summary>
/// Called when AttachParent changes, to allow the scene to update its attachment state.
/// </summary>
public override void OnAttachmentChanged()
=> E__Supper__UDirectionalLightComponent_OnAttachmentChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the hidden in game value of the component.
/// </summary>
protected override void OnHiddenInGameChanged()
=> E__Supper__UDirectionalLightComponent_OnHiddenInGameChanged(this);
/// <summary>
/// Overridable internal function to respond to changes in the visibility of the component.
/// </summary>
protected override void OnVisibilityChanged()
=> E__Supper__UDirectionalLightComponent_OnVisibilityChanged(this);
/// <summary>
/// Updates any visuals after the lighting has changed
/// </summary>
public override void PropagateLightingScenarioChange()
=> E__Supper__UDirectionalLightComponent_PropagateLightingScenarioChange(this);
/// <summary>
/// Update the Bounds of the component.
/// </summary>
public override void UpdateBounds()
=> E__Supper__UDirectionalLightComponent_UpdateBounds(this);
/// <summary>
/// Updates the PhysicsVolume of this SceneComponent, if bShouldUpdatePhysicsVolume is true.
/// </summary>
/// <param name="bTriggerNotifiers">if true, send zone/volume change events</param>
public override void UpdatePhysicsVolume(bool bTriggerNotifiers)
=> E__Supper__UDirectionalLightComponent_UpdatePhysicsVolume(this, bTriggerNotifiers);
/// <summary>
/// Activates the SceneComponent, should be overridden by native child classes.
/// </summary>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void Activate(bool bReset)
=> E__Supper__UDirectionalLightComponent_Activate(this, bReset);
/// <summary>
/// BeginsPlay for the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components (that want initialization) in the level will be Initialized on load before any </para>
/// Actor/Component gets BeginPlay.
/// <para>Requires component to be registered and initialized. </para>
/// </summary>
public override void BeginPlay()
=> E__Supper__UDirectionalLightComponent_BeginPlay(this);
/// <summary>
/// Used to create any rendering thread information for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void CreateRenderState_Concurrent()
=> E__Supper__UDirectionalLightComponent_CreateRenderState_Concurrent(this);
/// <summary>
/// Deactivates the SceneComponent.
/// </summary>
public override void Deactivate()
=> E__Supper__UDirectionalLightComponent_Deactivate(this);
/// <summary>
/// Unregister the component, remove it from its outer Actor's Components array and mark for pending kill.
/// </summary>
public override void DestroyComponent(bool bPromoteChildren)
=> E__Supper__UDirectionalLightComponent_DestroyComponent(this, bPromoteChildren);
/// <summary>
/// Used to shut down any rendering thread structure for this component
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void DestroyRenderState_Concurrent()
=> E__Supper__UDirectionalLightComponent_DestroyRenderState_Concurrent(this);
/// <summary>
/// Initializes the component. Occurs at level startup or actor spawn. This is before BeginPlay (Actor or Component).
/// <para>All Components in the level will be Initialized on load before any Actor/Component gets BeginPlay </para>
/// Requires component to be registered, and bWantsInitializeComponent to be true.
/// </summary>
public override void InitializeComponent()
=> E__Supper__UDirectionalLightComponent_InitializeComponent(this);
/// <summary>
/// Called when this actor component has moved, allowing it to discard statically cached lighting information.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bInvalidateBuildEnqueuedLighting, bool bTranslationOnly)
=> E__Supper__UDirectionalLightComponent_InvalidateLightingCacheDetailed(this, bInvalidateBuildEnqueuedLighting, bTranslationOnly);
/// <summary>
/// Called on each component when the Actor's bEnableCollisionChanged flag changes
/// </summary>
public override void OnActorEnableCollisionChanged()
=> E__Supper__UDirectionalLightComponent_OnActorEnableCollisionChanged(this);
/// <summary>
/// Called when a component is created (not loaded). This can happen in the editor or during gameplay
/// </summary>
public override void OnComponentCreated()
=> E__Supper__UDirectionalLightComponent_OnComponentCreated(this);
/// <summary>
/// Called when a component is destroyed
/// </summary>
/// <param name="bDestroyingHierarchy">True if the entire component hierarchy is being torn down, allows avoiding expensive operations</param>
public override void OnComponentDestroyed(bool bDestroyingHierarchy)
=> E__Supper__UDirectionalLightComponent_OnComponentDestroyed(this, bDestroyingHierarchy);
/// <summary>
/// Used to create any physics engine information for this component
/// </summary>
protected override void OnCreatePhysicsState()
=> E__Supper__UDirectionalLightComponent_OnCreatePhysicsState(this);
/// <summary>
/// Used to shut down and physics engine structure for this component
/// </summary>
protected override void OnDestroyPhysicsState()
=> E__Supper__UDirectionalLightComponent_OnDestroyPhysicsState(this);
/// <summary>
/// Called when a component is registered, after Scene is set, but before CreateRenderState_Concurrent or OnCreatePhysicsState are called.
/// </summary>
protected override void OnRegister()
=> E__Supper__UDirectionalLightComponent_OnRegister(this);
public override void OnRep_IsActive()
=> E__Supper__UDirectionalLightComponent_OnRep_IsActive(this);
/// <summary>
/// Called when a component is unregistered. Called after DestroyRenderState_Concurrent and OnDestroyPhysicsState are called.
/// </summary>
protected override void OnUnregister()
=> E__Supper__UDirectionalLightComponent_OnUnregister(this);
/// <summary>
/// Virtual call chain to register all tick functions
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterComponentTickFunctions(bool bRegister)
=> E__Supper__UDirectionalLightComponent_RegisterComponentTickFunctions(this, bRegister);
/// <summary>
/// Called to send dynamic data for this component to the rendering thread
/// </summary>
protected override void SendRenderDynamicData_Concurrent()
=> E__Supper__UDirectionalLightComponent_SendRenderDynamicData_Concurrent(this);
/// <summary>
/// Called to send a transform update for this component to the rendering thread
/// <para>@warning This is called concurrently on multiple threads (but never the same component concurrently) </para>
/// </summary>
protected override void SendRenderTransform_Concurrent()
=> E__Supper__UDirectionalLightComponent_SendRenderTransform_Concurrent(this);
/// <summary>
/// Sets whether the component is active or not
/// </summary>
/// <param name="bNewActive">The new active state of the component</param>
/// <param name="bReset">Whether the activation should happen even if ShouldActivate returns false.</param>
public override void SetActive(bool bNewActive, bool bReset)
=> E__Supper__UDirectionalLightComponent_SetActive(this, bNewActive, bReset);
/// <summary>
/// Sets whether the component should be auto activate or not. Only safe during construction scripts.
/// </summary>
/// <param name="bNewAutoActivate">The new auto activate state of the component</param>
public override void SetAutoActivate(bool bNewAutoActivate)
=> E__Supper__UDirectionalLightComponent_SetAutoActivate(this, bNewAutoActivate);
/// <summary>
/// Set this component's tick functions to be enabled or disabled. Only has an effect if the function is registered
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabled(bool bEnabled)
=> E__Supper__UDirectionalLightComponent_SetComponentTickEnabled(this, bEnabled);
/// <summary>
/// Spawns a task on GameThread that will call SetComponentTickEnabled
/// </summary>
/// <param name="bEnabled">Whether it should be enabled or not</param>
public override void SetComponentTickEnabledAsync(bool bEnabled)
=> E__Supper__UDirectionalLightComponent_SetComponentTickEnabledAsync(this, bEnabled);
/// <summary>
/// Toggles the active state of the component
/// </summary>
public override void ToggleActive()
=> E__Supper__UDirectionalLightComponent_ToggleActive(this);
/// <summary>
/// Handle this component being Uninitialized.
/// <para>Called from AActor::EndPlay only if bHasBeenInitialized is true </para>
/// </summary>
public override void UninitializeComponent()
=> E__Supper__UDirectionalLightComponent_UninitializeComponent(this);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__UDirectionalLightComponent_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__UDirectionalLightComponent_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__UDirectionalLightComponent_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__UDirectionalLightComponent_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__UDirectionalLightComponent_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__UDirectionalLightComponent_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__UDirectionalLightComponent_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__UDirectionalLightComponent_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__UDirectionalLightComponent_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__UDirectionalLightComponent_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__UDirectionalLightComponent_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__UDirectionalLightComponent_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__UDirectionalLightComponent_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__UDirectionalLightComponent_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__UDirectionalLightComponent_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageDirectionalLightComponent self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageDirectionalLightComponent(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageDirectionalLightComponent>(PtrDesc);
}
}
}
| |
// 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.
// The Regex class represents a single compiled instance of a regular
// expression.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.Serialization;
using System.Threading;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents an immutable, compiled regular expression. Also
/// contains static methods that allow use of regular expressions without instantiating
/// a Regex explicitly.
/// </summary>
public class Regex : ISerializable
{
protected internal string pattern; // The string pattern provided
protected internal RegexOptions roptions; // the top-level options from the options string
// *********** Match timeout fields { ***********
// We need this because time is queried using Environment.TickCount for performance reasons
// (Environment.TickCount returns milliseconds as an int and cycles):
private static readonly TimeSpan MaximumMatchTimeout = TimeSpan.FromMilliseconds(int.MaxValue - 1);
// InfiniteMatchTimeout specifies that match timeout is switched OFF. It allows for faster code paths
// compared to simply having a very large timeout.
// We do not want to ask users to use System.Threading.Timeout.InfiniteTimeSpan as a parameter because:
// (1) We do not want to imply any relation between having using a RegEx timeout and using multi-threading.
// (2) We do not want to require users to take ref to a contract assembly for threading just to use RegEx.
// There may in theory be a SKU that has RegEx, but no multithreading.
// We create a public Regex.InfiniteMatchTimeout constant, which for consistency uses the save underlying
// value as Timeout.InfiniteTimeSpan creating an implementation detail dependency only.
public static readonly TimeSpan InfiniteMatchTimeout = Timeout.InfiniteTimeSpan;
protected internal TimeSpan internalMatchTimeout; // timeout for the execution of this regex
// DefaultMatchTimeout specifies the match timeout to use if no other timeout was specified
// by one means or another. Typically, it is set to InfiniteMatchTimeout.
internal static readonly TimeSpan DefaultMatchTimeout = InfiniteMatchTimeout;
// *********** } match timeout fields ***********
protected internal RegexRunnerFactory factory;
protected internal Hashtable caps; // if captures are sparse, this is the hashtable capnum->index
protected internal Hashtable capnames; // if named captures are used, this maps names->index
protected internal string[] capslist; // if captures are sparse or named captures are used, this is the sorted list of names
protected internal int capsize; // the size of the capture array
[CLSCompliant(false)]
protected IDictionary Caps
{
get
{
return caps;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
caps = value as Hashtable;
if (caps == null)
{
caps = new Hashtable(value);
}
}
}
[CLSCompliant(false)]
protected IDictionary CapNames
{
get
{
return capnames;
}
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
capnames = value as Hashtable;
if (capnames == null)
{
capnames = new Hashtable(value);
}
}
}
internal ExclusiveReference _runnerref; // cached runner
internal SharedReference _replref; // cached parsed replacement pattern
internal RegexCode _code; // if interpreted, this is the code for RegexInterpreter
internal bool _refsInitialized = false;
internal static LinkedList<CachedCodeEntry> s_livecode = new LinkedList<CachedCodeEntry>();// the cache of code and factories that are currently loaded
internal static int s_cacheSize = 15;
internal const int MaxOptionShift = 10;
protected Regex()
{
internalMatchTimeout = DefaultMatchTimeout;
}
/// <summary>
/// Creates and compiles a regular expression object for the specified regular
/// expression.
/// </summary>
public Regex(string pattern)
: this(pattern, RegexOptions.None, DefaultMatchTimeout, false)
{
}
/// <summary>
/// Creates and compiles a regular expression object for the
/// specified regular expression with options that modify the pattern.
/// </summary>
public Regex(string pattern, RegexOptions options)
: this(pattern, options, DefaultMatchTimeout, false)
{
}
public Regex(string pattern, RegexOptions options, TimeSpan matchTimeout)
: this(pattern, options, matchTimeout, false)
{
}
protected Regex(SerializationInfo info, StreamingContext context)
: this(info.GetString("pattern"), (RegexOptions)info.GetInt32("options"))
{
try
{
long timeoutTicks = info.GetInt64("matchTimeout");
TimeSpan timeout = new TimeSpan(timeoutTicks);
ValidateMatchTimeout(timeout);
internalMatchTimeout = timeout;
}
catch (SerializationException)
{
// If this occurs, then assume that this object was serialized using a version
// before timeout was added. In that case just do not set a timeout
// (keep default value)
}
}
void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
{
si.AddValue("pattern", ToString());
si.AddValue("options", Options);
si.AddValue("matchTimeout", MatchTimeout.Ticks);
}
private Regex(string pattern, RegexOptions options, TimeSpan matchTimeout, bool useCache)
{
RegexTree tree;
CachedCodeEntry cached = null;
string cultureKey = null;
if (pattern == null)
throw new ArgumentNullException(nameof(pattern));
if (options < RegexOptions.None || (((int)options) >> MaxOptionShift) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
if ((options & RegexOptions.ECMAScript) != 0
&& (options & ~(RegexOptions.ECMAScript |
RegexOptions.IgnoreCase |
RegexOptions.Multiline |
RegexOptions.Compiled |
RegexOptions.CultureInvariant
#if DEBUG
| RegexOptions.Debug
#endif
)) != 0)
throw new ArgumentOutOfRangeException(nameof(options));
ValidateMatchTimeout(matchTimeout);
// Try to look up this regex in the cache. We do this regardless of whether useCache is true since there's
// really no reason not to.
if ((options & RegexOptions.CultureInvariant) != 0)
cultureKey = CultureInfo.InvariantCulture.ToString(); // "English (United States)"
else
cultureKey = CultureInfo.CurrentCulture.ToString();
var key = new CachedCodeEntryKey(options, cultureKey, pattern);
cached = LookupCachedAndUpdate(key);
this.pattern = pattern;
roptions = options;
internalMatchTimeout = matchTimeout;
if (cached == null)
{
// Parse the input
tree = RegexParser.Parse(pattern, roptions);
// Extract the relevant information
capnames = tree._capnames;
capslist = tree._capslist;
_code = RegexWriter.Write(tree);
caps = _code._caps;
capsize = _code._capsize;
InitializeReferences();
tree = null;
if (useCache)
cached = CacheCode(key);
}
else
{
caps = cached._caps;
capnames = cached._capnames;
capslist = cached._capslist;
capsize = cached._capsize;
_code = cached._code;
_runnerref = cached._runnerref;
_replref = cached._replref;
_refsInitialized = true;
}
}
// Note: "<" is the XML entity for smaller ("<").
/// <summary>
/// Validates that the specified match timeout value is valid.
/// The valid range is <code>TimeSpan.Zero < matchTimeout <= Regex.MaximumMatchTimeout</code>.
/// </summary>
/// <param name="matchTimeout">The timeout value to validate.</param>
/// <exception cref="ArgumentOutOfRangeException">If the specified timeout is not within a valid range.
/// </exception>
protected internal static void ValidateMatchTimeout(TimeSpan matchTimeout)
{
if (InfiniteMatchTimeout == matchTimeout)
return;
// Change this to make sure timeout is not longer then Environment.Ticks cycle length:
if (TimeSpan.Zero < matchTimeout && matchTimeout <= MaximumMatchTimeout)
return;
throw new ArgumentOutOfRangeException(nameof(matchTimeout));
}
/// <summary>
/// Escapes a minimal set of metacharacters (\, *, +, ?, |, {, [, (, ), ^, $, ., #, and
/// whitespace) by replacing them with their \ codes. This converts a string so that
/// it can be used as a constant within a regular expression safely. (Note that the
/// reason # and whitespace must be escaped is so the string can be used safely
/// within an expression parsed with x mode. If future Regex features add
/// additional metacharacters, developers should depend on Escape to escape those
/// characters as well.)
/// </summary>
public static string Escape(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Escape(str);
}
/// <summary>
/// Unescapes any escaped characters in the input string.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Unescape", Justification = "Already shipped since v1 - can't fix without causing a breaking change")]
public static string Unescape(string str)
{
if (str == null)
throw new ArgumentNullException(nameof(str));
return RegexParser.Unescape(str);
}
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread-safety")]
public static int CacheSize
{
get
{
return s_cacheSize;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
s_cacheSize = value;
if (s_livecode.Count > s_cacheSize)
{
lock (s_livecode)
{
while (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
}
}
/// <summary>
/// Returns the options passed into the constructor
/// </summary>
public RegexOptions Options
{
get { return roptions; }
}
/// <summary>
/// The match timeout used by this Regex instance.
/// </summary>
public TimeSpan MatchTimeout
{
get { return internalMatchTimeout; }
}
/// <summary>
/// Indicates whether the regular expression matches from right to left.
/// </summary>
public bool RightToLeft
{
get
{
return UseOptionR();
}
}
/// <summary>
/// Returns the regular expression pattern passed into the constructor
/// </summary>
public override string ToString()
{
return pattern;
}
/*
* Returns an array of the group names that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the GroupNameCollection for the regular expression. This collection contains the
/// set of strings used to name capturing groups in the expression.
/// </summary>
public string[] GetGroupNames()
{
string[] result;
if (capslist == null)
{
int max = capsize;
result = new string[max];
for (int i = 0; i < max; i++)
{
result[i] = Convert.ToString(i, CultureInfo.InvariantCulture);
}
}
else
{
result = new string[capslist.Length];
Array.Copy(capslist, 0, result, 0, capslist.Length);
}
return result;
}
/*
* Returns an array of the group numbers that are used to capture groups
* in the regular expression. Only needed if the regex is not known until
* runtime, and one wants to extract captured groups. (Probably unusual,
* but supplied for completeness.)
*/
/// <summary>
/// Returns the integer group number corresponding to a group name.
/// </summary>
public int[] GetGroupNumbers()
{
int[] result;
if (caps == null)
{
int max = capsize;
result = new int[max];
for (int i = 0; i < result.Length; i++)
{
result[i] = i;
}
}
else
{
result = new int[caps.Count];
// Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations.
IDictionaryEnumerator de = caps.GetEnumerator();
while (de.MoveNext())
{
result[(int)de.Value] = (int)de.Key;
}
}
return result;
}
/*
* Given a group number, maps it to a group name. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns null if the number is not a recognized group number.
*/
/// <summary>
/// Retrieves a group name that corresponds to a group number.
/// </summary>
public string GroupNameFromNumber(int i)
{
if (capslist == null)
{
if (i >= 0 && i < capsize)
return i.ToString(CultureInfo.InvariantCulture);
return string.Empty;
}
else
{
if (caps != null)
{
if (!caps.TryGetValue(i, out i))
return string.Empty;
}
if (i >= 0 && i < capslist.Length)
return capslist[i];
return string.Empty;
}
}
/*
* Given a group name, maps it to a group number. Note that numbered
* groups automatically get a group name that is the decimal string
* equivalent of its number.
*
* Returns -1 if the name is not a recognized group name.
*/
/// <summary>
/// Returns a group number that corresponds to a group name.
/// </summary>
public int GroupNumberFromName(string name)
{
int result = -1;
if (name == null)
throw new ArgumentNullException(nameof(name));
// look up name if we have a hashtable of names
if (capnames != null)
{
if (!capnames.TryGetValue(name, out result))
return -1;
return result;
}
// convert to an int if it looks like a number
result = 0;
for (int i = 0; i < name.Length; i++)
{
char ch = name[i];
if (ch > '9' || ch < '0')
return -1;
result *= 10;
result += (ch - '0');
}
// return int if it's in range
if (result >= 0 && result < capsize)
return result;
return -1;
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text supplied in the given pattern.
/// </summary>
public static bool IsMatch(string input, string pattern)
{
return IsMatch(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple IsMatch call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter with matching options supplied in the options
/// parameter.
/// </summary>
public static bool IsMatch(string input, string pattern, RegexOptions options)
{
return IsMatch(input, pattern, options, DefaultMatchTimeout);
}
public static bool IsMatch(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).IsMatch(input);
}
/*
* Returns true if the regex finds a match within the specified string
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern,
/// options, and starting position.
/// </summary>
public bool IsMatch(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return IsMatch(input, UseOptionR() ? input.Length : 0);
}
/*
* Returns true if the regex finds a match after the specified position
* (proceeding leftward if the regex is leftward and rightward otherwise)
*/
/// <summary>
/// Searches the input string for one or more matches using the previous pattern and options,
/// with a new starting position.
/// </summary>
public bool IsMatch(string input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return (null == Run(true, -1, input, 0, input.Length, startat));
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter.
/// </summary>
public static Match Match(string input, string pattern)
{
return Match(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Match call
*/
/// <summary>
/// Searches the input string for one or more occurrences of the text
/// supplied in the pattern parameter. Matching is modified with an option
/// string.
/// </summary>
public static Match Match(string input, string pattern, RegexOptions options)
{
return Match(input, pattern, options, DefaultMatchTimeout);
}
public static Match Match(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Match(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string (or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Match(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Matches a regular expression with a string and returns
/// the precise result as a RegexMatch object.
/// </summary>
public Match Match(string input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, 0, input.Length, startat);
}
/*
* Finds the first match, restricting the search to the specified interval of
* the char array.
*/
/// <summary>
/// Matches a regular expression with a string and returns the precise result as a
/// RegexMatch object.
/// </summary>
public Match Match(string input, int beginning, int length)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Run(false, -1, input, beginning, length, UseOptionR() ? beginning + length : beginning);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(string input, string pattern)
{
return Matches(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/*
* Static version of simple Matches call
*/
/// <summary>
/// Returns all the successful matches as if Match were called iteratively numerous times.
/// </summary>
public static MatchCollection Matches(string input, string pattern, RegexOptions options)
{
return Matches(input, pattern, options, DefaultMatchTimeout);
}
public static MatchCollection Matches(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Matches(input);
}
/*
* Finds the first match for the regular expression starting at the beginning
* of the string Enumerator(or at the end of the string if the regex is leftward)
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Matches(input, UseOptionR() ? input.Length : 0);
}
/*
* Finds the first match, starting at the specified position
*/
/// <summary>
/// Returns all the successful matches as if Match was called iteratively numerous times.
/// </summary>
public MatchCollection Matches(string input, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return new MatchCollection(this, input, 0, input.Length, startat);
}
/// <summary>
/// Replaces all occurrences of the pattern with the <paramref name="replacement"/> pattern, starting at
/// the first character in the input string.
/// </summary>
public static string Replace(string input, string pattern, string replacement)
{
return Replace(input, pattern, replacement, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of
/// the <paramref name="pattern "/>with the <paramref name="replacement "/>
/// pattern, starting at the first character in the input string.
/// </summary>
public static string Replace(string input, string pattern, string replacement, RegexOptions options)
{
return Replace(input, pattern, replacement, options, DefaultMatchTimeout);
}
public static string Replace(string input, string pattern, string replacement, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, replacement);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public string Replace(string input, string replacement)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the first character in the
/// input string.
/// </summary>
public string Replace(string input, string replacement, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, replacement, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the
/// <paramref name="replacement"/> pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public string Replace(string input, string replacement, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
if (replacement == null)
throw new ArgumentNullException(nameof(replacement));
// a little code to grab a cached parsed replacement object
RegexReplacement repl = (RegexReplacement)_replref.Get();
if (repl == null || !repl.Pattern.Equals(replacement))
{
repl = RegexParser.ParseReplacement(replacement, caps, capsize, capnames, roptions);
_replref.Cache(repl);
}
return repl.Replace(this, input, count, startat);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern.
/// </summary>
public static string Replace(string input, string pattern, MatchEvaluator evaluator)
{
return Replace(input, pattern, evaluator, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Replaces all occurrences of the <paramref name="pattern"/> with the recent
/// replacement pattern, starting at the first character.
/// </summary>
public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options)
{
return Replace(input, pattern, evaluator, options, DefaultMatchTimeout);
}
public static string Replace(string input, string pattern, MatchEvaluator evaluator, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Replace(input, evaluator);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public string Replace(string input, MatchEvaluator evaluator)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, -1, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the first character position.
/// </summary>
public string Replace(string input, MatchEvaluator evaluator, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Replace(input, evaluator, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Replaces all occurrences of the previously defined pattern with the recent
/// replacement pattern, starting at the character position
/// <paramref name="startat"/>.
/// </summary>
public string Replace(string input, MatchEvaluator evaluator, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Replace(evaluator, this, input, count, startat);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined
/// by <paramref name="pattern"/>.
/// </summary>
public static string[] Split(string input, string pattern)
{
return Split(input, pattern, RegexOptions.None, DefaultMatchTimeout);
}
/// <summary>
/// Splits the <paramref name="input "/>string at the position defined by <paramref name="pattern"/>.
/// </summary>
public static string[] Split(string input, string pattern, RegexOptions options)
{
return Split(input, pattern, options, DefaultMatchTimeout);
}
public static string[] Split(string input, string pattern, RegexOptions options, TimeSpan matchTimeout)
{
return new Regex(pattern, options, matchTimeout, true).Split(input);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public string[] Split(string input)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return Split(input, 0, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public string[] Split(string input, int count)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, UseOptionR() ? input.Length : 0);
}
/// <summary>
/// Splits the <paramref name="input"/> string at the position defined by a
/// previous pattern.
/// </summary>
public string[] Split(string input, int count, int startat)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
return RegexReplacement.Split(this, input, count, startat);
}
protected void InitializeReferences()
{
if (_refsInitialized)
throw new NotSupportedException(SR.OnlyAllowedOnce);
_refsInitialized = true;
_runnerref = new ExclusiveReference();
_replref = new SharedReference();
}
/*
* Internal worker called by all the public APIs
*/
internal Match Run(bool quick, int prevlen, string input, int beginning, int length, int startat)
{
Match match;
RegexRunner runner = null;
if (startat < 0 || startat > input.Length)
throw new ArgumentOutOfRangeException(nameof(startat), SR.BeginIndexNotNegative);
if (length < 0 || length > input.Length)
throw new ArgumentOutOfRangeException(nameof(length), SR.LengthNotNegative);
// There may be a cached runner; grab ownership of it if we can.
runner = (RegexRunner)_runnerref.Get();
// Create a RegexRunner instance if we need to
if (runner == null)
{
if (factory != null)
runner = factory.CreateInstance();
else
runner = new RegexInterpreter(_code, UseOptionInvariant() ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture);
}
try
{
// Do the scan starting at the requested position
match = runner.Scan(this, input, beginning, beginning + length, startat, prevlen, quick, internalMatchTimeout);
}
finally
{
// Release or fill the cache slot
_runnerref.Release(runner);
}
#if DEBUG
if (Debug && match != null)
match.Dump();
#endif
return match;
}
/*
* Find code cache based on options+pattern
*/
private static CachedCodeEntry LookupCachedAndUpdate(CachedCodeEntryKey key)
{
lock (s_livecode)
{
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
// If we find an entry in the cache, move it to the head at the same time.
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
}
return null;
}
/*
* Add current code to the cache
*/
private CachedCodeEntry CacheCode(CachedCodeEntryKey key)
{
CachedCodeEntry newcached = null;
lock (s_livecode)
{
// first look for it in the cache and move it to the head
for (LinkedListNode<CachedCodeEntry> current = s_livecode.First; current != null; current = current.Next)
{
if (current.Value._key == key)
{
s_livecode.Remove(current);
s_livecode.AddFirst(current);
return current.Value;
}
}
// it wasn't in the cache, so we'll add a new one. Shortcut out for the case where cacheSize is zero.
if (s_cacheSize != 0)
{
newcached = new CachedCodeEntry(key, capnames, capslist, _code, caps, capsize, _runnerref, _replref);
s_livecode.AddFirst(newcached);
if (s_livecode.Count > s_cacheSize)
s_livecode.RemoveLast();
}
}
return newcached;
}
protected bool UseOptionC()
{
return (roptions & RegexOptions.Compiled) != 0;
}
/*
* True if the L option was set
*/
protected internal bool UseOptionR()
{
return (roptions & RegexOptions.RightToLeft) != 0;
}
internal bool UseOptionInvariant()
{
return (roptions & RegexOptions.CultureInvariant) != 0;
}
#if DEBUG
/*
* True if the regex has debugging enabled
*/
internal bool Debug
{
get
{
return (roptions & RegexOptions.Debug) != 0;
}
}
#endif
}
/*
* Callback class
*/
public delegate string MatchEvaluator(Match match);
/*
* Used as a key for CacheCodeEntry
*/
internal struct CachedCodeEntryKey : IEquatable<CachedCodeEntryKey>
{
private readonly RegexOptions _options;
private readonly string _cultureKey;
private readonly string _pattern;
internal CachedCodeEntryKey(RegexOptions options, string cultureKey, string pattern)
{
_options = options;
_cultureKey = cultureKey;
_pattern = pattern;
}
public override bool Equals(object obj)
{
return obj is CachedCodeEntryKey && Equals((CachedCodeEntryKey)obj);
}
public bool Equals(CachedCodeEntryKey other)
{
return this == other;
}
public static bool operator ==(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return left._options == right._options && left._cultureKey == right._cultureKey && left._pattern == right._pattern;
}
public static bool operator !=(CachedCodeEntryKey left, CachedCodeEntryKey right)
{
return !(left == right);
}
public override int GetHashCode()
{
return ((int)_options) ^ _cultureKey.GetHashCode() ^ _pattern.GetHashCode();
}
}
/*
* Used to cache byte codes
*/
internal sealed class CachedCodeEntry
{
internal CachedCodeEntryKey _key;
internal RegexCode _code;
internal Hashtable _caps;
internal Hashtable _capnames;
internal string[] _capslist;
internal int _capsize;
internal ExclusiveReference _runnerref;
internal SharedReference _replref;
internal CachedCodeEntry(CachedCodeEntryKey key, Hashtable capnames, string[] capslist, RegexCode code, Hashtable caps, int capsize, ExclusiveReference runner, SharedReference repl)
{
_key = key;
_capnames = capnames;
_capslist = capslist;
_code = code;
_caps = caps;
_capsize = capsize;
_runnerref = runner;
_replref = repl;
}
}
/*
* Used to cache one exclusive runner reference
*/
internal sealed class ExclusiveReference
{
private RegexRunner _ref;
private object _obj;
private int _locked;
/*
* Return an object and grab an exclusive lock.
*
* If the exclusive lock can't be obtained, null is returned;
* if the object can't be returned, the lock is released.
*
*/
internal object Get()
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// grab reference
object obj = _ref;
// release the lock and return null if no reference
if (obj == null)
{
_locked = 0;
return null;
}
// remember the reference and keep the lock
_obj = obj;
return obj;
}
return null;
}
/*
* Release an object back to the cache
*
* If the object is the one that's under lock, the lock
* is released.
*
* If there is no cached object, then the lock is obtained
* and the object is placed in the cache.
*
*/
internal void Release(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
// if this reference owns the lock, release it
if (_obj == obj)
{
_obj = null;
_locked = 0;
return;
}
// if no reference owns the lock, try to cache this reference
if (_obj == null)
{
// try to obtain the lock
if (0 == Interlocked.Exchange(ref _locked, 1))
{
// if there's really no reference, cache this reference
if (_ref == null)
_ref = (RegexRunner)obj;
// release the lock
_locked = 0;
return;
}
}
}
}
/*
* Used to cache a weak reference in a threadsafe way
*/
internal sealed class SharedReference
{
private WeakReference _ref = new WeakReference(null);
private int _locked;
/*
* Return an object from a weakref, protected by a lock.
*
* If the exclusive lock can't be obtained, null is returned;
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal object Get()
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
object obj = _ref.Target;
_locked = 0;
return obj;
}
return null;
}
/*
* Suggest an object into a weakref, protected by a lock.
*
* Note that _ref.Target is referenced only under the protection
* of the lock. (Is this necessary?)
*/
internal void Cache(object obj)
{
if (0 == Interlocked.Exchange(ref _locked, 1))
{
_ref.Target = obj;
_locked = 0;
}
}
}
}
| |
/*
* Copyright (c) 2010, www.wojilu.com. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;
using wojilu.Web.Mvc.Utils;
using wojilu.Members.Users.Domain;
using wojilu.Members.Users.Interface;
using wojilu.Members.Users.Service;
using wojilu.Common.Msg.Service;
using wojilu.Common.Msg.Domain;
using wojilu.Common.Msg.Interface;
using wojilu.Web.Controller.Common;
using wojilu.Serialization;
namespace wojilu.Web.Controller.Users {
public class FeedbackController : ControllerBase {
public IFeedbackService feedbackService { get; set; }
public IBlacklistService blacklistService { get; set; }
public FeedbackController() {
feedbackService = new FeedbackService();
blacklistService = new BlacklistService();
}
public override void Layout() {
load( "userMenu", new Users.ProfileController().UserMenu );
set( "user.Name", ctx.owner.obj.Name );
}
[HttpPost]
public void Create() {
checkFeedbackPermission();
if (ctx.HasErrors) {
echoError();
return;
}
Feedback f = validate( 0 );
if (ctx.HasErrors) {
echoError();
return;
}
if (f.IsPrivate == 1) {
sendMsg( f );
String postContent = "<span>" + lang( "feedbackPrivate" ) + "</span>";
echoJsonMsg( postContent, true, "" );
//actionContent( MvcUtil.renderValidatorJson( postContent, true ) );
return;
}
else {
feedbackService.Insert( f );
List<Feedback> flist = new List<Feedback>();
flist.Add( f );
ctx.SetItem( "feedbackList", flist );
String postContent = loadHtml( bindList );
//echoJsonMsg( postContent, true, "formResult" );
Dictionary<String, Object> dic = new Dictionary<string, object>();
dic.Add( "IsValid", true );
dic.Add( "Info", "formResult" );
dic.Add( "Msg", postContent );
echoJson( JsonString.Convert( dic ) );
}
}
public void Reply( int id ) {
checkFeedbackPermission();
if (ctx.HasErrors) {
echo( errors.ErrorsText );
return;
}
Feedback parent = feedbackService.GetById( id );
if (parent.Target.Id != ctx.owner.Id) {
echo( lang( "exCommentTarget" ) );
return;
}
set( "maxCount", Feedback.ContentLength );
target( SaveReply, id );
}
[HttpPost, Login]
public void SaveReply( int id ) {
checkFeedbackPermission();
if (ctx.HasErrors) {
echoError();
return;
}
Feedback parent = feedbackService.GetById( id );
if (parent.Target.Id != ctx.owner.Id) {
echoError( lang( "exCommentTarget" ) );
return;
}
Feedback f = validate( id );
if (ctx.HasErrors) {
echoError();
return;
}
feedbackService.Reply( parent, f );
echoToParent( lang( "opok" ) );
}
private void sendMsg( Feedback f ) {
String title = lang( "feedbackPrivate" ) + ": " + strUtil.CutString( f.Content, 20 );
ctx.viewer.SendMsg( ctx.owner.obj.Name, title, f.Content );
}
public void List() {
if (hasAdminPermission()) redirect( AdminList );
WebUtils.pageTitle( this, lang( "feedback" ) );
set( "ActionLink", t2( Create ) );
String pwTip = string.Format( lang( "pwTip" ), Feedback.ContentLength );
set( "pwTip", pwTip );
DataPage<Feedback> list = feedbackService.GetPageList( ctx.owner.Id );
set( "page", list.PageBar );
ctx.SetItem( "feedbackList", list.Results );
load( "feedbackList", bindList );
}
[Login]
public void AdminList() {
if (!hasAdminPermission()) {
echoRedirect( lang( "exNoPermission" ), List );
return;
}
DataPage<Feedback> list = feedbackService.GetPageList( ctx.owner.Id );
set( "page", list.PageBar );
IBlock block = getBlock( "list" );
foreach (Feedback f in list.Results) {
bindItem( block, f );
block.Set( "f.DeleteLink", t2( new FeedbackController().Delete, f.Id ) );
block.Next();
}
}
[HttpDelete, Login]
public void Delete( int id ) {
if (!hasAdminPermission()) {
echo( lang( "exNoPermission" ) );
return;
}
Feedback f = feedbackService.GetById( id );
if (f.Target.Id != ctx.owner.Id) { echoRedirect( lang( "exDataNotFound" ) ); return; }
feedbackService.Delete( f );
redirect( AdminList );
}
//--------------------------------------------------------------------------------------------
private void checkFeedbackPermission() {
if (ctx.viewer.IsLogin == false) {
errors.Add( lang( "exPlsLogin" ) );
return;
}
if (blacklistService.IsBlack( ctx.owner.Id, ctx.viewer.Id )) {
errors.Add( lang( "exCantFeedback" ) );
return;
}
User owner = ctx.owner.obj as User;
if (ctx.viewer.HasPrivacyPermission( owner, UserPermission.Feedback.ToString() ) == false) {
errors.Add( lang( "exCantFeedback" ) );
return;
}
}
private Boolean hasAdminPermission() {
return ctx.viewer.Id == ctx.owner.Id && ctx.owner.obj is User;
}
private Feedback validate( int parentId ) {
Feedback f = new Feedback();
f.Creator = (User)ctx.viewer.obj;
f.Target = ctx.owner.obj as User;
f.Content = ctx.Post( "Content" );
if (strUtil.HasText( f.Content )) f.Content = strUtil.CutString( f.Content, Feedback.ContentLength );
f.Ip = ctx.Ip;
f.Created = DateTime.Now;
f.IsPrivate = ctx.PostIsCheck( "chkPrivate" );
f.ParentId = parentId;
if (strUtil.IsNullOrEmpty( f.Content )) errors.Add( lang( "exContent" ) );
return f;
}
[NonVisit]
public void bindList() {
List<Feedback> list = ctx.GetItem( "feedbackList" ) as List<Feedback>;
IBlock block = getBlock( "list" );
foreach (Feedback f in list) {
bindItem( block, f );
block.Next();
}
}
private void bindItem( IBlock block, Feedback f ) {
block.Set( "f.UserName", f.Creator.Name );
block.Set( "f.UserFace", f.Creator.PicSmall );
block.Set( "f.UserLink", Link.ToMember( f.Creator ) );
block.Set( "f.ReplyLink", t2( new FeedbackController().Reply, f.Id ) );
block.Set( "f.Content", f.GetContent() );
block.Set( "f.Created", cvt.ToTimeString( f.Created ) );
}
}
}
| |
using UnityEngine;
using System.Collections;
public class MainPlayerController : MonoBehaviour {
public Animator animator;
public Transform[] weapons;
public static int currentWeapon;
float rotationSpeed = 30;
Vector3 inputVec;
public float distance = 10;
bool isMoving;
public static Vector3 position;
ShootArrow shootArrow;
ShootMultiArrow shootMultiArrow;
public static Vector3 lookTarget;
public bool attacking = false;
public Transform cursorResponse;
public static Vector3 mousePosition;
public Vector3 cursorPos;
private CharacterController controller;
private Vector3 velocity = new Vector3(0,0,-200);
private StatsSheet_Player stats;
public static bool completedLevel = false;
private CharacterController cc;
public float knockbackTime;
private Rigidbody rb;
public static bool canBowSpecial;
public static bool canSwordSpecial;
public StatsSheet_Player getStats(){ return stats; }
public uiDisplay ui;
public static bool isDead = false;
public ParticleSystem dust;
public float dashDist = 20f;
public float dashTime = 0.3f;
private float dashTimer = 0f;
private bool dashing = false;
public static bool usingController = false;
public float swordAttackRoF;
public float bowAttackRoF;
public static bool bowSpecialUnlocked;
public static bool swordSpecialunlocked;
public audioPlay soundFX;
public bool concealed;
public SphereCollider swordAoE;
void Start()
{
/// Initializations
soundFX = GetComponent<audioPlay>();
swordAoE = GameObject.Find ("SwordColl").GetComponent<SphereCollider> ();
cameraShake.shake = 0;
isDead = false;
stats = GameObject.Find ("DungeonMaster").GetComponent<DungeonMaster> ().playerStats;
ui = GameObject.FindGameObjectWithTag ("UI").GetComponent<uiDisplay> ();
shootArrow = gameObject.GetComponentInChildren<ShootArrow> ();
shootMultiArrow = gameObject.GetComponentInChildren<ShootMultiArrow> ();
changeWeapon (0);
controller = this.gameObject.GetComponent<CharacterController> ();
ReceiverDamage receiver = GetComponent<ReceiverDamage> ();
if (receiver == null) {
print ("RECEIVER IS NULL");
} else {
receiver.setStats(stats);
}
SenderDamage[] sender = GetComponentsInChildren<SenderDamage> ();
if (sender != null) {
foreach(SenderDamage sd in sender){
Debug.Log (sd.gameObject.name);
sd.setStats(stats);
}
}
ui.UpdateHealth(stats.getCurHealth(), stats.getMaxHealth());
cc = gameObject.GetComponent<CharacterController> ();
rb = gameObject.GetComponent<Rigidbody> ();
concealed = false;
}
// Fires Arrow
public void CallShootArrow()
{
shootArrow.FireArrow ();
}
// Fires Multi Arrrows
public void CallShootMultiArrow()
{
shootMultiArrow.FireArrow ();
}
// Weapon Special Cooldowns
IEnumerator CoolDown(string weapon)
{
StartCoroutine(GameObject.Find("_MainHUDCanvas").GetComponent<uiDisplay>().SpecialCooldown());
if (weapon == "sword") {
canSwordSpecial=false;
yield return new WaitForSeconds(5f);
canSwordSpecial=true;
}
else if (weapon == "bow")
{
canBowSpecial=false;
yield return new WaitForSeconds(5f);
canBowSpecial=true;
}
}
// On Player Collisions
void OnTriggerEnter(Collider other)
{
/// Pick Up potion
if (other.gameObject.tag == "potion")
{
soundFX.MedpackPickup();
Destroy(other.gameObject);
PlayerPrefs.SetInt("potions", PlayerPrefs.GetInt("potions")+1);
}
/// Proceed to next level
if (other.gameObject.tag == "nextLevel")
{
if(other.gameObject.GetComponent<TeleportScript>().waveComplete){
//PlayerPrefs.SetInt("level", PlayerPrefs.GetInt("level")+1);
completedLevel=true;
levelChanger.fadeToLevel=true;
}
}
}
// On Death
public void Death()
{
GameObject dm = GameObject.Find ("DungeonMaster");
if(dm!=null){
/// Play death animation
cameraShake.shake = 3f;
dm.GetComponent<DungeonMaster>().handleOnDeathPlayer();
bringUp.playerAssigned=false;
PlayerPrefs.SetInt("minDunLength",0);
// Fade to end game level
levelChanger.fadeToEndGame=true;
}
}
void Update() // every frame
{
if (!swordAoE)
{
swordAoE = GameObject.Find ("SwordColl").GetComponent<SphereCollider> ();
}
/// CHECK IF BOW SPECIAL AND SWORD SPECIAL IS UNLOCKED
if (bowSpecialUnlocked != true) {
canBowSpecial = false;
}
if (swordSpecialunlocked != true) {
canSwordSpecial = false;
}
/// SWORD SPECIAL AOE RADIUS
if (PlayerPrefs.GetInt ("AoE") == 2) {
swordAoE.radius = 45;
} else if (PlayerPrefs.GetInt ("AoE") == 3) {
swordAoE.radius = 60;
}
else{
swordAoE.radius=30;
}
/// SWORD ROF
if (PlayerPrefs.GetInt ("SwordRoF") == 1) {
swordAttackRoF = 1.25f;
} else if (PlayerPrefs.GetInt ("SwordRoF") == 2) {
swordAttackRoF = 1.5f;
} else if (PlayerPrefs.GetInt ("SwordRoF") == 3) {
swordAttackRoF = 2;
} else {
swordAttackRoF = 1;
}
/// BOW ROF
if (PlayerPrefs.GetInt ("BowRoF") == 1) {
bowAttackRoF = 1.5f;
} else if (PlayerPrefs.GetInt ("BowRoF") == 2) {
bowAttackRoF = 1.75f;
} else if (PlayerPrefs.GetInt ("BowRoF") == 3) {
bowAttackRoF = 2;
} else {
bowAttackRoF = 1.25f;
}
/// PLAYER AGILITY
if (PlayerPrefs.GetInt ("Agility") == 1 && animator.GetBool("Moving") && animator.GetBool("Running") && animator.GetBool("attacking")!=true) {
animator.speed = 1.25f;
} else if (PlayerPrefs.GetInt ("Agility") == 2 && animator.GetBool("Moving") && animator.GetBool("Running")&& animator.GetBool("attacking")!=true) {
animator.speed = 1.5f;
} else if (PlayerPrefs.GetInt ("Agility") == 3 && animator.GetBool("Moving") && animator.GetBool("Running") && animator.GetBool("attacking")!=true) {
animator.speed = 2;
} else if(animator.GetBool("attacking")!=true) {
animator.speed = 1;
}
/// *** DASH ***
if (Input.GetButtonDown ("Dash") && uiDisplay.stamina[0].fillAmount>=1 && !isDead) // If dash pressed and player has enough stamina
{
if(!dashing){
soundFX.Dash();
// Reduce stamina
uiDisplay.stamina[0].fillAmount -=1;
dashing = true;
dust.enableEmission = true;
dust.Play();
}
}
/// Dashing particle and length
if (dashing)
{
dashTimer += Time.deltaTime;
if(dashTimer < dashTime && Time.deltaTime < 1f)
{
Dash(dashDist*Time.deltaTime/dashTime);
}
else if(Time.deltaTime>1f)
{
Dash(dashDist);
dashTimer = 0;
dashing = false;
dust.enableEmission = false;
}
else
{
Dash(dashDist*Time.deltaTime/dashTime);
dashTimer = 0;
dashing = false;
dust.enableEmission = false;
}
}
/// *** USE POTION ***
if (Input.GetButtonDown ("UsePotion") && !isDead)
{
if (PlayerPrefs.GetInt ("potions") > 0 && stats.getCurHealth()!=stats.getMaxHealth()) // If player has a potion to use and health is not full
{
soundFX.MedpackUse();
PlayerPrefs.SetInt("potions", PlayerPrefs.GetInt("potions")-1);
stats.setCurHealth (stats.getCurHealth()+(stats.getMaxHealth()/4));
ui.UpdateHealth(stats.getCurHealth(), stats.getMaxHealth());
}
}
// If player's health falls <=0
if (stats.getCurHealth () <= 0 && isDead==false)
{
isDead=true;
animator.SetTrigger("Death");
uiDisplay.deathUI.SetActive(true);
}
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (uiDisplay.cursor.transform.position);
if (Physics.Raycast (ray, out hit))
{
lookTarget = hit.point;
}
//Get input from controls
float z = Input.GetAxisRaw("Vertical") + Input.GetAxisRaw("JoystickMoveY");
float x = (Input.GetAxisRaw("Horizontal") + Input.GetAxisRaw("JoystickMoveX"));
inputVec = new Vector3(x, 0, z);
//Apply inputs to animator
animator.SetFloat("Input X", x);
animator.SetFloat("Input Z", z);
// If player is inputing movement through controller
if (Input.GetAxisRaw ("JoystickMoveX") != 0 || Input.GetAxisRaw ("JoystickMoveY") != 0)
{
usingController = true;
}
// Otherwise, if player is inputting movement through keyboard
else if(Input.GetAxisRaw("Horizontal") !=0 || Input.GetAxisRaw("Vertical") !=0)
{
usingController=false;
}
if ((x != 0 || z != 0) && !attacking && !isDead && animator.GetBool("attacking")!=true) // If player is moving
{
//set that character is moving
animator.SetBool("Moving", true);
animator.SetBool("Running", true);
isMoving = true;
}
else
{
//character is not moving
animator.SetBool("Moving", false);
animator.SetBool("Running", false);
isMoving = false;
}
/// *** NORMAL ATTACK ***
if (Input.GetButtonDown("Fire1") && !attacking && !isDead && gameManager.showUpgradeMenu!=true && animator.GetBool("attacking")!=true) // if player uses normal attack
{
uiDisplay UI = GameObject.Find ("_MainHUDCanvas").GetComponent<uiDisplay>();
// Face player towards mouse position
arrow.arrowTarget = lookTarget;
mousePosition = lookTarget;
// Spawn particle effect on mouse location at the time of attack
Instantiate(cursorResponse, lookTarget, Quaternion.identity);
cursorPos = cursorResponse.position;
lookTarget.y = this.transform.position.y;
//Play attack animation
if(currentWeapon==0) // if sword is active
{
// Play sword attack animation
animator.SetTrigger("Attack1Trigger");
}
else // otherwise
{
// Face player towards mouse and play Bow attack animation
transform.LookAt(lookTarget);
animator.SetTrigger("BowAttackTrigger");
}
}
/// *** SPECIAL ATTACK ***
if (Input.GetButtonDown ("Fire2") && !attacking && !isDead && gameManager.showUpgradeMenu!=true && animator.GetBool("attacking")!=true) // if player uses special attack
{
/// Play attack animation
if(currentWeapon==0 && canSwordSpecial) // if sword is active and sword special attack is available
{
animator.SetBool("attacking", true);
arrow.arrowTarget = lookTarget;
mousePosition = new Vector3(Input.mousePosition.x, this.transform.position.y, Input.mousePosition.z);
//Attack Cooldown
uiDisplay UI = GameObject.Find ("_MainHUDCanvas").GetComponent<uiDisplay>();
//Face player towards mouse position
Instantiate(cursorResponse, lookTarget, Quaternion.identity);
cursorPos = cursorResponse.position;
lookTarget.y = this.transform.position.y;
transform.LookAt(lookTarget);
// Play sword special animation
animator.SetTrigger("SwordSpecial");
// Start sword special cooldown
StartCoroutine(CoolDown("sword"));
}
else if(currentWeapon==1 && canBowSpecial) // otherwise, if bow is active and bow special attack is available
{
animator.SetBool("attacking", true);
arrow.arrowTarget = lookTarget;
mousePosition = new Vector3(Input.mousePosition.x, this.transform.position.y, Input.mousePosition.z);
//Attack Cooldown
uiDisplay UI = GameObject.Find ("_MainHUDCanvas").GetComponent<uiDisplay>();
//Face player towards mouse position
Instantiate(cursorResponse, lookTarget, Quaternion.identity);
cursorPos = cursorResponse.position;
lookTarget.y = this.transform.position.y;
transform.LookAt(lookTarget);
// Play bow special animation
animator.SetTrigger("BowMultiAttackTrigger");
// Start bow special cooldown
StartCoroutine(CoolDown("bow"));
}
}
/// *** WEAPON SWAP ***
if (Input.GetButtonDown ("WeaponSwap") && !attacking && !isDead && gameManager.showUpgradeMenu!=true)
{
if(currentWeapon==0)
{
changeWeapon(1);
}
else
{
changeWeapon(0);
}
}
// If player not attacking, update movement
if (Input.GetButtonDown ("Fire1") == false)
{
UpdateMovement ();
}
}
/// Get current attack speed depending on RoF upgrades
public void GetAttackSpeed(int weapon)
{
if (weapon == 0)
{
Debug.Log ("SwordAttackRoF: " + swordAttackRoF);
animator.SetBool ("attacking", true);
attacking = true;
animator.speed = swordAttackRoF;
}
else if (weapon == 1)
{
Debug.Log ("BowAttackRoF: " + bowAttackRoF);
animator.SetBool ("attacking", true);
attacking = true;
animator.speed = bowAttackRoF;
}
else
{
animator.SetBool ("attacking", true);
attacking = true;
}
}
public void ResetAnimatorSpeed()
{
animator.SetBool ("attacking", false);
attacking = false;
animator.speed = 1;
}
/// Switch active weapon
public void changeWeapon (int num)
{
currentWeapon = num;
for (int i = 0; i<weapons.Length; i++) {
if(i==num)
{
weapons[i].gameObject.SetActive(true);
}
else
{
weapons[i].gameObject.SetActive(false);
}
}
}
/// Moves the player forward in the direction they are facing
void Dash(float dashAmount)
{
Vector3 forward = new Vector3();
forward = transform.TransformDirection (Vector3.forward);
float curSpeed = 20 * dashAmount;
controller.SimpleMove(forward * curSpeed);
}
/// Face character along input direction
void RotateTowardsMovementDir()
{
if (inputVec != Vector3.zero && attacking==false && !isDead && animator.GetBool("attacking")!=true)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(inputVec), Time.deltaTime * rotationSpeed);
}
}
float UpdateMovement()
{
Vector3 motion = inputVec; //get movement input from controls
//reduce input for diagonal movement
motion *= (Mathf.Abs(inputVec.x) == 1 && Mathf.Abs(inputVec.z) == 1)?.7f:1;
RotateTowardsMovementDir(); //if not strafing, face character along input direction
return inputVec.magnitude; //return a movement value for the animator, not currently used
}
}
| |
//
// This file genenerated by the Buckle tool on 8/23/2014 at 5:05 PM.
//
// Contains strongly typed wrappers for resources in CommandLineParserResources.resx
//
namespace ToolBelt {
using System;
using System.Reflection;
using System.Resources;
using System.Diagnostics;
using System.Globalization;
/// <summary>
/// Strongly typed resource wrappers generated from CommandLineParserResources.resx.
/// </summary>
public class CommandLineParserResources
{
internal static readonly ResourceManager ResourceManager = new ResourceManager(typeof(CommandLineParserResources));
/// <summary>
/// command
/// </summary>
public static ToolBelt.Message Command_Lowercase
{
get
{
return new ToolBelt.Message("Command_Lowercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Command argument already defined
/// </summary>
public static ToolBelt.Message CommandArgumentAlreadyDefined
{
get
{
return new ToolBelt.Message("CommandArgumentAlreadyDefined", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// CommandLineCopyrightAttribute or AssemblyCopyrightAttribute not found.
/// </summary>
public static ToolBelt.Message CopyrightAttributesNotFound
{
get
{
return new ToolBelt.Message("CopyrightAttributesNotFound", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Default argument already defined
/// </summary>
public static ToolBelt.Message DefaultArgumentAlreadyDefined
{
get
{
return new ToolBelt.Message("DefaultArgumentAlreadyDefined", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// CommandLineDescriptionAttribute or AssemblyDescriptionAttribute not found
/// </summary>
public static ToolBelt.Message DescriptionAttributesNotFound
{
get
{
return new ToolBelt.Message("DescriptionAttributesNotFound", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Duplicate command line argument '{0}'
/// </summary>
public static ToolBelt.Message DuplicateCommandLineArgument(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("DuplicateCommandLineArgument", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// file-name
/// </summary>
public static ToolBelt.Message FileName_Lowercase
{
get
{
return new ToolBelt.Message("FileName_Lowercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Invalid Initializer class '{0}' for command line argument '{1}'
/// </summary>
public static ToolBelt.Message InvalidInitializerClassForCommandLineArgument(object param0, object param1)
{
Object[] o = { param0, param1 };
return new ToolBelt.Message("InvalidInitializerClassForCommandLineArgument", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Invalid value '{0}' for command line argument '{1}'.
/// </summary>
public static ToolBelt.Message InvalidValueForCommandLineArgument(object param0, object param1)
{
Object[] o = { param0, param1 };
return new ToolBelt.Message("InvalidValueForCommandLineArgument", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Invalid value {0} for command line argument '{1}'. Valid values are: {2}
/// </summary>
public static ToolBelt.Message InvalidValueForCommandLineArgumentWithValid(object param0, object param1, object param2)
{
Object[] o = { param0, param1, param2 };
return new ToolBelt.Message("InvalidValueForCommandLineArgumentWithValid", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// No way found to initialize type '{0}' for argument '{1}' from a string
/// </summary>
public static ToolBelt.Message NoWayToInitializeTypeFromString(object param0, object param1)
{
Object[] o = { param0, param1 };
return new ToolBelt.Message("NoWayToInitializeTypeFromString", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// number
/// </summary>
public static ToolBelt.Message Number_Lowercase
{
get
{
return new ToolBelt.Message("Number_Lowercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// switches
/// </summary>
public static ToolBelt.Message Switches_Lowercase
{
get
{
return new ToolBelt.Message("Switches_Lowercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Switches:
/// </summary>
public static ToolBelt.Message Switches_Propercase
{
get
{
return new ToolBelt.Message("Switches_Propercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Problem invoking the Add method for argument '{0}'
/// </summary>
public static ToolBelt.Message ProblemInvokingAddMethod(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("ProblemInvokingAddMethod", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Property '{0}' has no Add method with non-object parameter type.
/// </summary>
public static ToolBelt.Message PropertyHasNoAddMethodWithNonObjectParameter(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("PropertyHasNoAddMethodWithNonObjectParameter", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Property '{0}' is not a strongly typed array
/// </summary>
public static ToolBelt.Message PropertyIsNotAStronglyTypedArray(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("PropertyIsNotAStronglyTypedArray", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Property '{0}' should be readable and writeable
/// </summary>
public static ToolBelt.Message PropertyShouldBeReadableAndWriteable(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("PropertyShouldBeReadableAndWriteable", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Resource reader '{0}' does not contain a property '{1}'
/// </summary>
public static ToolBelt.Message ResourceReaderDoesNotContainString(object param0, object param1)
{
Object[] o = { param0, param1 };
return new ToolBelt.Message("ResourceReaderDoesNotContainString", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// (Short format: -{0})
/// </summary>
public static ToolBelt.Message ShortFormat(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("ShortFormat", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// text
/// </summary>
public static ToolBelt.Message Text_LowerCase
{
get
{
return new ToolBelt.Message("Text_LowerCase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Type '{0}' is not derived from type '{1}'
/// </summary>
public static ToolBelt.Message TypeNotDerivedFromType(object param0, object param1)
{
Object[] o = { param0, param1 };
return new ToolBelt.Message("TypeNotDerivedFromType", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Unknown or invalid argument '{0}'
/// </summary>
public static ToolBelt.Message UnknownArgument(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("UnknownArgument", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Unknown command '{0}'
/// </summary>
public static ToolBelt.Message UnknownCommandArgument(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("UnknownCommandArgument", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// Unprocessed argument already defined
/// </summary>
public static ToolBelt.Message UnprocessedArgumentAlreadyDefined
{
get
{
return new ToolBelt.Message("UnprocessedArgumentAlreadyDefined", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Unprocessed argument must be array or collection
/// </summary>
public static ToolBelt.Message UnprocessedArgumentMustBeArrayOrCollection
{
get
{
return new ToolBelt.Message("UnprocessedArgumentMustBeArrayOrCollection", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// A target for unprocessed arguments cannot be specified without a default argument target
/// </summary>
public static ToolBelt.Message UnprocessedRequiresDefaultArguments
{
get
{
return new ToolBelt.Message("UnprocessedRequiresDefaultArguments", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Syntax:
/// </summary>
public static ToolBelt.Message Syntax_Propercase
{
get
{
return new ToolBelt.Message("Syntax_Propercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// value
/// </summary>
public static ToolBelt.Message Value_Lowercase
{
get
{
return new ToolBelt.Message("Value_Lowercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// AssemblyFileVersionAttribute not found.
/// </summary>
public static ToolBelt.Message VersionAttributesNotFound
{
get
{
return new ToolBelt.Message("VersionAttributesNotFound", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Commands:
/// </summary>
public static ToolBelt.Message Commands_Propercase
{
get
{
return new ToolBelt.Message("Commands_Propercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Description:
/// </summary>
public static ToolBelt.Message Description_Propercase
{
get
{
return new ToolBelt.Message("Description_Propercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Examples:
/// </summary>
public static ToolBelt.Message Examples_Propercase
{
get
{
return new ToolBelt.Message("Examples_Propercase", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Response files nested too deeply:
/// </summary>
public static ToolBelt.Message ResponseFilesTooDeep
{
get
{
return new ToolBelt.Message("ResponseFilesTooDeep", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Could not open response file '{0}'
/// </summary>
public static ToolBelt.Message ResponseFileUnopened(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("ResponseFileUnopened", typeof(CommandLineParserResources), ResourceManager, o);
}
/// <summary>
/// CommandLineTitleAttribute or AssemblyTitleAttribute not found
/// </summary>
public static ToolBelt.Message TitleAttributesNotFound
{
get
{
return new ToolBelt.Message("TitleAttributesNotFound", typeof(CommandLineParserResources), ResourceManager, null);
}
}
/// <summary>
/// Property '{0}' is an array which is not supported. Please change it to a mutable ICollection derived type.
/// </summary>
public static ToolBelt.Message ArraysAreNotSupported(object param0)
{
Object[] o = { param0 };
return new ToolBelt.Message("ArraysAreNotSupported", typeof(CommandLineParserResources), ResourceManager, o);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Core;
using DumbBots.NET.Properties;
using Entities;
using Game;
using Graphs;
using IrrlichtNETCP;
using MDXInfo.Util.Script;
using Messaging;
using Scripting;
namespace DumbBots.NET
{
public partial class frmMain : Form
{
private ScriptEditorControl _txtCode;
private CombatEntity _team1Player;
private CombatEntity _team2Player;
private List<string> _referencedAssemblies;
public frmMain()
{
InitializeComponent();
_referencedAssemblies = new List<string>();
AddCodeEditor();
}
private void AddCodeEditor()
{
_txtCode = new ScriptEditorControl();
_txtCode.Dock = DockStyle.Fill;
_txtCode.ConfigurationManager.Language = "cs";
_txtCode.Margins.Margin0.Width = 35;
_txtCode.Parent = pnlCodeArea;
_txtCode.Dock = DockStyle.Fill;
_txtCode.BringToFront();
}
private void frmMain_Load(object sender, EventArgs e)
{
this.Show();
ScriptRunner.ReflectScripts();
SoundManager.PlaySound = Settings.Default.Sound;
UpdateSoundUI();
InitializeDevice(pnlRendering);
if (Settings.Default.ReferencedAssemblies != null)
{
foreach (var referencedAssembly in Settings.Default.ReferencedAssemblies)
{
_referencedAssemblies.Add(referencedAssembly);
}
UpdateExternalReferences();
}
LoadScript(String.IsNullOrEmpty(Settings.Default.ScriptFile) ? Application.StartupPath + "\\Scripts\\Default.cs" : Settings.Default.ScriptFile);
PlayLevel(String.IsNullOrEmpty(Settings.Default.MapFile) ? Application.StartupPath + "\\Maps\\DM_default.txt" : Settings.Default.MapFile);
}
private void PlayLevel(string mapFile)
{
pnlRendering.Enabled = false;
Globals.Device.Timer.Time = 0;
CombatManager.ClearEntities();
CollisionManager.ClearSpawningItems();
SceneNodeManager.ResetNodes();
CombatManager.ResetLists();
LevelManager.CreateLevel(mapFile);
pnlRendering.Enabled = true;
MessageDispatcher.ClearQueue();
ScriptRunner.ReflectScripts();
RuleManager.Reset();
if (Globals.Device != null)
{
Run(pnlRendering);
}
}
private void InitializeDevice(Control c)
{
Globals.Device = new IrrlichtDevice(DriverType.Direct3D8, new Dimension2D(1024, 768), 32, false, false, false, true, c.Handle);
if (Globals.Device == null)
{
MessageBox.Show("Could not create video device.", "Video device error");
return;
}
}
private void Run(Control c)
{
#region Initialization
_team1Player = SceneNodeManager.CreateTeam1SceneNode(LevelManager.GetTeamStartPosition(Team.Team1));
_team1Player.FloatingText = SceneNodeManager.CreateBillboardText(_team1Player.Node, String.Empty);
_team2Player = SceneNodeManager.CreateTeam2SceneNode(LevelManager.GetTeamStartPosition(Team.Team2));
_team2Player.FloatingText = SceneNodeManager.CreateBillboardText(_team2Player.Node, String.Empty);
var mainCamera = SceneNodeManager.CreateCameraSceneNode(new Vector3D(0, 1100, 0));
Globals.Scene.ActiveCamera = mainCamera;
ScriptRunner.DirectorAfterMapLoad(_team1Player, _team2Player);
#endregion Initialization
while (Globals.Device.Run() && c.Enabled) //Game loop
{
GC.Collect();
Globals.Driver.ClearZBuffer();
RenderManager.BeginRender();
LevelManager.UpdateLevelGraph();
CollisionManager.CheckProjectileCollisions(_team1Player);
CollisionManager.CheckProjectileCollisions(_team2Player);
CollisionManager.CheckPlayerCollisions(_team1Player, _team2Player);
CollisionManager.CheckSpawningItems();
CollisionManager.CheckBazookaCollisions(_team1Player);
CollisionManager.CheckBazookaCollisions(_team2Player);
CollisionManager.CheckMedkitCollisions(_team1Player);
CollisionManager.CheckMedkitCollisions(_team2Player);
Thinking(_team1Player, _team2Player);
Thinking(_team2Player, _team1Player);
ScriptRunner.DirectorThink(_team1Player, _team2Player);
foreach (var customEntity in SceneNodeManager.CustomEntities)
{
MoveEntity(customEntity);
}
CheckForDeath(_team1Player, _team2Player);
CheckForDeath(_team2Player, _team1Player);
UpdateLabels();
RenderManager.EndRender();
}
}
private void LoadScript(string filename)
{
_txtCode.ReferencedAssemblies.AddRange(new string[] { "System.dll", "DumbBots.NET.Api.dll" });
_txtCode.ReferencedAssemblies.AddRange(_referencedAssemblies);
if (File.Exists(filename))
_txtCode.Text = File.ReadAllText(filename);
}
private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
{
//HACK: objectdisposedexception throw by irrlicht when window is maximized!?!
this.WindowState = FormWindowState.Normal;
pnlRendering.Enabled = false;
Settings.Default.Save();
}
private void FrmMain_Deactivate(object sender, EventArgs e)
{
Globals.GameSpeed = 0;
}
private void FrmMain_Activated(object sender, EventArgs e)
{
Globals.GameSpeed = RuleManager.GameSpeed;
}
private void Thinking(CombatEntity entity, CombatEntity enemy)
{
ScriptRunner.Think(entity, enemy);
MoveEntity(entity);
}
private void MoveEntity(CombatEntity entity)
{
entity.Node.RemoveAnimators();
if (entity.Route.Count > 0)
{
Vector3D destination;
if (entity.Route.Count > 1)
destination = LevelManager.SparseGraph.GetNode(entity.Route[1]).Position;
else
{
destination = LevelManager.SparseGraph.GetNode(entity.Route[0]).Position;
}
entity.Destination = destination;
Line3D travelLine = new Line3D(entity.Node.Position, entity.Destination);
if (travelLine.Length > 0)
{
uint travelTime = (uint)(travelLine.Length * entity.SpeedModifier);
Animator anim = Globals.Scene.CreateFlyStraightAnimator(entity.Node.Position, entity.Destination, travelTime, false);
entity.Node.AddAnimator(anim);
entity.TargetRotation = travelLine.Vector.HorizontalAngle + entity.Rotation;
}
}
entity.UpdateRotation();
}
private void CheckForDeath(CombatEntity entity, CombatEntity enemy)
{
if (entity.Health == 0)
{
SoundManager.PlayDeath();
enemy.Score += 1;
int temp = GetNodes.GetFurthestNodeFromPosition(enemy.Node.Position);
entity.Destination = LevelManager.SparseGraph.GetNode(temp).Position;
if (entity.Destination == enemy.Destination)
{
temp = GetNodes.GetFurthestNodeFromPosition(enemy.Destination);
entity.Destination = LevelManager.SparseGraph.GetNode(temp).Position;
}
entity.Route = new List<int>();
entity.Node.RemoveAnimators();
Animator anim = Globals.Scene.CreateFlyStraightAnimator(entity.Node.Position, entity.Destination, 0, false);
entity.Node.AddAnimator(anim);
entity.Health = RuleManager.MaxHealth;
entity.Ammo = RuleManager.DefaultAmmo;
}
}
private void UpdateLabels()
{
btnPlayer1Info.Text = String.Format("Score: {0}", _team1Player.Score);
btnPlayer2Info.Text = String.Format("Score: {0}", _team2Player.Score);
}
private void PnlRendering_Resize(object sender, EventArgs e)
{
if (Globals.Device != null)
{
float aspectRatio = (float)pnlRendering.Width / pnlRendering.Height;
Globals.Scene.ActiveCamera.AspectRatio = aspectRatio;
}
}
private void UpdateExternalReferences()
{
btnDeleteReference.Enabled = false;
btnDeleteReference.DropDownItems.Clear();
if (_referencedAssemblies != null && _referencedAssemblies.Count > 0)
{
btnDeleteReference.Enabled = true;
foreach (string assemblyLocation in _referencedAssemblies)
{
btnDeleteReference.DropDownItems.Add(assemblyLocation, null, (s, e) =>
{
_referencedAssemblies.Remove(assemblyLocation);
if (Settings.Default.ReferencedAssemblies != null)
{
Settings.Default.ReferencedAssemblies.Remove(assemblyLocation);
}
UpdateExternalReferences();
});
}
}
}
private void LabelErrors_DoubleClick(object sender, EventArgs e)
{
if (lbErrors.SelectedItem != null && lbErrors.SelectedItem is ErrorInformation)
{
var lineNumber = (lbErrors.SelectedItem as ErrorInformation).LineNumber;
_txtCode.Lines[lineNumber - 1].Select();
_txtCode.Focus();
}
}
#region Menu Methods
private void btnCompileTeam1_Click(object sender, EventArgs e)
{
CompileScript(Team.Team1);
}
private void btnCompileTeam2_Click(object sender, EventArgs e)
{
CompileScript(Team.Team2);
}
private void btnCompileDirector_Click(object sender, EventArgs e)
{
CompileScript(Team.Director);
}
private void CompileScript(Team team)
{
SoundManager.PlayUpdate();
ScriptCompiler sc = new ScriptCompiler();
if (team == Team.Director)
{
PopulateErrors(sc.CompileDirectorScript("C#", _txtCode.Text, _referencedAssemblies));
ScriptRunner.ReflectDirectorScript();
}
else
{
PopulateErrors(sc.CompileScript("C#", _txtCode.Text, (int)team, _referencedAssemblies));
ScriptRunner.ReflectScript(team);
}
}
private void PopulateErrors(List<ErrorInformation> errorList)
{
lbErrors.Items.Clear();
if (errorList.Count > 0)
{
lbErrors.Items.AddRange(errorList.ToArray());
}
else
{
lbErrors.Items.Add("Build succeeded");
}
}
private void mnuFileSaveScript_Click(object sender, EventArgs e)
{
Globals.GameSpeed = 0;
dlgSaveScript.InitialDirectory = Application.StartupPath + "\\Scripts";
if (dlgSaveScript.ShowDialog() == DialogResult.OK)
{
File.WriteAllText(dlgSaveScript.FileName, _txtCode.Text);
}
Globals.GameSpeed = RuleManager.GameSpeed;
}
private void mnuFileLoadScript_Click(object sender, EventArgs e)
{
dlgOpenScript.InitialDirectory = Application.StartupPath + "\\Scripts";
if (dlgOpenScript.ShowDialog() == DialogResult.OK)
{
Settings.Default.ScriptFile = dlgOpenScript.FileName;
LoadScript(dlgOpenScript.FileName);
}
}
private void mnuFileLoadMap_Click(object sender, EventArgs e)
{
Globals.GameSpeed = 0;
dlgOpenMap.InitialDirectory = Application.StartupPath + "\\Maps";
if (dlgOpenMap.ShowDialog() == DialogResult.OK)
{
Settings.Default.MapFile = dlgOpenMap.FileName;
PlayLevel(dlgOpenMap.FileName);
}
Globals.GameSpeed = RuleManager.GameSpeed;
}
private void mnuHelpAbout_Click(object sender, EventArgs e)
{
frmAbout about = new frmAbout();
about.ShowDialog();
}
private void mnuSoundOff_Click(object sender, EventArgs e)
{
Settings.Default.Sound = SoundManager.PlaySound = false;
UpdateSoundUI();
}
private void mnuSoundOn_Click(object sender, EventArgs e)
{
Settings.Default.Sound = SoundManager.PlaySound = true;
UpdateSoundUI();
}
private void UpdateSoundUI()
{
if (Settings.Default.Sound)
{
btnSoundOn.Checked = true;
btnSoundOff.Checked = false;
}
else
{
btnSoundOn.Checked = false;
btnSoundOff.Checked = true;
}
}
private void mnuMapEditor_Click(object sender, EventArgs e)
{
Globals.GameSpeed = 0;
using (MapEditor editor = new MapEditor())
{
editor.ShowDialog();
}
Globals.GameSpeed = RuleManager.GameSpeed;
}
private void btnAddReference_Click(object sender, EventArgs e)
{
dlgAddReference.InitialDirectory = Application.StartupPath;
if (dlgAddReference.ShowDialog() == DialogResult.OK)
{
_referencedAssemblies.AddRange(dlgAddReference.FileNames);
if (Settings.Default.ReferencedAssemblies == null)
{
Settings.Default.ReferencedAssemblies = new System.Collections.Specialized.StringCollection();
}
Settings.Default.ReferencedAssemblies.AddRange(dlgAddReference.FileNames);
}
UpdateExternalReferences();
}
private void ReferenceDocumentToolStripMenuItem_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(Application.StartupPath + "\\Help\\DumbBots.htm");
}
private void btnBasicScriptEditor_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(Application.StartupPath + "\\BasicScriptEditor\\DumbBots.BasicCoder.exe");
}
#endregion Menu Methods
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Globalization;
using AWIComponentLib.Database;
using Microsoft.Win32;
namespace AWI.SmartTracker
{
/// <summary>
/// Summary description for DatabaseForm.
/// </summary>
public class DatabaseForm : System.Windows.Forms.Form
{
private System.Windows.Forms.TextBox PortTextBox;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox DBTextBox;
private System.Windows.Forms.TextBox ServerTextBox;
private System.Windows.Forms.TextBox PWTextBox;
private System.Windows.Forms.TextBox UserNameTextBox;
private System.Windows.Forms.Button CloseButton;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton SQLRadioButton;
private System.Windows.Forms.Label ConnectStatusLabel;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private MainForm mForm;
private OdbcDbClass odbcDB = new OdbcDbClass();
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Button ConnectButton;
private System.Windows.Forms.Button DisconnectButton;
private System.Windows.Forms.RadioButton MySQLRadioButton;
private OdbcConnection m_connection = null;
public DatabaseForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
}
public DatabaseForm(MainForm form)
{
InitializeComponent();
//changes made to support MYSQL Server v5.0 and later
CultureInfo ci = new CultureInfo("sv-SE", true);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
ci.DateTimeFormat.DateSeparator = "-";
mForm = form;
OdbcDbClass.NotifyDBConnectionStatusHandler += new NotifyDBConnectionStatus(DBConnectionStatusHandler);
if (MainForm.m_connection == null)
DisconnectButton.Enabled = false;
else
ConnectButton.Enabled = false;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.PortTextBox = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.DBTextBox = new System.Windows.Forms.TextBox();
this.ServerTextBox = new System.Windows.Forms.TextBox();
this.PWTextBox = new System.Windows.Forms.TextBox();
this.UserNameTextBox = new System.Windows.Forms.TextBox();
this.CloseButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.MySQLRadioButton = new System.Windows.Forms.RadioButton();
this.SQLRadioButton = new System.Windows.Forms.RadioButton();
this.ConnectStatusLabel = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.ConnectButton = new System.Windows.Forms.Button();
this.DisconnectButton = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// PortTextBox
//
this.PortTextBox.Location = new System.Drawing.Point(103, 198);
this.PortTextBox.Name = "PortTextBox";
this.PortTextBox.ReadOnly = true;
this.PortTextBox.Size = new System.Drawing.Size(154, 20);
this.PortTextBox.TabIndex = 25;
//
// label5
//
this.label5.Location = new System.Drawing.Point(37, 198);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(64, 23);
this.label5.TabIndex = 18;
this.label5.Text = "Port: ";
//
// label4
//
this.label4.Location = new System.Drawing.Point(37, 168);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 23);
this.label4.TabIndex = 17;
this.label4.Text = "Database: ";
//
// label3
//
this.label3.Location = new System.Drawing.Point(37, 138);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(64, 23);
this.label3.TabIndex = 16;
this.label3.Text = "Server:";
//
// label2
//
this.label2.Location = new System.Drawing.Point(37, 108);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(64, 23);
this.label2.TabIndex = 15;
this.label2.Text = "Password: ";
//
// label1
//
this.label1.Location = new System.Drawing.Point(37, 78);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(64, 23);
this.label1.TabIndex = 14;
this.label1.Text = "User Name: ";
//
// DBTextBox
//
this.DBTextBox.Location = new System.Drawing.Point(103, 168);
this.DBTextBox.Name = "DBTextBox";
this.DBTextBox.Size = new System.Drawing.Size(154, 20);
this.DBTextBox.TabIndex = 24;
//
// ServerTextBox
//
this.ServerTextBox.Location = new System.Drawing.Point(103, 138);
this.ServerTextBox.Name = "ServerTextBox";
this.ServerTextBox.Size = new System.Drawing.Size(154, 20);
this.ServerTextBox.TabIndex = 23;
//
// PWTextBox
//
this.PWTextBox.Location = new System.Drawing.Point(103, 108);
this.PWTextBox.Name = "PWTextBox";
this.PWTextBox.Size = new System.Drawing.Size(154, 20);
this.PWTextBox.TabIndex = 22;
//
// UserNameTextBox
//
this.UserNameTextBox.Location = new System.Drawing.Point(103, 78);
this.UserNameTextBox.Name = "UserNameTextBox";
this.UserNameTextBox.Size = new System.Drawing.Size(154, 20);
this.UserNameTextBox.TabIndex = 21;
//
// CloseButton
//
this.CloseButton.Location = new System.Drawing.Point(200, 280);
this.CloseButton.Name = "CloseButton";
this.CloseButton.Size = new System.Drawing.Size(75, 26);
this.CloseButton.TabIndex = 20;
this.CloseButton.Text = "Close";
this.CloseButton.Click += new System.EventHandler(this.CancelButton_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.MySQLRadioButton);
this.groupBox1.Controls.Add(this.SQLRadioButton);
this.groupBox1.Location = new System.Drawing.Point(35, 6);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(222, 56);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Database Server";
//
// MySQLRadioButton
//
this.MySQLRadioButton.Location = new System.Drawing.Point(130, 24);
this.MySQLRadioButton.Name = "MySQLRadioButton";
this.MySQLRadioButton.Size = new System.Drawing.Size(64, 24);
this.MySQLRadioButton.TabIndex = 1;
this.MySQLRadioButton.Text = "MySQL";
this.MySQLRadioButton.Click += new System.EventHandler(this.MySQLRadioButton_Click);
//
// SQLRadioButton
//
this.SQLRadioButton.Location = new System.Drawing.Point(40, 24);
this.SQLRadioButton.Name = "SQLRadioButton";
this.SQLRadioButton.Size = new System.Drawing.Size(56, 24);
this.SQLRadioButton.TabIndex = 0;
this.SQLRadioButton.Text = "SQL";
this.SQLRadioButton.Click += new System.EventHandler(this.SQLRadioButton_Click);
//
// ConnectStatusLabel
//
this.ConnectStatusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.ConnectStatusLabel.ForeColor = System.Drawing.Color.Red;
this.ConnectStatusLabel.Location = new System.Drawing.Point(104, 232);
this.ConnectStatusLabel.Name = "ConnectStatusLabel";
this.ConnectStatusLabel.Size = new System.Drawing.Size(152, 16);
this.ConnectStatusLabel.TabIndex = 27;
this.ConnectStatusLabel.Text = "Disconnected";
this.ConnectStatusLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label6
//
this.label6.Location = new System.Drawing.Point(32, 232);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(64, 23);
this.label6.TabIndex = 28;
this.label6.Text = "Status: ";
//
// ConnectButton
//
this.ConnectButton.Location = new System.Drawing.Point(24, 280);
this.ConnectButton.Name = "ConnectButton";
this.ConnectButton.Size = new System.Drawing.Size(75, 26);
this.ConnectButton.TabIndex = 29;
this.ConnectButton.Text = "Connect";
this.ConnectButton.Click += new System.EventHandler(this.ConnectButton_Click);
//
// DisconnectButton
//
this.DisconnectButton.Location = new System.Drawing.Point(112, 280);
this.DisconnectButton.Name = "DisconnectButton";
this.DisconnectButton.Size = new System.Drawing.Size(75, 26);
this.DisconnectButton.TabIndex = 30;
this.DisconnectButton.Text = "Disconnect";
this.DisconnectButton.Click += new System.EventHandler(this.DisconnectButton_Click);
//
// DatabaseForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(298, 317);
this.ControlBox = false;
this.Controls.Add(this.DisconnectButton);
this.Controls.Add(this.ConnectButton);
this.Controls.Add(this.label6);
this.Controls.Add(this.ConnectStatusLabel);
this.Controls.Add(this.PortTextBox);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.DBTextBox);
this.Controls.Add(this.ServerTextBox);
this.Controls.Add(this.PWTextBox);
this.Controls.Add(this.UserNameTextBox);
this.Controls.Add(this.CloseButton);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "DatabaseForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Database";
this.Load += new System.EventHandler(this.DatabaseForm_Load);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void DatabaseForm_Load(object sender, System.EventArgs e)
{
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;
if (MainForm.user.Length > 0)
UserNameTextBox.Text = MainForm.user;
if (MainForm.providerName == dbProvider.SQL)
{
SQLRadioButton.Checked = true;
if (MainForm.server.Length > 0)
ServerTextBox.Text = MainForm.server;
}
else if (MainForm.providerName == dbProvider.MySQL)
{
MySQLRadioButton.Checked = true;
if (MainForm.serverMySQL.Length > 0)
ServerTextBox.Text = MainForm.serverMySQL;
}
/*if (MainForm.server.Length > 0)
ServerTextBox.Text = MainForm.server;
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;*/
if (MainForm.m_connection == null)
{
ConnectStatusLabel.Text = "Disconnected";
}
else
{
ConnectStatusLabel.ForeColor = System.Drawing.Color.Blue;
ConnectStatusLabel.Text = "Connected";
}
}
private void ConnectButton_Click(object sender, System.EventArgs e)
{
if (MainForm.m_connection != null)
mForm.CloseConnection();
string s = "";
if (SQLRadioButton.Checked)
//if (MainForm.providerName == dbProvider.SQL)
{
//string s = "";
s = "Driver={SQL Native Client};";
if (ServerTextBox.TextLength > 0)
s += "Server=" + ServerTextBox.Text;
else
{
MainForm.PlaySound(1);
MessageBox.Show(this, "No server name", "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
s += ";";
if (DBTextBox.TextLength > 0)
s += "Database=" + DBTextBox.Text;
else
{
MainForm.PlaySound(1);
MessageBox.Show(this, "No database name", "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
s += ";";
s += "Trusted_Connection=yes;Pooling=False;";
//if (!odbcDB.Connect("Driver={SQL Native Client};Server=MainForm.server;Database=MainForm.database;Trusted_Connection=yes;Pooling=False;")) //SQL
MainForm.providerName = dbProvider.SQL;
MainForm.database = DBTextBox.Text;
MainForm.server = ServerTextBox.Text;
mForm.odbcDB.Connect(s);
MainForm.PlaySound(1);
/*if (!odbcDB.Connect(s)) //SQL
{
MainForm.conStr = "";
ConnectStatusLabel.ForeColor = System.Drawing.Color.Red;
ConnectStatusLabel.Text = "Disconnected";
MainForm.PlaySound(1);
return;
}*/
//MainForm.conStr = s;
//ConnectStatusLabel.ForeColor = System.Drawing.Color.Blue;
//ConnectStatusLabel.Text = "Connected";
}
else if (MySQLRadioButton.Checked) //if (MainForm.providerName == dbProvider.MySQL)
{
//string s = "";
s = "DRIVER={MySQL ODBC 3.51 Driver};";
if (ServerTextBox.TextLength > 0)
s += "Server=" + ServerTextBox.Text;
else
{
MainForm.PlaySound(1);
MessageBox.Show(this, "No server name", "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
s += ";";
if (DBTextBox.TextLength > 0)
s += "Database=" + DBTextBox.Text;
else
{
MainForm.PlaySound(1);
MessageBox.Show(this, "No database name", "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
s += ";";
if (UserNameTextBox.TextLength > 0)
s += "User=" + UserNameTextBox.Text;
else
{
MainForm.PlaySound(1);
MessageBox.Show(this, "No user name", "Smart Tracker", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
if (PWTextBox.TextLength > 0) {
s += ";PASSWORD=" + PWTextBox.Text;
} else {
s += ";PASSWORD=";
}
s += ";OPTION=3;";
MainForm.providerName = dbProvider.MySQL;
MainForm.database = DBTextBox.Text;
MainForm.serverMySQL = ServerTextBox.Text;
MainForm.user = UserNameTextBox.Text;
MainForm.password = PWTextBox.Text;
mForm.OpenConnection(s);
//mForm.odbcDB.Connect(s);
MainForm.PlaySound(1);
/*if (!odbcDB.Connect(s)) //MYSQL
{
MainForm.conStr = "";
ConnectStatusLabel.ForeColor = System.Drawing.Color.Red;
ConnectStatusLabel.Text = "Disconnected";
MainForm.PlaySound(1);
return;
}*/
////////////////////////////////
//if (!odbcDB.Connect("DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=parkingtracker;USER=root;PASSWORD=;OPTION=3;")) //MYSQL
//{
//return;
//}
}
else
{
return;
}
MainForm.conStr = s;
ConnectStatusLabel.ForeColor = System.Drawing.Color.Blue;
ConnectStatusLabel.Text = "Connected";
RegistryKey reg = Registry.CurrentUser.CreateSubKey("Software\\Active Wave\\Smart Tracker\\");
//reg.SetValue("server", MainForm.server);
reg.SetValue("database", MainForm.database);
if (MainForm.providerName == dbProvider.SQL)
{
reg.SetValue("provider", "SQL");
reg.SetValue("server", MainForm.server);
}
else
{
reg.SetValue("provider", "MySQL");
reg.SetValue("user", MainForm.user);
reg.SetValue("serverMySQL", MainForm.serverMySQL);
}
DisconnectButton.Enabled = true;
ConnectButton.Enabled = false;
MainForm.PlaySound(1);
}
private void DisconnectButton_Click(object sender, System.EventArgs e)
{
mForm.CloseConnection();
//mForm.timer4.Enabled = false;
/*ConnectStatusLabel.Text = "Disconnected";
ConnectStatusLabel.ForeColor = System.Drawing.Color.Red;
ConnectButton.Enabled = true;
DisconnectButton.Enabled = false;*/
MainForm.PlaySound(1);
}
private void CancelButton_Click(object sender, System.EventArgs e)
{
Close();
}
private void DBConnectionStatusHandler(status stat, OdbcConnection connect)
{
if (stat == status.open)
{
m_connection = connect;
//mForm.timer4.Enabled = tr;
}
else if (stat == status.broken)
{
m_connection = null;
}
else if (stat == status.close)
{
m_connection = null;
ConnectStatusLabel.Text = "Disconnected";
ConnectStatusLabel.ForeColor = System.Drawing.Color.Red;
ConnectButton.Enabled = true;
DisconnectButton.Enabled = false;
}
}
private void SQLRadioButton_Click(object sender, System.EventArgs e)
{
UserNameTextBox.Text = "";
if (MainForm.server.Length > 0)
ServerTextBox.Text = MainForm.server;
else
ServerTextBox.Text = "";
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;
}
private void MySQLRadioButton_Click(object sender, System.EventArgs e)
{
if (MainForm.user.Length > 0)
UserNameTextBox.Text = MainForm.user;
if (MainForm.server.Length > 0)
ServerTextBox.Text = MainForm.serverMySQL;
if (MainForm.database.Length > 0)
DBTextBox.Text = MainForm.database;
}
}
}
| |
// 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.IdentityModel.Policy;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
namespace System.IdentityModel.Claims
{
public class X509CertificateClaimSet : ClaimSet, IIdentityInfo, IDisposable
{
private X509Certificate2 _certificate;
private DateTime _expirationTime = SecurityUtils.MinUtcDateTime;
private ClaimSet _issuer;
private X509Identity _identity;
private X509ChainElementCollection _elements;
private IList<Claim> _claims;
private int _index;
private bool _disposed = false;
public X509CertificateClaimSet(X509Certificate2 certificate)
: this(certificate, true)
{
}
internal X509CertificateClaimSet(X509Certificate2 certificate, bool clone)
{
if (certificate == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("certificate");
_certificate = clone ? new X509Certificate2(certificate) : certificate;
}
private X509CertificateClaimSet(X509CertificateClaimSet from)
: this(from.X509Certificate, true)
{
}
private X509CertificateClaimSet(X509ChainElementCollection elements, int index)
{
_elements = elements;
_index = index;
_certificate = elements[index].Certificate;
}
public override Claim this[int index]
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims[index];
}
}
public override int Count
{
get
{
ThrowIfDisposed();
EnsureClaims();
return _claims.Count;
}
}
IIdentity IIdentityInfo.Identity
{
get
{
ThrowIfDisposed();
if (_identity == null)
_identity = new X509Identity(_certificate, false, false);
return _identity;
}
}
public DateTime ExpirationTime
{
get
{
ThrowIfDisposed();
if (_expirationTime == SecurityUtils.MinUtcDateTime)
_expirationTime = _certificate.NotAfter.ToUniversalTime();
return _expirationTime;
}
}
public override ClaimSet Issuer
{
get
{
ThrowIfDisposed();
if (_issuer == null)
{
if (_elements == null)
{
X509Chain chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.Build(_certificate);
_index = 0;
_elements = chain.ChainElements;
}
if (_index + 1 < _elements.Count)
{
_issuer = new X509CertificateClaimSet(_elements, _index + 1);
_elements = null;
}
// SelfSigned?
else if (StringComparer.OrdinalIgnoreCase.Equals(_certificate.SubjectName.Name, _certificate.IssuerName.Name))
_issuer = this;
else
_issuer = new X500DistinguishedNameClaimSet(_certificate.IssuerName);
}
return _issuer;
}
}
public X509Certificate2 X509Certificate
{
get
{
ThrowIfDisposed();
return _certificate;
}
}
internal X509CertificateClaimSet Clone()
{
ThrowIfDisposed();
return new X509CertificateClaimSet(this);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
SecurityUtils.DisposeIfNecessary(_identity);
if (_issuer != null)
{
if (_issuer != this)
{
SecurityUtils.DisposeIfNecessary(_issuer as IDisposable);
}
}
if (_elements != null)
{
for (int i = _index + 1; i < _elements.Count; ++i)
{
SecurityUtils.ResetCertificate(_elements[i].Certificate);
}
}
SecurityUtils.ResetCertificate(_certificate);
}
}
private IList<Claim> InitializeClaimsCore()
{
List<Claim> claims = new List<Claim>();
byte[] thumbprint = _certificate.GetCertHash();
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.Identity));
claims.Add(new Claim(ClaimTypes.Thumbprint, thumbprint, Rights.PossessProperty));
// Ordering SubjectName, Dns, SimpleName, Email, Upn
string value = _certificate.SubjectName.Name;
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateX500DistinguishedNameClaim(_certificate.SubjectName));
// A SAN field can have multiple DNS names
string[] dnsEntries = GetDnsFromExtensions(_certificate);
if (dnsEntries.Length > 0)
{
for (int i = 0; i < dnsEntries.Length; ++i)
{
claims.Add(Claim.CreateDnsClaim(dnsEntries[i]));
}
}
else
{
// If no SANs found in certificate, fall back to looking for the CN
value = _certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
{
claims.Add(Claim.CreateDnsClaim(value));
}
}
value = _certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateNameClaim(value));
value = _certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrEmpty(value))
#if SUPPORTS_WINDOWSIDENTITY
claims.Add(Claim.CreateUpnClaim(value));
#else
throw ExceptionHelper.PlatformNotSupported();
#endif // SUPPORTS_WINDOWSIDENTITY
value = _certificate.GetNameInfo(X509NameType.UrlName, false);
if (!string.IsNullOrEmpty(value))
claims.Add(Claim.CreateUriClaim(new Uri(value)));
//RSA rsa = _certificate.PublicKey.Key as RSA;
//if (rsa != null)
// claims.Add(Claim.CreateRsaClaim(rsa));
return claims;
}
private void EnsureClaims()
{
if (_claims != null)
return;
_claims = InitializeClaimsCore();
}
private static bool SupportedClaimType(string claimType)
{
return claimType == null ||
ClaimTypes.Thumbprint.Equals(claimType) ||
ClaimTypes.X500DistinguishedName.Equals(claimType) ||
ClaimTypes.Dns.Equals(claimType) ||
ClaimTypes.Name.Equals(claimType) ||
ClaimTypes.Email.Equals(claimType) ||
ClaimTypes.Upn.Equals(claimType) ||
ClaimTypes.Uri.Equals(claimType) ||
ClaimTypes.Rsa.Equals(claimType);
}
// Note: null string represents any.
public override IEnumerable<Claim> FindClaims(string claimType, string right)
{
ThrowIfDisposed();
if (!SupportedClaimType(claimType) || !ClaimSet.SupportedRight(right))
{
yield break;
}
else if (_claims == null && ClaimTypes.Thumbprint.Equals(claimType))
{
if (right == null || Rights.Identity.Equals(right))
{
yield return new Claim(ClaimTypes.Thumbprint, _certificate.GetCertHash(), Rights.Identity);
}
if (right == null || Rights.PossessProperty.Equals(right))
{
yield return new Claim(ClaimTypes.Thumbprint, _certificate.GetCertHash(), Rights.PossessProperty);
}
}
else if (_claims == null && ClaimTypes.Dns.Equals(claimType))
{
if (right == null || Rights.PossessProperty.Equals(right))
{
// A SAN field can have multiple DNS names
string[] dnsEntries = GetDnsFromExtensions(_certificate);
if (dnsEntries.Length > 0)
{
for (int i = 0; i < dnsEntries.Length; ++i)
{
yield return Claim.CreateDnsClaim(dnsEntries[i]);
}
}
else
{
// If no SANs found in certificate, fall back to looking at the CN
string value = _certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
{
yield return Claim.CreateDnsClaim(value);
}
}
}
}
else
{
EnsureClaims();
bool anyClaimType = (claimType == null);
bool anyRight = (right == null);
for (int i = 0; i < _claims.Count; ++i)
{
Claim claim = _claims[i];
if ((claim != null) &&
(anyClaimType || claimType.Equals(claim.ClaimType)) &&
(anyRight || right.Equals(claim.Right)))
{
yield return claim;
}
}
}
}
private static string[] GetDnsFromExtensions(X509Certificate2 cert)
{
foreach (X509Extension ext in cert.Extensions)
{
// Extension is SAN2
if (ext.Oid.Value == X509SubjectAlternativeNameConstants.Oid)
{
string asnString = ext.Format(false);
if (string.IsNullOrWhiteSpace(asnString))
{
return new string[0];
}
// SubjectAlternativeNames might contain something other than a dNSName,
// so we have to parse through and only use the dNSNames
// <identifier><delimter><value><separator(s)>
string[] rawDnsEntries =
asnString.Split(new string[1] { X509SubjectAlternativeNameConstants.Separator }, StringSplitOptions.RemoveEmptyEntries);
List<string> dnsEntries = new List<string>();
for (int i = 0; i < rawDnsEntries.Length; i++)
{
string[] keyval = rawDnsEntries[i].Split(X509SubjectAlternativeNameConstants.Delimiter);
if (string.Equals(keyval[0], X509SubjectAlternativeNameConstants.Identifier))
{
dnsEntries.Add(keyval[1]);
}
}
return dnsEntries.ToArray();
}
}
return new string[0];
}
public override IEnumerator<Claim> GetEnumerator()
{
ThrowIfDisposed();
EnsureClaims();
return _claims.GetEnumerator();
}
public override string ToString()
{
return _disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this);
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
private class X500DistinguishedNameClaimSet : DefaultClaimSet, IIdentityInfo
{
private IIdentity _identity;
public X500DistinguishedNameClaimSet(X500DistinguishedName x500DistinguishedName)
{
if (x500DistinguishedName == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("x500DistinguishedName");
_identity = new X509Identity(x500DistinguishedName);
List<Claim> claims = new List<Claim>(2);
claims.Add(new Claim(ClaimTypes.X500DistinguishedName, x500DistinguishedName, Rights.Identity));
claims.Add(Claim.CreateX500DistinguishedNameClaim(x500DistinguishedName));
Initialize(ClaimSet.Anonymous, claims);
}
public IIdentity Identity
{
get { return _identity; }
}
}
// We don't have a strongly typed extension to parse Subject Alt Names, so we have to do a workaround
// to figure out what the identifier, delimiter, and separator is by using a well-known extension
private static class X509SubjectAlternativeNameConstants
{
public const string Oid = "2.5.29.17";
private static readonly string s_identifier;
private static readonly char s_delimiter;
private static readonly string s_separator;
private static bool s_successfullyInitialized = false;
private static Exception s_initializationException;
public static string Identifier
{
get
{
EnsureInitialized();
return s_identifier;
}
}
public static char Delimiter
{
get
{
EnsureInitialized();
return s_delimiter;
}
}
public static string Separator
{
get
{
EnsureInitialized();
return s_separator;
}
}
private static void EnsureInitialized()
{
if (!s_successfullyInitialized)
{
throw new FormatException(string.Format(
"There was an error detecting the identifier, delimiter, and separator for X509CertificateClaims on this platform.{0}" +
"Detected values were: Identifier: '{1}'; Delimiter:'{2}'; Separator:'{3}'",
Environment.NewLine,
s_identifier,
s_delimiter,
s_separator
), s_initializationException);
}
}
// static initializer runs only when one of the properties is accessed
static X509SubjectAlternativeNameConstants()
{
// Extracted a well-known X509Extension
byte[] x509ExtensionBytes = new byte[] {
48, 36, 130, 21, 110, 111, 116, 45, 114, 101, 97, 108, 45, 115, 117, 98, 106, 101, 99,
116, 45, 110, 97, 109, 101, 130, 11, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109
};
const string subjectName1 = "not-real-subject-name";
try
{
X509Extension x509Extension = new X509Extension(Oid, x509ExtensionBytes, true);
string x509ExtensionFormattedString = x509Extension.Format(false);
// Each OS has a different dNSName identifier and delimiter
// On Windows, dNSName == "DNS Name" (localizable), on Linux, dNSName == "DNS"
// e.g.,
// Windows: x509ExtensionFormattedString is: "DNS Name=not-real-subject-name, DNS Name=example.com"
// Linux: x509ExtensionFormattedString is: "DNS:not-real-subject-name, DNS:example.com"
// Parse: <identifier><delimter><value><separator(s)>
int delimiterIndex = x509ExtensionFormattedString.IndexOf(subjectName1) - 1;
s_delimiter = x509ExtensionFormattedString[delimiterIndex];
// Make an assumption that all characters from the the start of string to the delimiter
// are part of the identifier
s_identifier = x509ExtensionFormattedString.Substring(0, delimiterIndex);
int separatorFirstChar = delimiterIndex + subjectName1.Length + 1;
int separatorLength = 1;
for (int i = separatorFirstChar + 1; i < x509ExtensionFormattedString.Length; i++)
{
// We advance until the first character of the identifier to determine what the
// separator is. This assumes that the identifier assumption above is correct
if (x509ExtensionFormattedString[i] == s_identifier[0])
{
break;
}
separatorLength++;
}
s_separator = x509ExtensionFormattedString.Substring(separatorFirstChar, separatorLength);
s_successfullyInitialized = true;
}
catch (Exception ex)
{
s_successfullyInitialized = false;
s_initializationException = ex;
}
}
}
}
internal class X509Identity : GenericIdentity, IDisposable
{
private const string X509 = "X509";
private const string Thumbprint = "; ";
private X500DistinguishedName _x500DistinguishedName;
private X509Certificate2 _certificate;
private string _name;
private bool _disposed = false;
private bool _disposable = true;
public X509Identity(X509Certificate2 certificate)
: this(certificate, true, true)
{
}
public X509Identity(X500DistinguishedName x500DistinguishedName)
: base(X509, X509)
{
_x500DistinguishedName = x500DistinguishedName;
}
internal X509Identity(X509Certificate2 certificate, bool clone, bool disposable)
: base(X509, X509)
{
_certificate = clone ? new X509Certificate2(certificate) : certificate;
_disposable = clone || disposable;
}
public override string Name
{
get
{
ThrowIfDisposed();
if (_name == null)
{
//
// PrincipalPermission authorization using certificates could cause Elevation of Privilege.
// because there could be duplicate subject name. In order to be more unique, we use SubjectName + Thumbprint
// instead
//
_name = GetName() + Thumbprint + _certificate.Thumbprint;
}
return _name;
}
}
private string GetName()
{
if (_x500DistinguishedName != null)
return _x500DistinguishedName.Name;
string value = _certificate.SubjectName.Name;
if (!string.IsNullOrEmpty(value))
return value;
value = _certificate.GetNameInfo(X509NameType.DnsName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = _certificate.GetNameInfo(X509NameType.SimpleName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = _certificate.GetNameInfo(X509NameType.EmailName, false);
if (!string.IsNullOrEmpty(value))
return value;
value = _certificate.GetNameInfo(X509NameType.UpnName, false);
if (!string.IsNullOrEmpty(value))
return value;
return String.Empty;
}
public override ClaimsIdentity Clone()
{
return _certificate != null ? new X509Identity(_certificate) : new X509Identity(_x500DistinguishedName);
}
public void Dispose()
{
if (_disposable && !_disposed)
{
_disposed = true;
if (_certificate != null)
{
_certificate.Dispose();
}
}
}
private void ThrowIfDisposed()
{
if (_disposed)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ObjectDisposedException(this.GetType().FullName));
}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
using Microsoft.AspNetCore.Razor.Hosting;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
{
internal class RuntimeViewCompiler : IViewCompiler
{
private readonly object _cacheLock = new object();
private readonly Dictionary<string, CompiledViewDescriptor> _precompiledViews;
private readonly ConcurrentDictionary<string, string> _normalizedPathCache;
private readonly IFileProvider _fileProvider;
private readonly RazorProjectEngine _projectEngine;
private readonly IMemoryCache _cache;
private readonly ILogger _logger;
private readonly CSharpCompiler _csharpCompiler;
public RuntimeViewCompiler(
IFileProvider fileProvider,
RazorProjectEngine projectEngine,
CSharpCompiler csharpCompiler,
IList<CompiledViewDescriptor> precompiledViews,
ILogger logger)
{
if (fileProvider == null)
{
throw new ArgumentNullException(nameof(fileProvider));
}
if (projectEngine == null)
{
throw new ArgumentNullException(nameof(projectEngine));
}
if (csharpCompiler == null)
{
throw new ArgumentNullException(nameof(csharpCompiler));
}
if (precompiledViews == null)
{
throw new ArgumentNullException(nameof(precompiledViews));
}
if (logger == null)
{
throw new ArgumentNullException(nameof(logger));
}
_fileProvider = fileProvider;
_projectEngine = projectEngine;
_csharpCompiler = csharpCompiler;
_logger = logger;
_normalizedPathCache = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
// This is our L0 cache, and is a durable store. Views migrate into the cache as they are requested
// from either the set of known precompiled views, or by being compiled.
_cache = new MemoryCache(new MemoryCacheOptions());
// We need to validate that the all of the precompiled views are unique by path (case-insensitive).
// We do this because there's no good way to canonicalize paths on windows, and it will create
// problems when deploying to linux. Rather than deal with these issues, we just don't support
// views that differ only by case.
_precompiledViews = new Dictionary<string, CompiledViewDescriptor>(
precompiledViews.Count,
StringComparer.OrdinalIgnoreCase);
foreach (var precompiledView in precompiledViews)
{
logger.ViewCompilerLocatedCompiledView(precompiledView.RelativePath);
if (!_precompiledViews.ContainsKey(precompiledView.RelativePath))
{
// View ordering has precedence semantics, a view with a higher precedence was
// already added to the list.
_precompiledViews.Add(precompiledView.RelativePath, precompiledView);
}
}
if (_precompiledViews.Count == 0)
{
logger.ViewCompilerNoCompiledViewsFound();
}
}
public Task<CompiledViewDescriptor> CompileAsync(string relativePath)
{
if (relativePath == null)
{
throw new ArgumentNullException(nameof(relativePath));
}
// Attempt to lookup the cache entry using the passed in path. This will succeed if the path is already
// normalized and a cache entry exists.
if (_cache.TryGetValue(relativePath, out Task<CompiledViewDescriptor> cachedResult))
{
return cachedResult;
}
var normalizedPath = GetNormalizedPath(relativePath);
if (_cache.TryGetValue(normalizedPath, out cachedResult))
{
return cachedResult;
}
// Entry does not exist. Attempt to create one.
cachedResult = OnCacheMiss(normalizedPath);
return cachedResult;
}
private Task<CompiledViewDescriptor> OnCacheMiss(string normalizedPath)
{
ViewCompilerWorkItem item;
TaskCompletionSource<CompiledViewDescriptor> taskSource;
MemoryCacheEntryOptions cacheEntryOptions;
// Safe races cannot be allowed when compiling Razor pages. To ensure only one compilation request succeeds
// per file, we'll lock the creation of a cache entry. Creating the cache entry should be very quick. The
// actual work for compiling files happens outside the critical section.
lock (_cacheLock)
{
// Double-checked locking to handle a possible race.
if (_cache.TryGetValue(normalizedPath, out Task<CompiledViewDescriptor> result))
{
return result;
}
if (_precompiledViews.TryGetValue(normalizedPath, out var precompiledView))
{
_logger.ViewCompilerLocatedCompiledViewForPath(normalizedPath);
item = CreatePrecompiledWorkItem(normalizedPath, precompiledView);
}
else
{
item = CreateRuntimeCompilationWorkItem(normalizedPath);
}
// At this point, we've decided what to do - but we should create the cache entry and
// release the lock first.
cacheEntryOptions = new MemoryCacheEntryOptions();
Debug.Assert(item.ExpirationTokens != null);
for (var i = 0; i < item.ExpirationTokens.Count; i++)
{
cacheEntryOptions.ExpirationTokens.Add(item.ExpirationTokens[i]);
}
taskSource = new TaskCompletionSource<CompiledViewDescriptor>(creationOptions: TaskCreationOptions.RunContinuationsAsynchronously);
if (item.SupportsCompilation)
{
// We'll compile in just a sec, be patient.
}
else
{
// If we can't compile, we should have already created the descriptor
Debug.Assert(item.Descriptor != null);
taskSource.SetResult(item.Descriptor);
}
_cache.Set(normalizedPath, taskSource.Task, cacheEntryOptions);
}
// Now the lock has been released so we can do more expensive processing.
if (item.SupportsCompilation)
{
Debug.Assert(taskSource != null);
if (item.Descriptor?.Item != null &&
ChecksumValidator.IsItemValid(_projectEngine.FileSystem, item.Descriptor.Item))
{
// If the item has checksums to validate, we should also have a precompiled view.
Debug.Assert(item.Descriptor != null);
taskSource.SetResult(item.Descriptor);
return taskSource.Task;
}
_logger.ViewCompilerInvalidingCompiledFile(item.NormalizedPath);
try
{
var descriptor = CompileAndEmit(normalizedPath);
descriptor.ExpirationTokens = cacheEntryOptions.ExpirationTokens;
taskSource.SetResult(descriptor);
}
catch (Exception ex)
{
taskSource.SetException(ex);
}
}
return taskSource.Task;
}
private ViewCompilerWorkItem CreatePrecompiledWorkItem(string normalizedPath, CompiledViewDescriptor precompiledView)
{
// We have a precompiled view - but we're not sure that we can use it yet.
//
// We need to determine first if we have enough information to 'recompile' this view. If that's the case
// we'll create change tokens for all of the files.
//
// Then we'll attempt to validate if any of those files have different content than the original sources
// based on checksums.
if (precompiledView.Item == null || !ChecksumValidator.IsRecompilationSupported(precompiledView.Item))
{
return new ViewCompilerWorkItem()
{
// If we don't have a checksum for the primary source file we can't recompile.
SupportsCompilation = false,
ExpirationTokens = Array.Empty<IChangeToken>(), // Never expire because we can't recompile.
Descriptor = precompiledView, // This will be used as-is.
};
}
var item = new ViewCompilerWorkItem()
{
SupportsCompilation = true,
Descriptor = precompiledView, // This might be used, if the checksums match.
// Used to validate and recompile
NormalizedPath = normalizedPath,
ExpirationTokens = GetExpirationTokens(precompiledView),
};
// We also need to create a new descriptor, because the original one doesn't have expiration tokens on
// it. These will be used by the view location cache, which is like an L1 cache for views (this class is
// the L2 cache).
item.Descriptor = new CompiledViewDescriptor()
{
ExpirationTokens = item.ExpirationTokens,
Item = precompiledView.Item,
RelativePath = precompiledView.RelativePath,
};
return item;
}
private ViewCompilerWorkItem CreateRuntimeCompilationWorkItem(string normalizedPath)
{
IList<IChangeToken> expirationTokens = new List<IChangeToken>
{
_fileProvider.Watch(normalizedPath),
};
var projectItem = _projectEngine.FileSystem.GetItem(normalizedPath, fileKind: null);
if (!projectItem.Exists)
{
_logger.ViewCompilerCouldNotFindFileAtPath(normalizedPath);
// If the file doesn't exist, we can't do compilation right now - we still want to cache
// the fact that we tried. This will allow us to re-trigger compilation if the view file
// is added.
return new ViewCompilerWorkItem()
{
// We don't have enough information to compile
SupportsCompilation = false,
Descriptor = new CompiledViewDescriptor()
{
RelativePath = normalizedPath,
ExpirationTokens = expirationTokens,
},
// We can try again if the file gets created.
ExpirationTokens = expirationTokens,
};
}
_logger.ViewCompilerFoundFileToCompile(normalizedPath);
GetChangeTokensFromImports(expirationTokens, projectItem);
return new ViewCompilerWorkItem()
{
SupportsCompilation = true,
NormalizedPath = normalizedPath,
ExpirationTokens = expirationTokens,
};
}
private IList<IChangeToken> GetExpirationTokens(CompiledViewDescriptor precompiledView)
{
var checksums = precompiledView.Item.GetChecksumMetadata();
var expirationTokens = new List<IChangeToken>(checksums.Count);
for (var i = 0; i < checksums.Count; i++)
{
// We rely on Razor to provide the right set of checksums. Trust the compiler, it has to do a good job,
// so it probably will.
expirationTokens.Add(_fileProvider.Watch(checksums[i].Identifier));
}
return expirationTokens;
}
private void GetChangeTokensFromImports(IList<IChangeToken> expirationTokens, RazorProjectItem projectItem)
{
// OK this means we can do compilation. For now let's just identify the other files we need to watch
// so we can create the cache entry. Compilation will happen after we release the lock.
var importFeature = _projectEngine.ProjectFeatures.OfType<IImportProjectFeature>().ToArray();
foreach (var feature in importFeature)
{
foreach (var file in feature.GetImports(projectItem))
{
if (file.FilePath != null)
{
expirationTokens.Add(_fileProvider.Watch(file.FilePath));
}
}
}
}
protected virtual CompiledViewDescriptor CompileAndEmit(string relativePath)
{
var projectItem = _projectEngine.FileSystem.GetItem(relativePath, fileKind: null);
var codeDocument = _projectEngine.Process(projectItem);
var cSharpDocument = codeDocument.GetCSharpDocument();
if (cSharpDocument.Diagnostics.Count > 0)
{
throw CompilationFailedExceptionFactory.Create(
codeDocument,
cSharpDocument.Diagnostics);
}
var assembly = CompileAndEmit(codeDocument, cSharpDocument.GeneratedCode);
// Anything we compile from source will use Razor 2.1 and so should have the new metadata.
var loader = new RazorCompiledItemLoader();
var item = loader.LoadItems(assembly).Single();
return new CompiledViewDescriptor(item);
}
internal Assembly CompileAndEmit(RazorCodeDocument codeDocument, string generatedCode)
{
_logger.GeneratedCodeToAssemblyCompilationStart(codeDocument.Source.FilePath);
var startTimestamp = _logger.IsEnabled(LogLevel.Debug) ? Stopwatch.GetTimestamp() : 0;
var assemblyName = Path.GetRandomFileName();
var compilation = CreateCompilation(generatedCode, assemblyName);
var emitOptions = _csharpCompiler.EmitOptions;
var emitPdbFile = _csharpCompiler.EmitPdb && emitOptions.DebugInformationFormat != DebugInformationFormat.Embedded;
using (var assemblyStream = new MemoryStream())
using (var pdbStream = emitPdbFile ? new MemoryStream() : null)
{
var result = compilation.Emit(
assemblyStream,
pdbStream,
options: emitOptions);
if (!result.Success)
{
throw CompilationFailedExceptionFactory.Create(
codeDocument,
generatedCode,
assemblyName,
result.Diagnostics);
}
assemblyStream.Seek(0, SeekOrigin.Begin);
pdbStream?.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(assemblyStream.ToArray(), pdbStream?.ToArray());
_logger.GeneratedCodeToAssemblyCompilationEnd(codeDocument.Source.FilePath, startTimestamp);
return assembly;
}
}
private CSharpCompilation CreateCompilation(string compilationContent, string assemblyName)
{
var sourceText = SourceText.From(compilationContent, Encoding.UTF8);
var syntaxTree = _csharpCompiler.CreateSyntaxTree(sourceText).WithFilePath(assemblyName);
return _csharpCompiler
.CreateCompilation(assemblyName)
.AddSyntaxTrees(syntaxTree);
}
private string GetNormalizedPath(string relativePath)
{
Debug.Assert(relativePath != null);
if (relativePath.Length == 0)
{
return relativePath;
}
if (!_normalizedPathCache.TryGetValue(relativePath, out var normalizedPath))
{
normalizedPath = ViewPath.NormalizePath(relativePath);
_normalizedPathCache[relativePath] = normalizedPath;
}
return normalizedPath;
}
private class ViewCompilerWorkItem
{
public bool SupportsCompilation { get; set; } = default!;
public string NormalizedPath { get; set; } = default!;
public IList<IChangeToken> ExpirationTokens { get; set; } = default!;
public CompiledViewDescriptor Descriptor { get; set; } = default!;
}
}
}
| |
/*
* REST API Documentation for the MOTI School Bus Application
*
* The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus.
*
* OpenAPI spec version: v1
*
*
*/
using System;
using Microsoft.AspNetCore.Mvc;
using SchoolBusAPI.Models;
using SchoolBusAPI.Services;
using SchoolBusAPI.Authorization;
using SchoolBusAPI.Helpers;
using SchoolBusAPI.ViewModels;
namespace SchoolBusAPI.Controllers
{
/// <summary>
///
/// </summary>
[ApiVersion("1.0")]
[ApiController]
public class SchoolBusController : ControllerBase
{
private readonly ISchoolBusService _service;
/// <summary>
/// Create a controller and set the service
/// </summary>
public SchoolBusController(ISchoolBusService service)
{
_service = service;
}
/// <summary>
///
/// </summary>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesGet()
{
return this._service.SchoolbusesGetAsync();
}
/// <summary>
///
/// </summary>
/// <remarks>Returns attachments for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch attachments for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/attachments")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdAttachmentsGet([FromRoute]int id)
{
return this._service.SchoolbusesIdAttachmentsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns CCWData for a particular Schoolbus</remarks>
/// <param name="id">id of SchoolBus to fetch CCWData for</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/ccwdata")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdCcwdataGet([FromRoute]int id)
{
return this._service.SchoolbusesIdCcwdataGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to delete</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpPost]
[Route("/api/schoolbuses/{id}/delete")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdDeletePost([FromRoute]int id)
{
return this._service.SchoolbusesIdDeletePostAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdGet([FromRoute]int id)
{
return this._service.SchoolbusesIdGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns History for a particular SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch History for</param>
/// <param name="offset">offset for records that are returned</param>
/// <param name="limit">limits the number of records returned.</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/history")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdHistoryGet([FromRoute]int id, [FromQuery]int? offset, [FromQuery]int? limit)
{
return this._service.SchoolbusesIdHistoryGetAsync(id, offset, limit);
}
/// <summary>
///
/// </summary>
/// <remarks>Add a History record to the SchoolBus</remarks>
/// <param name="id">id of SchoolBus to fetch History for</param>
/// <param name="item"></param>
/// <response code="201">History created</response>
[HttpPost]
[Route("/api/schoolbuses/{id}/history")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdHistoryPost([FromRoute]int id, [FromBody]History item)
{
return this._service.SchoolbusesIdHistoryPostAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch Inspections for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/inspections")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdInspectionsGet([FromRoute]int id)
{
return this._service.SchoolbusesIdInspectionsGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Obtains a new permit number for the indicated Schoolbus. Returns the updated SchoolBus record.</remarks>
/// <param name="id">id of SchoolBus to obtain a new permit number for</param>
/// <response code="200">OK</response>
[HttpPut]
[Route("/api/schoolbuses/{id}/newpermit")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdNewpermitPut([FromRoute]int id)
{
return this._service.SchoolbusesIdNewpermitPutAsync(id);
}
/// <summary>
///
/// </summary>
/// <remarks>Returns notes for a particular SchoolBus.</remarks>
/// <param name="id">id of SchoolBus to fetch notes for</param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/notes")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdNotesGet([FromRoute]int id)
{
return this._service.SchoolbusesIdNotesGetAsync(id);
}
[HttpPut]
[Route("/api/schoolbuses/{sbId}/notes/{noteId}")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdNotesPut(int sbId, int noteId, [FromBody]NoteSaveViewModel item)
{
var (success, error) = _service.UpdateSchoolBusNote(sbId, noteId, item);
return success ? NoContent() : error;
}
[HttpPost]
[Route("/api/schoolbuses/{sbId}/notes/")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdNotesPost(int sbId, [FromBody]NoteSaveViewModel note)
{
var (success, error) = _service.CreateSchoolBusNote(sbId, note);
return success ? NoContent() : error;
}
[HttpDelete]
[Route("/api/schoolbuses/{sbId}/notes/{noteId}")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdNotesDelete(int sbId, int noteId)
{
var (success, error) = _service.DeleteSchoolBusNote(sbId, noteId);
return success ? NoContent() : error;
}
/// <summary>
///
/// </summary>
/// <remarks>Returns a PDF version of the permit for the selected Schoolbus</remarks>
/// <param name="id">id of SchoolBus to obtain the PDF permit for</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/{id}/pdfpermit")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesIdPdfpermitGet([FromRoute]int id)
{
return this._service.SchoolbusesIdPdfpermitGetAsync(id);
}
/// <summary>
///
/// </summary>
/// <param name="id">id of SchoolBus to fetch</param>
/// <param name="item"></param>
/// <response code="200">OK</response>
/// <response code="404">SchoolBus not found</response>
[HttpPut]
[Route("/api/schoolbuses/{id}")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesIdPut([FromRoute]int id, [FromBody]SchoolBus item)
{
return this._service.SchoolbusesIdPutAsync(id, item);
}
/// <summary>
///
/// </summary>
/// <param name="item"></param>
/// <response code="201">SchoolBus created</response>
[HttpPost]
[Route("/api/schoolbuses")]
[RequiresPermission(Permissions.SchoolBusWrite)]
public virtual IActionResult SchoolbusesPost([FromBody]SchoolBus item)
{
return this._service.SchoolbusesPostAsync(item);
}
/// <summary>
/// Searches school buses
/// </summary>
/// <remarks>Used for the search schoolbus page.</remarks>
/// <param name="districts">Districts (array of id numbers)</param>
/// <param name="inspectors">Assigned School Bus Inspectors (array of id numbers)</param>
/// <param name="cities">Cities (array of id numbers)</param>
/// <param name="schooldistricts">School Districts (array of id numbers)</param>
/// <param name="owner"></param>
/// <param name="regi">e Regi Number</param>
/// <param name="vin">VIN</param>
/// <param name="plate">License Plate String</param>
/// <param name="includeInactive">True if Inactive schoolbuses will be returned</param>
/// <param name="onlyReInspections">If true, only buses that need a re-inspection will be returned</param>
/// <param name="startDate">Inspection start date</param>
/// <param name="endDate">Inspection end date</param>
/// <response code="200">OK</response>
[HttpGet]
[Route("/api/schoolbuses/search")]
[RequiresPermission(Permissions.SchoolBusRead)]
public virtual IActionResult SchoolbusesSearchGet(
[ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] districts,
[ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] inspectors,
[ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] cities,
[ModelBinder(BinderType = typeof(CsvArrayBinder))]int?[] schooldistricts,
[FromQuery]int? owner,
[FromQuery]string regi,
[FromQuery]string vin,
[FromQuery]string plate,
[FromQuery]bool? includeInactive,
[FromQuery]bool? onlyReInspections,
[FromQuery]DateTime? startDate,
[FromQuery]DateTime? endDate)
{
// TODO: Implement fix for Swagger and APIExplorer interpretation of ModelBinder
// TODO: Return 400 Bad Request status code when query is malformed
// TODO: Integrate ModelBinder with SimpleModelBinderProvider
return this._service.SchoolbusesSearchGetAsync(districts, inspectors, cities, schooldistricts, owner, regi, vin, plate, includeInactive, onlyReInspections, startDate, endDate);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AddressCompositeControlTemplate.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Globalization;
using Adxstudio.Xrm.Resources;
using Adxstudio.Xrm.Web.UI.WebControls;
using Microsoft.Practices.EnterpriseLibrary.Common.Utility;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Metadata;
/// <summary>
/// Fullname control
/// </summary>
/// <seealso cref="Adxstudio.Xrm.Web.UI.CrmEntityFormView.CellTemplate" />
/// <seealso cref="Adxstudio.Xrm.Web.UI.CrmEntityFormView.ICustomFieldControlTemplate" />
public class AddressCompositeControlTemplate : CellTemplate, ICustomFieldControlTemplate
{
/// <summary>
/// Address Field alias
/// </summary>
private readonly string alias;
/// <summary>
/// The entity metadata
/// </summary>
private readonly EntityMetadata entityMetadata;
/// <summary>
/// The is editable
/// </summary>
private bool isEditable;
/// <summary>
/// Address Control Value
/// </summary>
private StringBuilder addressControlValue;
/// <summary>
/// Bind Control Value
/// </summary>
private ICollection<Action<Entity>> bindControlValue;
/// <summary>
/// Initializes a new instance of the <see cref="AddressCompositeControlTemplate"/> class.
/// </summary>
/// <param name="field">The field.</param>
/// <param name="metadata">The metadata.</param>
/// <param name="validationGroup">The validation group.</param>
/// <param name="bindings">The bindings.</param>
/// <param name="entityMetadata">The entity metadata.</param>
/// <param name="mode">The mode.</param>
public AddressCompositeControlTemplate(
CrmEntityFormViewField field,
FormXmlCellMetadata metadata,
string validationGroup,
IDictionary<string, CellBinding> bindings,
EntityMetadata entityMetadata,
FormViewMode? mode)
: base(metadata, validationGroup, bindings)
{
this.Field = field;
this.isEditable = mode != FormViewMode.ReadOnly;
this.entityMetadata = entityMetadata;
this.alias = this.ControlID.Split('_').First();
this.bindControlValue = new List<Action<Entity>>();
}
/// <summary>
/// CSS Class name assigned.
/// </summary>
public override string CssClass
{
get
{
return "text form-control";
}
}
/// <summary>
/// Gets the field.
/// </summary>
/// <value>
/// The field.
/// </value>
public CrmEntityFormViewField Field { get; private set; }
/// <summary>
/// Gets the validator display.
/// </summary>
/// <value>
/// The validator display.
/// </value>
private ValidatorDisplay ValidatorDisplay
{
get
{
return string.IsNullOrWhiteSpace(this.Metadata.ValidationText) ? ValidatorDisplay.None : ValidatorDisplay.Dynamic;
}
}
/// <summary>
/// Instantiates the control in.
/// </summary>
/// <param name="container">The container.</param>
protected override void InstantiateControlIn(Control container)
{
var contentId = Guid.NewGuid();
if (this.Metadata.ReadOnly)
{
this.isEditable = false;
}
var addressTextBox = new TextBox
{
ID = this.ControlID,
CssClass = string.Join(" ", "trigger", this.CssClass, this.Metadata.CssClass, "addressCompositeControl"),
ToolTip = this.Metadata.ToolTip,
TextMode = TextBoxMode.MultiLine
};
addressTextBox.Attributes.Add("data-composite-control", string.Empty);
addressTextBox.Attributes.Add("data-content-id", contentId.ToString());
addressTextBox.Attributes.Add("data-editable", this.isEditable.ToString());
try
{
addressTextBox.Rows = checked((this.Metadata.RowSpan.GetValueOrDefault(2) * 3) - 2);
}
catch (OverflowException)
{
addressTextBox.Rows = 3;
}
container.Controls.Add(addressTextBox);
// Creating container for all popover elements
var divContainer = new HtmlGenericControl("div");
divContainer.Attributes["class"] = "content hide addressCompositeControlContainer";
divContainer.ID = contentId.ToString();
var addRangeControls =
new Action<IEnumerable<Control>>(controls => { controls.ForEach(x => divContainer.Controls.Add(x)); });
container.Controls.Add(divContainer);
switch (CultureInfo.CurrentUICulture.LCID)
{
case LocaleIds.Japanese:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_postalcode}}{{BREAK}}{{{0}_country}} {{{0}_stateorprovince}} {{{0}_city}}{{BREAK}}{{{0}_line1}} {{{0}_line2}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
this.MakeState(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeAddressLine1(addRangeControls);
this.MakeAddressLine2(addRangeControls);
break;
case LocaleIds.ChineseSimplified:
case LocaleIds.ChineseHongKong:
case LocaleIds.ChineseTraditional:
case LocaleIds.Korean:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_postalcode}} {{{0}_country}}{{BREAK}}{{{0}_stateorprovince}} {{{0}_city}}{{BREAK}}{{{0}_line1}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
this.MakeState(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeAddressLine1(addRangeControls);
break;
default:
addressTextBox.Attributes.Add(
"data-content-template",
string.Format("{{{0}_line1}} {{{0}_line2}} {{{0}_line3}}{{BREAK}}{{{0}_city}} {{{0}_stateorprovince}} {{{0}_postalcode}}{{BREAK}}{{{0}_country}}", this.ControlID));
this.addressControlValue = new StringBuilder(addressTextBox.Attributes["data-content-template"]);
this.MakeAddressLine1(addRangeControls);
this.MakeAddressLine2(addRangeControls);
this.MakeAddressLine3(addRangeControls);
this.MakeCity(addRangeControls);
this.MakeState(addRangeControls);
this.MakePostalCode(addRangeControls);
this.MakeCountry(addRangeControls);
break;
}
var doneButton = new HtmlGenericControl("input");
doneButton.Attributes["class"] = "btn btn-primary btn-block";
doneButton.Attributes["role"] = "button";
doneButton.ID = "popoverUpdateButton_" + Guid.NewGuid().ToString().Trim();
doneButton.Attributes["readonly"] = "true";
doneButton.Attributes.Add("value", ResourceManager.GetString("Composite_Control_Done"));
addRangeControls(new[] { doneButton });
var ariaLabelPattern = "{0}. {1}";
if (this.Metadata.IsRequired || this.Metadata.WebFormForceFieldIsRequired)
{
addressTextBox.Attributes.Add("required", string.Empty);
ariaLabelPattern = "{0}*. {1}";
}
if (this.isEditable)
{
addressTextBox.Attributes.Add("aria-label", string.Format(ariaLabelPattern, this.Metadata.Label, ResourceManager.GetString("Narrator_Label_For_Composite_Controls")));
}
else
{
addressTextBox.CssClass += " readonly ";
}
this.Bindings[this.ControlID] = new CellBinding
{
Get = () =>
{
var str = addressTextBox.Text;
return str ?? string.Empty;
},
Set = obj =>
{
Entity entity = obj as Entity;
foreach (var bindAction in this.bindControlValue)
{
bindAction(entity);
}
var textBoxValue = string.Join("\r\n",
this.addressControlValue.ToString()
.Split(new[] { "{BREAK}" }, StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Trim()));
addressTextBox.Text = textBoxValue;
}
};
}
/// <summary>
/// Instantiates the validators in.
/// </summary>
/// <param name="container">The container.</param>
protected override void InstantiateValidatorsIn(Control container)
{
if (this.Metadata.IsRequired || this.Metadata.WebFormForceFieldIsRequired || this.Metadata.IsFullNameControl)
{
container.Controls.Add(
new RequiredFieldValidator
{
ID = string.Format("RequiredFieldValidator{0}", this.ControlID),
ControlToValidate = this.ControlID,
ValidationGroup = this.ValidationGroup,
Display = this.ValidatorDisplay,
ErrorMessage = ValidationSummaryMarkup(this.ValidationMessage()),
Text = this.Metadata.ValidationText,
});
}
this.InstantiateCustomValidatorsIn(container);
}
/// <summary>
/// Make Field Address Line1
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeAddressLine1(Action<IEnumerable<Control>> addRangeControls)
{
var line1 = this.MakeEditControls("_line1", "Address_Line_1_DefaultText");
addRangeControls(line1);
}
/// <summary>
/// Make Field Address Line2
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeAddressLine2(Action<IEnumerable<Control>> addRangeControls)
{
var line2 = this.MakeEditControls("_line2", "Address_Line_2_DefaultText");
addRangeControls(line2);
}
/// <summary>
/// Make Field Address Line3
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeAddressLine3(Action<IEnumerable<Control>> addRangeControls)
{
var line3 = this.MakeEditControls("_line3", "Address_Line_3_DefaultText");
addRangeControls(line3);
}
/// <summary>
/// Make Field City
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeCity(Action<IEnumerable<Control>> addRangeControls)
{
var city = this.MakeEditControls("_city", "City_DefaultText");
addRangeControls(city);
}
/// <summary>
/// Make Field Country/Region
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeCountry(Action<IEnumerable<Control>> addRangeControls)
{
var country = this.MakeEditControls("_country", "Country_DefaultText");
addRangeControls(country);
}
/// <summary>
/// Make Field Postal Code
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakePostalCode(Action<IEnumerable<Control>> addRangeControls)
{
var postalcode = this.MakeEditControls("_postalcode", "Zip_Postal_Code");
addRangeControls(postalcode);
}
/// <summary>
/// Make Field State
/// </summary>
/// <param name="addRangeControls">Add Corols Delegate</param>
private void MakeState(Action<IEnumerable<Control>> addRangeControls)
{
var stateorprovince = this.MakeEditControls("_stateorprovince", "State_Province_DefaultText");
addRangeControls(stateorprovince);
}
/// <summary>
/// Generatefields the specified field name.
/// </summary>
/// <param name="fieldName">Name of Field.</param>
/// <param name="labelName">Name of Label</param>
/// <returns>Collection with Field and Label controls</returns>
private IEnumerable<Control> MakeEditControls(string fieldName, string labelName)
{
var fieldMetaData = this.entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == this.alias + fieldName);
var controls = new List<Control>();
var textBox = new TextBox
{
ID = string.Concat(this.ControlID, fieldName),
CssClass = string.Concat(" content ", " ", this.CssClass, this.Metadata.CssClass),
ToolTip = this.Metadata.ToolTip
};
var snippetName = "AddressCompositeControlTemplate/FieldLabel/" + labelName;
var fieldLabelSnippet = new WebControls.Snippet
{
SnippetName = snippetName,
DisplayName = snippetName,
EditType = "text",
Editable = true,
DefaultText = ResourceManager.GetString(labelName),
HtmlTag = HtmlTextWriterTag.Label
};
if (this.isEditable)
{
// Applying required parameters to first name if it's application required
if (fieldMetaData != null
&& (fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.ApplicationRequired
|| fieldMetaData.RequiredLevel.Value == AttributeRequiredLevel.SystemRequired))
{
textBox.Attributes.Add("required", string.Empty);
var requierdContainer = new HtmlGenericControl("div");
requierdContainer.Attributes["class"] = "info required";
requierdContainer.Controls.Add(fieldLabelSnippet);
controls.Add(requierdContainer);
}
else
{
controls.Add(fieldLabelSnippet);
}
}
controls.Add(textBox);
textBox.Attributes.Add("onchange", "setIsDirty(this.id);");
this.Bindings[this.ControlID + this.alias + fieldName] = new CellBinding
{
Get = () =>
{
var str = textBox.Text;
return str != null ? str.Replace("\r\n", "\n") : string.Empty;
},
Set = obj =>
{
var entity = obj as Entity;
if (entity != null)
{
textBox.Text =
entity.GetAttributeValue<string>(
this.alias + fieldName);
}
}
};
this.bindControlValue.Add(entity =>
{
this.addressControlValue.Replace("{" + textBox.ID + "}", entity.GetAttributeValue<string>(this.alias + fieldName));
});
return controls;
}
/// <summary>
/// Validation Message
/// </summary>
/// <returns>string Validation Message</returns>
private string ValidationMessage()
{
return string.IsNullOrWhiteSpace(this.Metadata.RequiredFieldValidationErrorMessage)
? (this.Metadata.Messages == null || !this.Metadata.Messages.ContainsKey("Required"))
? ResourceManager.GetString("Required_Field_Error").FormatWith(this.Metadata.Label)
: this.Metadata.Messages["Required"].FormatWith(this.Metadata.Label)
: this.Metadata.RequiredFieldValidationErrorMessage;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.AddImport;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Packaging;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.SymbolSearch;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport.AddImportDiagnosticIds;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.AddImport
{
internal static class AddImportDiagnosticIds
{
/// <summary>
/// name does not exist in context
/// </summary>
public const string CS0103 = nameof(CS0103);
/// <summary>
/// type or namespace could not be found
/// </summary>
public const string CS0246 = nameof(CS0246);
/// <summary>
/// wrong number of type args
/// </summary>
public const string CS0305 = nameof(CS0305);
/// <summary>
/// type does not contain a definition of method or extension method
/// </summary>
public const string CS1061 = nameof(CS1061);
/// <summary>
/// cannot find implementation of query pattern
/// </summary>
public const string CS1935 = nameof(CS1935);
/// <summary>
/// The non-generic type 'A' cannot be used with type arguments
/// </summary>
public const string CS0308 = nameof(CS0308);
/// <summary>
/// 'A' is inaccessible due to its protection level
/// </summary>
public const string CS0122 = nameof(CS0122);
/// <summary>
/// The using alias 'A' cannot be used with type arguments
/// </summary>
public const string CS0307 = nameof(CS0307);
/// <summary>
/// 'A' is not an attribute class
/// </summary>
public const string CS0616 = nameof(CS0616);
/// <summary>
/// No overload for method 'X' takes 'N' arguments
/// </summary>
public const string CS1501 = nameof(CS1501);
/// <summary>
/// cannot convert from 'int' to 'string'
/// </summary>
public const string CS1503 = nameof(CS1503);
/// <summary>
/// XML comment on 'construct' has syntactically incorrect cref attribute 'name'
/// </summary>
public const string CS1574 = nameof(CS1574);
/// <summary>
/// Invalid type for parameter 'parameter number' in XML comment cref attribute
/// </summary>
public const string CS1580 = nameof(CS1580);
/// <summary>
/// Invalid return type in XML comment cref attribute
/// </summary>
public const string CS1581 = nameof(CS1581);
/// <summary>
/// XML comment has syntactically incorrect cref attribute
/// </summary>
public const string CS1584 = nameof(CS1584);
/// <summary>
/// Type 'X' does not contain a valid extension method accepting 'Y'
/// </summary>
public const string CS1929 = nameof(CS1929);
/// <summary>
/// Cannot convert method group 'X' to non-delegate type 'Y'. Did you intend to invoke the method?
/// </summary>
public const string CS0428 = nameof(CS0428);
/// <summary>
/// There is no argument given that corresponds to the required formal parameter 'X' of 'Y'
/// </summary>
public const string CS7036 = nameof(CS7036);
public static ImmutableArray<string> FixableTypeIds =
ImmutableArray.Create(
CS0103,
CS0246,
CS0305,
CS0308,
CS0122,
CS0307,
CS0616,
CS1580,
CS1581);
public static ImmutableArray<string> FixableDiagnosticIds =
FixableTypeIds.Concat(ImmutableArray.Create(
CS1061,
CS1935,
CS1501,
CS1503,
CS1574,
CS1584,
CS1929,
CS0428,
CS7036));
}
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.AddUsingOrImport), Shared]
internal class CSharpAddImportCodeFixProvider : AbstractAddImportCodeFixProvider<SimpleNameSyntax>
{
public override ImmutableArray<string> FixableDiagnosticIds => AddImportDiagnosticIds.FixableDiagnosticIds;
public CSharpAddImportCodeFixProvider()
{
}
/// <summary>For testing purposes only (so that tests can pass in mock values)</summary>
internal CSharpAddImportCodeFixProvider(
IPackageInstallerService installerService,
ISymbolSearchService symbolSearchService)
: base(installerService, symbolSearchService)
{
}
protected override bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return node.CanAddUsingDirectives(cancellationToken);
}
protected override bool CanAddImportForMethod(
Diagnostic diagnostic, ISyntaxFactsService syntaxFacts, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
switch (diagnostic.Id)
{
case CS7036:
case CS0428:
case CS1061:
if (node.IsKind(SyntaxKind.ConditionalAccessExpression))
{
node = (node as ConditionalAccessExpressionSyntax).WhenNotNull;
}
else if (node.IsKind(SyntaxKind.MemberBindingExpression))
{
node = (node as MemberBindingExpressionSyntax).Name;
}
else if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
return true;
}
break;
case CS0122:
case CS1501:
if (node is SimpleNameSyntax)
{
break;
}
else if (node is MemberBindingExpressionSyntax)
{
node = (node as MemberBindingExpressionSyntax).Name;
}
break;
case CS1929:
var memberAccessName = (node.Parent as MemberAccessExpressionSyntax)?.Name;
var conditionalAccessName = (((node.Parent as ConditionalAccessExpressionSyntax)?.WhenNotNull as InvocationExpressionSyntax)?.Expression as MemberBindingExpressionSyntax)?.Name;
if (memberAccessName == null && conditionalAccessName == null)
{
return false;
}
node = memberAccessName ?? conditionalAccessName;
break;
case CS1503:
//// look up its corresponding method name
var parent = node.GetAncestor<InvocationExpressionSyntax>();
if (parent == null)
{
return false;
}
var method = parent.Expression as MemberAccessExpressionSyntax;
if (method != null)
{
node = method.Name;
}
break;
default:
return false;
}
nameNode = node as SimpleNameSyntax;
if (!nameNode.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) &&
!nameNode.IsParentKind(SyntaxKind.MemberBindingExpression))
{
return false;
}
var memberAccess = nameNode.Parent as MemberAccessExpressionSyntax;
var memberBinding = nameNode.Parent as MemberBindingExpressionSyntax;
if (memberAccess.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberAccess.IsParentKind(SyntaxKind.ElementAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.SimpleMemberAccessExpression) ||
memberBinding.IsParentKind(SyntaxKind.ElementAccessExpression))
{
return false;
}
if (!syntaxFacts.IsMemberAccessExpressionName(node))
{
return false;
}
return true;
}
protected override bool CanAddImportForNamespace(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
return false;
}
protected override bool CanAddImportForQuery(Diagnostic diagnostic, SyntaxNode node)
{
if (diagnostic.Id != CS1935)
{
return false;
}
return node.AncestorsAndSelf().Any(n => n is QueryExpressionSyntax && !(n.Parent is QueryContinuationSyntax));
}
protected override bool CanAddImportForType(Diagnostic diagnostic, SyntaxNode node, out SimpleNameSyntax nameNode)
{
nameNode = null;
switch (diagnostic.Id)
{
case CS0103:
case CS0246:
case CS0305:
case CS0308:
case CS0122:
case CS0307:
case CS0616:
case CS1580:
case CS1581:
break;
case CS1574:
case CS1584:
var cref = node as QualifiedCrefSyntax;
if (cref != null)
{
node = cref.Container;
}
break;
default:
return false;
}
return TryFindStandaloneType(node, out nameNode);
}
private static bool TryFindStandaloneType(SyntaxNode node, out SimpleNameSyntax nameNode)
{
var qn = node as QualifiedNameSyntax;
if (qn != null)
{
node = GetLeftMostSimpleName(qn);
}
nameNode = node as SimpleNameSyntax;
return nameNode.LooksLikeStandaloneTypeName();
}
private static SimpleNameSyntax GetLeftMostSimpleName(QualifiedNameSyntax qn)
{
while (qn != null)
{
var left = qn.Left;
var simpleName = left as SimpleNameSyntax;
if (simpleName != null)
{
return simpleName;
}
qn = left as QualifiedNameSyntax;
}
return null;
}
protected override ISet<INamespaceSymbol> GetNamespacesInScope(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
return semanticModel.GetUsingNamespacesInScope(node);
}
protected override ITypeSymbol GetQueryClauseInfo(
SemanticModel semanticModel,
SyntaxNode node,
CancellationToken cancellationToken)
{
var query = node.AncestorsAndSelf().OfType<QueryExpressionSyntax>().First();
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(query.FromClause, cancellationToken)))
{
return null;
}
foreach (var clause in query.Body.Clauses)
{
if (InfoBoundSuccessfully(semanticModel.GetQueryClauseInfo(clause, cancellationToken)))
{
return null;
}
}
if (InfoBoundSuccessfully(semanticModel.GetSymbolInfo(query.Body.SelectOrGroup, cancellationToken)))
{
return null;
}
var fromClause = query.FromClause;
return semanticModel.GetTypeInfo(fromClause.Expression, cancellationToken).Type;
}
private bool InfoBoundSuccessfully(SymbolInfo symbolInfo)
{
return InfoBoundSuccessfully(symbolInfo.Symbol);
}
private bool InfoBoundSuccessfully(QueryClauseInfo semanticInfo)
{
return InfoBoundSuccessfully(semanticInfo.OperationInfo);
}
private static bool InfoBoundSuccessfully(ISymbol operation)
{
operation = operation.GetOriginalUnreducedDefinition();
return operation != null;
}
protected override string GetDescription(IReadOnlyList<string> nameParts)
{
return $"using { string.Join(".", nameParts) };";
}
protected override string GetDescription(
INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, SyntaxNode contextNode, bool checkForExistingUsing)
{
var root = GetCompilationUnitSyntaxNode(contextNode);
// No localization necessary
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return $"extern alias {externAliasString};";
}
string namespaceString;
if (TryGetNamespaceString(namespaceSymbol, root, false, null, checkForExistingUsing, out namespaceString))
{
return $"using {namespaceString};";
}
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, false, null, out staticNamespaceString))
{
return $"using static {staticNamespaceString};";
}
// We can't find a string to show to the user, we should not show this codefix.
return null;
}
protected override async Task<Document> AddImportAsync(
SyntaxNode contextNode,
INamespaceOrTypeSymbol namespaceOrTypeSymbol,
Document document,
bool placeSystemNamespaceFirst,
CancellationToken cancellationToken)
{
var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
var newRoot = await AddImportWorkerAsync(document, root, contextNode, namespaceOrTypeSymbol, placeSystemNamespaceFirst, cancellationToken).ConfigureAwait(false);
return document.WithSyntaxRoot(newRoot);
}
private async Task<CompilationUnitSyntax> AddImportWorkerAsync(
Document document, CompilationUnitSyntax root, SyntaxNode contextNode,
INamespaceOrTypeSymbol namespaceOrTypeSymbol, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var simpleUsingDirective = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: false);
var externAliasUsingDirective = GetExternAliasUsingDirective(root, namespaceOrTypeSymbol, semanticModel);
if (externAliasUsingDirective != null)
{
root = root.AddExterns(
externAliasUsingDirective
.WithAdditionalAnnotations(Formatter.Annotation));
}
if (simpleUsingDirective == null)
{
return root;
}
// Because of the way usings can be nested inside of namespace declarations,
// we need to check if the usings must be fully qualified so as not to be
// ambiguous with the containing namespace.
if (UsingsAreContainedInNamespace(contextNode))
{
// When we add usings we try and place them, as best we can, where the user
// wants them according to their settings. This means we can't just add the fully-
// qualified usings and expect the simplifier to take care of it, the usings have to be
// simplified before we attempt to add them to the document.
// You might be tempted to think that we could call
// AddUsings -> Simplifier -> SortUsings
// But this will clobber the users using settings without asking. Instead we create a new
// Document and check if our using can be simplified. Worst case we need to back out the
// fully qualified change and reapply with the simple name.
var fullyQualifiedUsingDirective = GetUsingDirective(root, namespaceOrTypeSymbol, semanticModel, fullyQualify: true);
var newRoot = root.AddUsingDirective(
fullyQualifiedUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
var newUsing = newRoot
.DescendantNodes().OfType<UsingDirectiveSyntax>()
.Where(uds => uds.IsEquivalentTo(fullyQualifiedUsingDirective, topLevel: true))
.Single();
newRoot = newRoot.TrackNodes(newUsing);
var documentWithSyntaxRoot = document.WithSyntaxRoot(newRoot);
var options = document.Project.Solution.Workspace.Options;
var simplifiedDocument = await Simplifier.ReduceAsync(documentWithSyntaxRoot, newUsing.Span, options, cancellationToken).ConfigureAwait(false);
newRoot = (CompilationUnitSyntax)await simplifiedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var simplifiedUsing = newRoot.GetCurrentNode(newUsing);
if (simplifiedUsing.Name.IsEquivalentTo(newUsing.Name, topLevel: true))
{
// Not fully qualifying the using causes to refer to a different namespace so we need to keep it as is.
return (CompilationUnitSyntax)await documentWithSyntaxRoot.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
// It does not matter if it is fully qualified or simple so lets return the simple name.
return root.AddUsingDirective(
simplifiedUsing.WithoutAnnotations(), contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
}
}
else
{
// simple form
return root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
}
}
protected override Task<Document> AddImportAsync(
SyntaxNode contextNode, IReadOnlyList<string> namespaceParts, Document document, bool placeSystemNamespaceFirst, CancellationToken cancellationToken)
{
var root = GetCompilationUnitSyntaxNode(contextNode, cancellationToken);
// Suppress diagnostics on the import we create. Because we only get here when we are
// adding a nuget package, it is certainly the case that in the preview this will not
// bind properly. It will look silly to show such an error, so we just suppress things.
var simpleUsingDirective = SyntaxFactory.UsingDirective(
CreateNameSyntax(namespaceParts, namespaceParts.Count - 1)).WithAdditionalAnnotations(
SuppressDiagnosticsAnnotation.Create());
// If we have an existing using with this name then don't bother adding this new using.
if (root.Usings.Any(u => u.IsEquivalentTo(simpleUsingDirective, topLevel: false)))
{
return Task.FromResult(document);
}
var newRoot = root.AddUsingDirective(
simpleUsingDirective, contextNode, placeSystemNamespaceFirst,
Formatter.Annotation);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
private NameSyntax CreateNameSyntax(IReadOnlyList<string> namespaceParts, int index)
{
var part = namespaceParts[index];
if (SyntaxFacts.GetKeywordKind(part) != SyntaxKind.None)
{
part = "@" + part;
}
var namePiece = SyntaxFactory.IdentifierName(part);
return index == 0
? (NameSyntax)namePiece
: SyntaxFactory.QualifiedName(CreateNameSyntax(namespaceParts, index - 1), namePiece);
}
private static ExternAliasDirectiveSyntax GetExternAliasUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel)
{
string externAliasString;
if (TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString))
{
return SyntaxFactory.ExternAliasDirective(SyntaxFactory.Identifier(externAliasString));
}
return null;
}
private UsingDirectiveSyntax GetUsingDirective(CompilationUnitSyntax root, INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, bool fullyQualify)
{
if (namespaceSymbol is INamespaceSymbol)
{
string namespaceString;
string externAliasString;
TryGetExternAliasString(namespaceSymbol, semanticModel, root, out externAliasString);
if (externAliasString != null)
{
if (TryGetNamespaceString(namespaceSymbol, root, false, externAliasString,
checkForExistingUsing: true, namespaceString: out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
return null;
}
if (TryGetNamespaceString(namespaceSymbol, root, fullyQualify, null,
checkForExistingUsing: true, namespaceString: out namespaceString))
{
return SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(namespaceString).WithAdditionalAnnotations(Simplifier.Annotation));
}
}
if (namespaceSymbol is ITypeSymbol)
{
string staticNamespaceString;
if (TryGetStaticNamespaceString(namespaceSymbol, root, fullyQualify, null, out staticNamespaceString))
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.Token(SyntaxKind.UsingKeyword),
SyntaxFactory.Token(SyntaxKind.StaticKeyword),
null,
SyntaxFactory.ParseName(staticNamespaceString).WithAdditionalAnnotations(Simplifier.Annotation),
SyntaxFactory.Token(SyntaxKind.SemicolonToken));
}
}
return null;
}
private bool UsingsAreContainedInNamespace(SyntaxNode contextNode)
{
return contextNode.GetAncestor<NamespaceDeclarationSyntax>()?.DescendantNodes().OfType<UsingDirectiveSyntax>().FirstOrDefault() != null;
}
private static bool TryGetExternAliasString(INamespaceOrTypeSymbol namespaceSymbol, SemanticModel semanticModel, CompilationUnitSyntax root, out string externAliasString)
{
externAliasString = null;
var metadataReference = semanticModel.Compilation.GetMetadataReference(namespaceSymbol.ContainingAssembly);
if (metadataReference == null)
{
return false;
}
var aliases = metadataReference.Properties.Aliases;
if (aliases.IsEmpty)
{
return false;
}
aliases = metadataReference.Properties.Aliases.Where(a => a != MetadataReferenceProperties.GlobalAlias).ToImmutableArray();
if (!aliases.Any())
{
return false;
}
externAliasString = aliases.First();
return ShouldAddExternAlias(aliases, root);
}
private static bool TryGetNamespaceString(
INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias,
bool checkForExistingUsing, out string namespaceString)
{
if (namespaceSymbol is ITypeSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return checkForExistingUsing
? ShouldAddUsing(namespaceString, root)
: true;
}
private static bool TryGetStaticNamespaceString(INamespaceOrTypeSymbol namespaceSymbol, CompilationUnitSyntax root, bool fullyQualify, string alias, out string namespaceString)
{
if (namespaceSymbol is INamespaceSymbol)
{
namespaceString = null;
return false;
}
namespaceString = fullyQualify
? namespaceSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)
: namespaceSymbol.ToDisplayString();
if (alias != null)
{
namespaceString = alias + "::" + namespaceString;
}
return ShouldAddStaticUsing(namespaceString, root);
}
private static bool ShouldAddExternAlias(ImmutableArray<string> aliases, CompilationUnitSyntax root)
{
var identifiers = root.DescendantNodes().OfType<ExternAliasDirectiveSyntax>().Select(e => e.Identifier.ToString());
var externAliases = aliases.Where(a => identifiers.Contains(a));
return !externAliases.Any();
}
private static bool ShouldAddUsing(string usingDirective, CompilationUnitSyntax root)
{
var simpleUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.None));
return !simpleUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static bool ShouldAddStaticUsing(string usingDirective, CompilationUnitSyntax root)
{
var staticUsings = root.Usings.Where(u => u.StaticKeyword.IsKind(SyntaxKind.StaticKeyword));
return !staticUsings.Any(u => u.Name.ToString() == usingDirective);
}
private static CompilationUnitSyntax GetCompilationUnitSyntaxNode(SyntaxNode contextNode, CancellationToken cancellationToken = default(CancellationToken))
{
return (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
}
protected override bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken)
{
var leftExpression = syntaxFacts.GetExpressionOfMemberAccessExpression(expression);
if (leftExpression == null)
{
if (expression.IsKind(SyntaxKind.CollectionInitializerExpression))
{
leftExpression = expression.GetAncestor<ObjectCreationExpressionSyntax>();
}
else
{
return false;
}
}
var semanticInfo = semanticModel.GetTypeInfo(leftExpression, cancellationToken);
var leftExpressionType = semanticInfo.Type;
return IsViableExtensionMethod(method, leftExpressionType);
}
internal override bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel)
{
if (node.Parent.IsKind(SyntaxKind.CollectionInitializerExpression))
{
var objectCreationExpressionSyntax = node.GetAncestor<ObjectCreationExpressionSyntax>();
if (objectCreationExpressionSyntax == null)
{
return false;
}
return true;
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using VersionOne.ServiceHost.ConfigurationTool.BZ;
using VersionOne.ServiceHost.ConfigurationTool.Entities;
using VersionOne.ServiceHost.ConfigurationTool.UI.Interfaces;
namespace VersionOne.ServiceHost.ConfigurationTool.UI.Controls {
public partial class QCPageControl : BasePageControl<QCServiceEntity>, IQualityCenterPageView {
public event EventHandler ValidationRequested;
public QCPageControl() {
InitializeComponent();
grdDefectFilters.AutoGenerateColumns = false;
grdQCProjects.AutoGenerateColumns = false;
grdPriorityMappings.AutoGenerateColumns = false;
btnValidate.Click += btnValidate_Click;
btnQCProjectsDelete.Click += btnQCProjectsDelete_Click;
btnFiltersDelete.Click += btnFiltersDelete_Click;
btnDeletePriorityMapping.Click += btnDeletePriorityMapping_Click;
grdQCProjects.DataError += grdQCProjects_DataError;
grdQCProjects.CellValidating += grdQCProjects_CellValidating;
grdQCProjects.UserDeletingRow += delegate(object sender, DataGridViewRowCancelEventArgs e) {
e.Cancel = !ConfirmDelete();
};
grdDefectFilters.UserDeletingRow += delegate(object sender, DataGridViewRowCancelEventArgs e) {
e.Cancel = !ConfirmDelete();
};
grdPriorityMappings.UserDeletingRow += delegate(object sender, DataGridViewRowCancelEventArgs e) {
e.Cancel = !ConfirmDelete();
};
grdPriorityMappings.DataError += grdPriorityMappings_DataError;
AddValidationProvider(typeof(QCConnection));
// TODO handle unique project ID validation manually?
AddGridValidationProvider(typeof(QCProject), grdQCProjects);
AddGridValidationProvider(typeof(QCDefectFilter), grdDefectFilters);
AddGridValidationProvider(typeof(QCPriorityMapping), grdPriorityMappings);
AddControlTextValidation<QCConnection>(txtUrl, QCConnection.ApplicationUrlProperty);
AddControlTextValidation<QCConnection>(txtUsername, QCConnection.UsernameProperty);
AddControlTextValidation<QCServiceEntity>(txtCreateStatusValue, QCServiceEntity.CreateStatusValueProperty);
AddControlTextValidation<QCServiceEntity>(txtCloseStatusValue, QCServiceEntity.CloseStatusValueProperty);
AddControlTextValidation<QCServiceEntity>(cboSourceFieldValue, QCServiceEntity.SourceFieldValueProperty);
AddTabHighlightingSupport(tcData);
}
public override void DataBind() {
AddControlBinding(chkDisabled, Model, BaseEntity.DisabledProperty);
AddControlBinding(txtUrl, Model.Connection, QCConnection.ApplicationUrlProperty);
AddControlBinding(txtUsername, Model.Connection, QCConnection.UsernameProperty);
AddControlBinding(txtPassword, Model.Connection, QCConnection.PasswordProperty);
AddControlBinding(nmdInterval, Model.Timer, TimerEntity.TimerProperty);
AddSimpleComboboxBinding(cboSourceFieldValue, Model, QCServiceEntity.SourceFieldValueProperty);
AddControlBinding(txtCreateStatusValue, Model, QCServiceEntity.CreateStatusValueProperty);
AddControlBinding(txtCloseStatusValue, Model, QCServiceEntity.CloseStatusValueProperty);
FillComboBoxWithStrings(cboSourceFieldValue, SourceList);
BindProjectMappingsGrid();
BimdPriorityMappingsGrid();
BindDefectFiltersGrid();
BindHelpStrings();
InvokeValidationTriggered();
}
private void BindDefectFiltersGrid() {
bsDefectFilters.DataSource = Model.DefectFilters;
grdDefectFilters.DataSource = bsDefectFilters;
}
private void BimdPriorityMappingsGrid() {
BindVersionOnePriorityColumn();
bsPriorities.DataSource = Model.PriorityMappings;
grdPriorityMappings.DataSource = bsPriorities;
}
private void BindProjectMappingsGrid() {
BindProjectColumn();
bsQCProjects.DataSource = Model.Projects;
grdQCProjects.DataSource = bsQCProjects;
}
private void BindHelpStrings() {
AddHelpSupport(chkDisabled, Model, BaseEntity.DisabledProperty);
AddHelpSupport(grdDefectFilters, Model, QCServiceEntity.DefectFiltersProperty);
AddHelpSupport(txtCreateStatusValue, Model, QCServiceEntity.CreateStatusValueProperty);
AddHelpSupport(txtCloseStatusValue, Model, QCServiceEntity.CloseStatusValueProperty);
AddHelpSupport(cboSourceFieldValue, Model, QCServiceEntity.SourceFieldValueProperty);
AddHelpSupport(grdQCProjects, Model, QCServiceEntity.ProjectMappingsProperty);
AddHelpSupport(grdPriorityMappings, Model, QCServiceEntity.PriorityMappingsProperty);
AddHelpSupport(lblMin, Model.Timer, TimerEntity.TimerProperty);
}
private void BindVersionOnePriorityColumn() {
colVersionOnePriority.DisplayMember = ListValue.NameProperty;
colVersionOnePriority.ValueMember = ListValue.ValueProperty;
colVersionOnePriority.DataSource = VersionOnePriorities;
}
private void BindProjectColumn() {
colV1Project.Items.Clear();
foreach(string project in ProjectList) {
colV1Project.Items.Add(project);
}
}
private void btnValidate_Click(object sender, EventArgs e) {
if(ValidationRequested != null) {
ValidationRequested(this, EventArgs.Empty);
}
}
private void btnQCProjectsDelete_Click(object sender, EventArgs e) {
if(grdQCProjects.SelectedRows.Count != 0 && ConfirmDelete()) {
bsQCProjects.Remove(grdQCProjects.SelectedRows[0].DataBoundItem);
}
}
private void btnFiltersDelete_Click(object sender, EventArgs e) {
if(grdDefectFilters.SelectedRows.Count != 0 && ConfirmDelete()) {
bsDefectFilters.Remove(grdDefectFilters.SelectedRows[0].DataBoundItem);
}
}
private void btnDeletePriorityMapping_Click(object sender, EventArgs e) {
if(grdPriorityMappings.SelectedRows.Count > 0 && ConfirmDelete()) {
bsPriorities.Remove(grdPriorityMappings.SelectedRows[0].DataBoundItem);
}
}
private void grdQCProjects_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) {
if(e.ColumnIndex != 0) {
return;
}
var currentRow = grdQCProjects.Rows[e.RowIndex];
currentRow.ErrorText = string.Empty;
var idValue = currentRow.Cells[0].EditedFormattedValue as string;
var project = (QCProject)currentRow.DataBoundItem;
var duplicateIdItemsList = Model.Projects.FindAll(
item => string.Equals(idValue, item.Id) && !item.Equals(project));
if(duplicateIdItemsList.Count > 0) {
currentRow.ErrorText = "Project ID should be unique";
}
}
private void grdQCProjects_DataError(object sender, DataGridViewDataErrorEventArgs e) {
if(ProjectList != null && ProjectList.Count != 0) {
grdQCProjects.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ProjectList[0];
}
e.ThrowException = false;
}
private void grdPriorityMappings_DataError(object sender, DataGridViewDataErrorEventArgs e) {
if(VersionOnePriorities != null && VersionOnePriorities.Count > 0) {
grdPriorityMappings.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = VersionOnePriorities[0];
}
}
public IList<string> ProjectList { get; set; }
public IList<ListValue> VersionOnePriorities { get; set; }
public IList<string> SourceList { get; set; }
public void SetGeneralTabValid(bool isValid) {
TabHighlighter.SetTabPageValidationMark(tpSettings, isValid);
}
public void SetMappingTabValid(bool isValid) {
TabHighlighter.SetTabPageValidationMark(tpMappings, isValid);
}
public void SetValidationResult(bool isSuccessful) {
lblValidationResult.Visible = true;
if(isSuccessful) {
lblValidationResult.ForeColor = Color.Green;
lblValidationResult.Text = Resources.ConnectionValidMessage;
} else {
lblValidationResult.ForeColor = Color.Red;
lblValidationResult.Text = Resources.ConnectionInvalidMessage;
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Common
{
using JetBrains.Annotations;
using System;
using System.ComponentModel;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
using NLog.Internal;
using NLog.Time;
#if !SILVERLIGHT
using ConfigurationManager = System.Configuration.ConfigurationManager;
using System.Diagnostics;
#endif
/// <summary>
/// NLog internal logger.
/// </summary>
public static class InternalLogger
{
private static object lockObject = new object();
private static string _logFile;
/// <summary>
/// Initializes static members of the InternalLogger class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static InternalLogger()
{
#if !SILVERLIGHT
LogToConsole = GetSetting("nlog.internalLogToConsole", "NLOG_INTERNAL_LOG_TO_CONSOLE", false);
LogToConsoleError = GetSetting("nlog.internalLogToConsoleError", "NLOG_INTERNAL_LOG_TO_CONSOLE_ERROR", false);
LogLevel = GetSetting("nlog.internalLogLevel", "NLOG_INTERNAL_LOG_LEVEL", LogLevel.Info);
LogFile = GetSetting("nlog.internalLogFile", "NLOG_INTERNAL_LOG_FILE", string.Empty);
Info("NLog internal logger initialized.");
#else
LogLevel = LogLevel.Info;
#endif
IncludeTimestamp = true;
}
/// <summary>
/// Gets or sets the internal log level.
/// </summary>
public static LogLevel LogLevel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console output stream.
/// </summary>
public static bool LogToConsole { get; set; }
/// <summary>
/// Gets or sets a value indicating whether internal messages should be written to the console error stream.
/// </summary>
public static bool LogToConsoleError { get; set; }
/// <summary>
/// Gets or sets the file path of the internal log file.
/// </summary>
/// <remarks>A value of <see langword="null" /> value disables internal logging to a file.</remarks>
public static string LogFile
{
get
{
return _logFile;
}
set
{
_logFile = value;
#if !SILVERLIGHT
if (!string.IsNullOrEmpty(_logFile))
{
CreateDirectoriesIfNeeded(_logFile);
}
#endif
}
}
/// <summary>
/// Gets or sets the text writer that will receive internal logs.
/// </summary>
public static TextWriter LogWriter { get; set; }
/// <summary>
/// Gets or sets a value indicating whether timestamp should be included in internal log output.
/// </summary>
public static bool IncludeTimestamp { get; set; }
/// <summary>
/// Gets a value indicating whether internal log includes Trace messages.
/// </summary>
public static bool IsTraceEnabled
{
get { return LogLevel.Trace >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Debug messages.
/// </summary>
public static bool IsDebugEnabled
{
get { return LogLevel.Debug >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Info messages.
/// </summary>
public static bool IsInfoEnabled
{
get { return LogLevel.Info >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Warn messages.
/// </summary>
public static bool IsWarnEnabled
{
get { return LogLevel.Warn >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Error messages.
/// </summary>
public static bool IsErrorEnabled
{
get { return LogLevel.Error >= LogLevel; }
}
/// <summary>
/// Gets a value indicating whether internal log includes Fatal messages.
/// </summary>
public static bool IsFatalEnabled
{
get { return LogLevel.Fatal >= LogLevel; }
}
/// <summary>
/// Logs the specified message at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Log(LogLevel level, string message, params object[] args)
{
Write(level, message, args);
}
/// <summary>
/// Logs the specified message at the specified level.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="message">Log message.</param>
public static void Log(LogLevel level, [Localizable(false)] string message)
{
Write(level, message, null);
}
/// <summary>
/// Logs the specified message at the Trace level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Trace([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Trace, message, args);
}
/// <summary>
/// Logs the specified message at the Trace level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Trace([Localizable(false)] string message)
{
Write(LogLevel.Trace, message, null);
}
/// <summary>
/// Logs the specified message at the Debug level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Debug([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Debug, message, args);
}
/// <summary>
/// Logs the specified message at the Debug level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Debug([Localizable(false)] string message)
{
Write(LogLevel.Debug, message, null);
}
/// <summary>
/// Logs the specified message at the Info level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Info([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Info, message, args);
}
/// <summary>
/// Logs the specified message at the Info level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Info([Localizable(false)] string message)
{
Write(LogLevel.Info, message, null);
}
/// <summary>
/// Logs the specified message at the Warn level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Warn([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Warn, message, args);
}
/// <summary>
/// Logs the specified message at the Warn level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Warn([Localizable(false)] string message)
{
Write(LogLevel.Warn, message, null);
}
/// <summary>
/// Logs the specified message at the Error level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Error([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Error, message, args);
}
/// <summary>
/// Logs the specified message at the Error level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Error([Localizable(false)] string message)
{
Write(LogLevel.Error, message, null);
}
/// <summary>
/// Logs the specified message at the Fatal level.
/// </summary>
/// <param name="message">Message which may include positional parameters.</param>
/// <param name="args">Arguments to the message.</param>
[StringFormatMethod("message")]
public static void Fatal([Localizable(false)] string message, params object[] args)
{
Write(LogLevel.Fatal, message, args);
}
/// <summary>
/// Logs the specified message at the Fatal level.
/// </summary>
/// <param name="message">Log message.</param>
public static void Fatal([Localizable(false)] string message)
{
Write(LogLevel.Fatal, message, null);
}
private static void Write(LogLevel level, string message, object[] args)
{
if (level < LogLevel)
{
return;
}
if (string.IsNullOrEmpty(LogFile) && !LogToConsole && !LogToConsoleError && LogWriter == null)
{
return;
}
try
{
string formattedMessage = message;
if (args != null)
{
formattedMessage = string.Format(CultureInfo.InvariantCulture, message, args);
}
var builder = new StringBuilder(message.Length + 32);
if (IncludeTimestamp)
{
builder.Append(TimeSource.Current.Time.ToString("yyyy-MM-dd HH:mm:ss.ffff", CultureInfo.InvariantCulture));
builder.Append(" ");
}
builder.Append(level.ToString());
builder.Append(" ");
builder.Append(formattedMessage);
string msg = builder.ToString();
// log to file
var logFile = LogFile;
if (!string.IsNullOrEmpty(logFile))
{
using (var textWriter = File.AppendText(logFile))
{
textWriter.WriteLine(msg);
}
}
// log to LogWriter
var writer = LogWriter;
if (writer != null)
{
lock (lockObject)
{
writer.WriteLine(msg);
}
}
// log to console
if (LogToConsole)
{
Console.WriteLine(msg);
}
// log to console error
if (LogToConsoleError)
{
Console.Error.WriteLine(msg);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
// we have no place to log the message to so we ignore it
}
}
/// <summary>
/// Logs the assembly version and file version of the given Assembly.
/// </summary>
/// <param name="assembly">The assembly to log.</param>
public static void LogAssemblyVersion(Assembly assembly)
{
try
{
#if SILVERLIGHT
Info(assembly.FullName);
#else
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
Info("{0}. File version: {1}. Product version: {2}.",
assembly.FullName,
fileVersionInfo.FileVersion,
fileVersionInfo.ProductVersion);
#endif
}
catch (Exception exc)
{
Error("Error logging version of assembly {0}: {1}.", assembly.FullName, exc.Message);
}
}
#if !SILVERLIGHT
private static string GetSettingString(string configName, string envName)
{
string settingValue = ConfigurationManager.AppSettings[configName];
if (settingValue == null)
{
try
{
settingValue = Environment.GetEnvironmentVariable(envName);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
}
}
return settingValue;
}
private static LogLevel GetSetting(string configName, string envName, LogLevel defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return LogLevel.FromString(value);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
return defaultValue;
}
}
private static T GetSetting<T>(string configName, string envName, T defaultValue)
{
string value = GetSettingString(configName, envName);
if (value == null)
{
return defaultValue;
}
try
{
return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
return defaultValue;
}
}
private static void CreateDirectoriesIfNeeded(string filename)
{
try
{
string parentDirectory = Path.GetDirectoryName(filename);
if (!string.IsNullOrEmpty(parentDirectory))
{
Directory.CreateDirectory(parentDirectory);
}
}
catch (Exception exception)
{
Error("Cannot create needed directories to {0}. {1}", filename, exception.Message);
if (exception.MustBeRethrown())
{
throw;
}
}
}
#endif
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using Orleans.CodeGeneration;
using Orleans.Serialization;
namespace Orleans.Runtime
{
/// <summary>
/// This is the base class for all typed grain references.
/// </summary>
[Serializable]
public class GrainReference : IAddressable, IEquatable<GrainReference>, ISerializable
{
private static readonly Action<Message, TaskCompletionSource<object>> ResponseCallbackDelegate = ResponseCallback;
private readonly string genericArguments;
private readonly GuidId observerId;
[NonSerialized]
private static readonly Logger logger = LogManager.GetLogger("GrainReference", LoggerType.Runtime);
[NonSerialized]
private static ConcurrentDictionary<int, string> debugContexts = new ConcurrentDictionary<int, string>();
[NonSerialized] private const bool USE_DEBUG_CONTEXT = true;
[NonSerialized] private const bool USE_DEBUG_CONTEXT_PARAMS = false;
[NonSerialized]
private readonly bool isUnordered = false;
internal bool IsSystemTarget { get { return GrainId.IsSystemTarget; } }
internal bool IsObserverReference { get { return GrainId.IsClient; } }
internal GuidId ObserverId { get { return observerId; } }
private bool HasGenericArgument { get { return !String.IsNullOrEmpty(genericArguments); } }
internal GrainId GrainId { get; private set; }
/// <summary>
/// Called from generated code.
/// </summary>
protected internal readonly SiloAddress SystemTargetSilo;
/// <summary>
/// Whether the runtime environment for system targets has been initialized yet.
/// Called from generated code.
/// </summary>
protected internal bool IsInitializedSystemTarget { get { return SystemTargetSilo != null; } }
internal bool IsUnordered { get { return isUnordered; } }
#region Constructors
/// <summary>Constructs a reference to the grain with the specified Id.</summary>
/// <param name="grainId">The Id of the grain to refer to.</param>
/// <param name="genericArgument">Type arguments in case of a generic grain.</param>
/// <param name="systemTargetSilo">Target silo in case of a system target reference.</param>
/// <param name="observerId">Observer ID in case of an observer reference.</param>
private GrainReference(GrainId grainId, string genericArgument, SiloAddress systemTargetSilo, GuidId observerId)
{
GrainId = grainId;
genericArguments = genericArgument;
SystemTargetSilo = systemTargetSilo;
this.observerId = observerId;
if (String.IsNullOrEmpty(genericArgument))
{
genericArguments = null; // always keep it null instead of empty.
}
// SystemTarget checks
if (grainId.IsSystemTarget && systemTargetSilo==null)
{
throw new ArgumentNullException("systemTargetSilo", String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, but passing null systemTargetSilo.", grainId));
}
if (grainId.IsSystemTarget && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsSystemTarget && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for SystemTarget grain id {0}, and also passing non-null observerId {1}.", grainId, observerId), "genericArgument");
}
if (!grainId.IsSystemTarget && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for non-SystemTarget grain id {0}, but passing a non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "systemTargetSilo");
}
// ObserverId checks
if (grainId.IsClient && observerId == null)
{
throw new ArgumentNullException("observerId", String.Format("Trying to create a GrainReference for Observer with Client grain id {0}, but passing null observerId.", grainId));
}
if (grainId.IsClient && genericArguments != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null genericArguments {1}.", grainId, genericArguments), "genericArgument");
}
if (grainId.IsClient && systemTargetSilo != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference for Client grain id {0}, and also passing non-null systemTargetSilo {1}.", grainId, systemTargetSilo), "genericArgument");
}
if (!grainId.IsClient && observerId != null)
{
throw new ArgumentException(String.Format("Trying to create a GrainReference with non null Observer {0}, but non Client grain id {1}.", observerId, grainId), "observerId");
}
isUnordered = GetUnordered();
}
/// <summary>
/// Constructs a copy of a grain reference.
/// </summary>
/// <param name="other">The reference to copy.</param>
protected GrainReference(GrainReference other)
: this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId) { }
#endregion
#region Instance creator factory functions
/// <summary>Constructs a reference to the grain with the specified ID.</summary>
/// <param name="grainId">The ID of the grain to refer to.</param>
/// <param name="genericArguments">Type arguments in case of a generic grain.</param>
/// <param name="systemTargetSilo">Target silo in case of a system target reference.</param>
internal static GrainReference FromGrainId(GrainId grainId, string genericArguments = null, SiloAddress systemTargetSilo = null)
{
return new GrainReference(grainId, genericArguments, systemTargetSilo, null);
}
internal static GrainReference NewObserverGrainReference(GrainId grainId, GuidId observerId)
{
return new GrainReference(grainId, null, null, observerId);
}
#endregion
/// <summary>
/// Tests this reference for equality to another object.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="obj">The object to test for equality against this reference.</param>
/// <returns><c>true</c> if the object is equal to this reference.</returns>
public override bool Equals(object obj)
{
return Equals(obj as GrainReference);
}
public bool Equals(GrainReference other)
{
if (other == null)
return false;
if (genericArguments != other.genericArguments)
return false;
if (!GrainId.Equals(other.GrainId))
{
return false;
}
if (IsSystemTarget)
{
return Equals(SystemTargetSilo, other.SystemTargetSilo);
}
if (IsObserverReference)
{
return observerId.Equals(other.observerId);
}
return true;
}
/// <summary> Calculates a hash code for a grain reference. </summary>
public override int GetHashCode()
{
int hash = GrainId.GetHashCode();
if (IsSystemTarget)
{
hash = hash ^ SystemTargetSilo.GetHashCode();
}
if (IsObserverReference)
{
hash = hash ^ observerId.GetHashCode();
}
return hash;
}
/// <summary>Get a uniform hash code for this grain reference.</summary>
public uint GetUniformHashCode()
{
// GrainId already includes the hashed type code for generic arguments.
return GrainId.GetUniformHashCode();
}
/// <summary>
/// Compares two references for equality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>true</c> if both grain references refer to the same grain (by grain identifier).</returns>
public static bool operator ==(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) == null;
return reference1.Equals(reference2);
}
/// <summary>
/// Compares two references for inequality.
/// Two grain references are equal if they both refer to the same grain.
/// </summary>
/// <param name="reference1">First grain reference to compare.</param>
/// <param name="reference2">Second grain reference to compare.</param>
/// <returns><c>false</c> if both grain references are resolved to the same grain (by grain identifier).</returns>
public static bool operator !=(GrainReference reference1, GrainReference reference2)
{
if (((object)reference1) == null)
return ((object)reference2) != null;
return !reference1.Equals(reference2);
}
#region Protected members
/// <summary>
/// Implemented by generated subclasses to return a constant
/// Implemented in generated code.
/// </summary>
protected virtual int InterfaceId
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Implemented in generated code.
/// </summary>
public virtual bool IsCompatible(int interfaceId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Return the name of the interface for this GrainReference.
/// Implemented in Orleans generated code.
/// </summary>
public virtual string InterfaceName
{
get
{
throw new InvalidOperationException("Should be overridden by subclass");
}
}
/// <summary>
/// Return the method name associated with the specified interfaceId and methodId values.
/// </summary>
/// <param name="interfaceId">Interface Id</param>
/// <param name="methodId">Method Id</param>
/// <returns>Method name string.</returns>
protected virtual string GetMethodName(int interfaceId, int methodId)
{
throw new InvalidOperationException("Should be overridden by subclass");
}
/// <summary>
/// Called from generated code.
/// </summary>
protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
Task<object> resultTask = InvokeMethodAsync<object>(methodId, arguments, options | InvokeMethodOptions.OneWay);
if (!resultTask.IsCompleted && resultTask.Result != null)
{
throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null.");
}
}
/// <summary>
/// Called from generated code.
/// </summary>
protected Task<T> InvokeMethodAsync<T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null)
{
object[] argsDeepCopy = null;
if (arguments != null)
{
CheckForGrainArguments(arguments);
SetGrainCancellationTokensTarget(arguments, this);
argsDeepCopy = (object[])SerializationManager.DeepCopy(arguments);
}
var request = new InvokeMethodRequest(this.InterfaceId, methodId, argsDeepCopy);
if (IsUnordered)
options |= InvokeMethodOptions.Unordered;
Task<object> resultTask = InvokeMethod_Impl(request, null, options);
if (resultTask == null)
{
if (typeof(T) == typeof(object))
{
// optimize for most common case when using one way calls.
return PublicOrleansTaskExtensions.CompletedTask as Task<T>;
}
return Task.FromResult(default(T));
}
resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask);
return resultTask.Unbox<T>();
}
#endregion
#region Private members
private Task<object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options)
{
if (debugContext == null && USE_DEBUG_CONTEXT)
{
if (USE_DEBUG_CONTEXT_PARAMS)
{
#pragma warning disable 162
// This is normally unreachable code, but kept for debugging purposes
debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments);
#pragma warning restore 162
}
else
{
var hash = InterfaceId ^ request.MethodId;
if (!debugContexts.TryGetValue(hash, out debugContext))
{
debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments);
debugContexts[hash] = debugContext;
}
}
}
// Call any registered client pre-call interceptor function.
CallClientInvokeCallback(request);
bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0);
var resolver = isOneWayCall ? null : new TaskCompletionSource<object>();
RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallbackDelegate, debugContext, options, genericArguments);
return isOneWayCall ? null : resolver.Task;
}
private void CallClientInvokeCallback(InvokeMethodRequest request)
{
// Make callback to any registered client callback function, allowing opportunity for an application to set any additional RequestContext info, etc.
// Should we set some kind of callback-in-progress flag to detect and prevent any inappropriate callback loops on this GrainReference?
try
{
Action<InvokeMethodRequest, IGrain> callback = GrainClient.ClientInvokeCallback; // Take copy to avoid potential race conditions
if (callback == null) return;
// Call ClientInvokeCallback only for grain calls, not for system targets.
if (this is IGrain)
{
callback(request, (IGrain) this);
}
}
catch (Exception exc)
{
logger.Warn(ErrorCode.ProxyClient_ClientInvokeCallback_Error,
"Error while invoking ClientInvokeCallback function " + GrainClient.ClientInvokeCallback,
exc);
throw;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static void ResponseCallback(Message message, TaskCompletionSource<object> context)
{
Response response;
if (message.Result != Message.ResponseTypes.Rejection)
{
try
{
response = (Response)message.BodyObject;
}
catch (Exception exc)
{
// catch the Deserialize exception and break the promise with it.
response = Response.ExceptionResponse(exc);
}
}
else
{
Exception rejection;
switch (message.RejectionType)
{
case Message.RejectionTypes.GatewayTooBusy:
rejection = new GatewayTooBusyException();
break;
case Message.RejectionTypes.DuplicateRequest:
return; // Ignore duplicates
default:
rejection = message.BodyObject as OrleansException;
if (rejection == null)
{
if (string.IsNullOrEmpty(message.RejectionInfo))
{
message.RejectionInfo = "Unable to send request - no rejection info available";
}
rejection = new OrleansException(message.RejectionInfo);
}
break;
}
response = Response.ExceptionResponse(rejection);
}
if (!response.ExceptionFlag)
{
context.TrySetResult(response.Data);
}
else
{
context.TrySetException(response.Exception);
}
}
private bool GetUnordered()
{
if (RuntimeClient.Current == null) return false;
return RuntimeClient.Current.GrainTypeResolver != null && RuntimeClient.Current.GrainTypeResolver.IsUnordered(GrainId.GetTypeCode());
}
#endregion
private static String GetDebugContext(string interfaceName, string methodName, object[] arguments)
{
// String concatenation is approx 35% faster than string.Format here
//debugContext = String.Format("{0}:{1}()", this.InterfaceName, GetMethodName(this.InterfaceId, methodId));
var debugContext = new StringBuilder();
debugContext.Append(interfaceName);
debugContext.Append(":");
debugContext.Append(methodName);
if (USE_DEBUG_CONTEXT_PARAMS && arguments != null && arguments.Length > 0)
{
debugContext.Append("(");
debugContext.Append(Utils.EnumerableToString(arguments));
debugContext.Append(")");
}
else
{
debugContext.Append("()");
}
return debugContext.ToString();
}
private static void CheckForGrainArguments(object[] arguments)
{
foreach (var argument in arguments)
if (argument is Grain)
throw new ArgumentException(String.Format("Cannot pass a grain object {0} as an argument to a method. Pass this.AsReference<GrainInterface>() instead.", argument.GetType().FullName));
}
/// <summary>
/// Sets target grain to the found instances of type GrainCancellationToken
/// </summary>
/// <param name="arguments"> Grain method arguments list</param>
/// <param name="target"> Target grain reference</param>
private static void SetGrainCancellationTokensTarget(object[] arguments, GrainReference target)
{
if (arguments == null) return;
foreach (var argument in arguments)
{
(argument as GrainCancellationToken)?.AddGrainReference(target);
}
}
/// <summary> Serializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[SerializerMethod]
protected internal static void SerializeGrainReference(object obj, ISerializationContext context, Type expected)
{
var writer = context.StreamWriter;
var input = (GrainReference)obj;
writer.Write(input.GrainId);
if (input.IsSystemTarget)
{
writer.Write((byte)1);
writer.Write(input.SystemTargetSilo);
}
else
{
writer.Write((byte)0);
}
if (input.IsObserverReference)
{
input.observerId.SerializeToStream(writer);
}
// store as null, serialize as empty.
var genericArg = String.Empty;
if (input.HasGenericArgument)
genericArg = input.genericArguments;
writer.Write(genericArg);
}
/// <summary> Deserializer function for grain reference.</summary>
/// <seealso cref="SerializationManager"/>
[DeserializerMethod]
protected internal static object DeserializeGrainReference(Type t, IDeserializationContext context)
{
var reader = context.StreamReader;
GrainId id = reader.ReadGrainId();
SiloAddress silo = null;
GuidId observerId = null;
byte siloAddressPresent = reader.ReadByte();
if (siloAddressPresent != 0)
{
silo = reader.ReadSiloAddress();
}
bool expectObserverId = id.IsClient;
if (expectObserverId)
{
observerId = GuidId.DeserializeFromStream(reader);
}
// store as null, serialize as empty.
var genericArg = reader.ReadString();
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
if (expectObserverId)
{
return NewObserverGrainReference(id, observerId);
}
return FromGrainId(id, genericArg, silo);
}
/// <summary> Copier function for grain reference. </summary>
/// <seealso cref="SerializationManager"/>
[CopierMethod]
protected internal static object CopyGrainReference(object original, ICopyContext context)
{
return (GrainReference)original;
}
private const string GRAIN_REFERENCE_STR = "GrainReference";
private const string SYSTEM_TARGET_STR = "SystemTarget";
private const string OBSERVER_ID_STR = "ObserverId";
private const string GENERIC_ARGUMENTS_STR = "GenericArguments";
/// <summary>Returns a string representation of this reference.</summary>
public override string ToString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId, SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId, observerId);
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId,
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
internal string ToDetailedString()
{
if (IsSystemTarget)
{
return String.Format("{0}:{1}/{2}", SYSTEM_TARGET_STR, GrainId.ToDetailedString(), SystemTargetSilo);
}
if (IsObserverReference)
{
return String.Format("{0}:{1}/{2}", OBSERVER_ID_STR, GrainId.ToDetailedString(), observerId.ToDetailedString());
}
return String.Format("{0}:{1}{2}", GRAIN_REFERENCE_STR, GrainId.ToDetailedString(),
!HasGenericArgument ? String.Empty : String.Format("<{0}>", genericArguments));
}
/// <summary> Get the key value for this grain, as a string. </summary>
public string ToKeyString()
{
if (IsObserverReference)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), OBSERVER_ID_STR, observerId.ToParsableString());
}
if (IsSystemTarget)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), SYSTEM_TARGET_STR, SystemTargetSilo.ToParsableString());
}
if (HasGenericArgument)
{
return String.Format("{0}={1} {2}={3}", GRAIN_REFERENCE_STR, GrainId.ToParsableString(), GENERIC_ARGUMENTS_STR, genericArguments);
}
return String.Format("{0}={1}", GRAIN_REFERENCE_STR, GrainId.ToParsableString());
}
public static GrainReference FromKeyString(string key)
{
if (string.IsNullOrWhiteSpace(key)) throw new ArgumentNullException("key", "GrainReference.FromKeyString cannot parse null key");
string trimmed = key.Trim();
string grainIdStr;
int grainIdIndex = (GRAIN_REFERENCE_STR + "=").Length;
int genericIndex = trimmed.IndexOf(GENERIC_ARGUMENTS_STR + "=", StringComparison.Ordinal);
int observerIndex = trimmed.IndexOf(OBSERVER_ID_STR + "=", StringComparison.Ordinal);
int systemTargetIndex = trimmed.IndexOf(SYSTEM_TARGET_STR + "=", StringComparison.Ordinal);
if (genericIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, genericIndex - grainIdIndex).Trim();
string genericStr = trimmed.Substring(genericIndex + (GENERIC_ARGUMENTS_STR + "=").Length);
if (String.IsNullOrEmpty(genericStr))
{
genericStr = null;
}
return FromGrainId(GrainId.FromParsableString(grainIdStr), genericStr);
}
else if (observerIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, observerIndex - grainIdIndex).Trim();
string observerIdStr = trimmed.Substring(observerIndex + (OBSERVER_ID_STR + "=").Length);
GuidId observerId = GuidId.FromParsableString(observerIdStr);
return NewObserverGrainReference(GrainId.FromParsableString(grainIdStr), observerId);
}
else if (systemTargetIndex >= 0)
{
grainIdStr = trimmed.Substring(grainIdIndex, systemTargetIndex - grainIdIndex).Trim();
string systemTargetStr = trimmed.Substring(systemTargetIndex + (SYSTEM_TARGET_STR + "=").Length);
SiloAddress siloAddress = SiloAddress.FromParsableString(systemTargetStr);
return FromGrainId(GrainId.FromParsableString(grainIdStr), null, siloAddress);
}
else
{
grainIdStr = trimmed.Substring(grainIdIndex);
return FromGrainId(GrainId.FromParsableString(grainIdStr));
}
//return FromGrainId(GrainId.FromParsableString(grainIdStr), generic);
}
#region ISerializable Members
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
// Use the AddValue method to specify serialized values.
info.AddValue("GrainId", GrainId.ToParsableString(), typeof(string));
if (IsSystemTarget)
{
info.AddValue("SystemTargetSilo", SystemTargetSilo.ToParsableString(), typeof(string));
}
if (IsObserverReference)
{
info.AddValue(OBSERVER_ID_STR, observerId.ToParsableString(), typeof(string));
}
string genericArg = String.Empty;
if (HasGenericArgument)
genericArg = genericArguments;
info.AddValue("GenericArguments", genericArg, typeof(string));
}
// The special constructor is used to deserialize values.
protected GrainReference(SerializationInfo info, StreamingContext context)
{
// Reset the property value using the GetValue method.
var grainIdStr = info.GetString("GrainId");
GrainId = GrainId.FromParsableString(grainIdStr);
if (IsSystemTarget)
{
var siloAddressStr = info.GetString("SystemTargetSilo");
SystemTargetSilo = SiloAddress.FromParsableString(siloAddressStr);
}
if (IsObserverReference)
{
var observerIdStr = info.GetString(OBSERVER_ID_STR);
observerId = GuidId.FromParsableString(observerIdStr);
}
var genericArg = info.GetString("GenericArguments");
if (String.IsNullOrEmpty(genericArg))
genericArg = null;
genericArguments = genericArg;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Sqloogle.Libs.DBDiff.Schema.Attributes;
using Sqloogle.Libs.DBDiff.Schema.Model;
using Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Options;
namespace Sqloogle.Libs.DBDiff.Schema.SqlServer2005.Model
{
public class Database : SQLServerSchemaBase, IDatabase
{
private readonly List<DatabaseChangeStatus> _changesOptions;
private DatabaseInfo _info;
public Database() : base(null, Enums.ObjectType.Database)
{
AllObjects = new SearchSchemaBase();
_changesOptions = new List<DatabaseChangeStatus>();
Dependencies = new Dependencies();
TablesTypes = new SchemaList<TableType, Database>(this, AllObjects);
UserTypes = new SchemaList<UserDataType, Database>(this, AllObjects);
XmlSchemas = new SchemaList<XMLSchema, Database>(this, AllObjects);
Schemas = new SchemaList<Schema, Database>(this, AllObjects);
Procedures = new SchemaList<StoreProcedure, Database>(this, AllObjects);
CLRProcedures = new SchemaList<CLRStoreProcedure, Database>(this, AllObjects);
CLRFunctions = new SchemaList<CLRFunction, Database>(this, AllObjects);
FileGroups = new SchemaList<FileGroup, Database>(this);
Rules = new SchemaList<Rule, Database>(this, AllObjects);
DDLTriggers = new SchemaList<Trigger, Database>(this, AllObjects);
Synonyms = new SchemaList<Synonym, Database>(this, AllObjects);
Assemblies = new SchemaList<Assembly, Database>(this, AllObjects);
Views = new SchemaList<View, Database>(this, AllObjects);
Users = new SchemaList<User, Database>(this, AllObjects);
FullText = new SchemaList<FullText, Database>(this, AllObjects);
Functions = new SchemaList<Function, Database>(this, AllObjects);
PartitionFunctions = new SchemaList<PartitionFunction, Database>(this, AllObjects);
PartitionSchemes = new SchemaList<PartitionScheme, Database>(this, AllObjects);
Roles = new SchemaList<Role, Database>(this);
Tables = new SchemaList<Table, Database>(this, AllObjects);
Defaults = new SchemaList<Default, Database>(this, AllObjects);
ActionMessage = new SqlAction(this);
}
internal SearchSchemaBase AllObjects { get; private set; }
[ShowItem("Full Text Catalog", "FullText")]
public SchemaList<FullText, Database> FullText { get; private set; }
[ShowItem("Table Type", "Table")]
public SchemaList<TableType, Database> TablesTypes { get; private set; }
[ShowItem("Partition Scheme", "PartitionScheme")]
public SchemaList<PartitionScheme, Database> PartitionSchemes { get; private set; }
[ShowItem("Partition Functions", "PartitionFunction")]
public SchemaList<PartitionFunction, Database> PartitionFunctions { get; private set; }
[ShowItem("Defaults")]
public SchemaList<Default, Database> Defaults { get; private set; }
[ShowItem("Roles", "Rol")]
public SchemaList<Role, Database> Roles { get; private set; }
[ShowItem("Functions", "Function", true)]
public SchemaList<Function, Database> Functions { get; private set; }
[ShowItem("Users", "User")]
public SchemaList<User, Database> Users { get; private set; }
[ShowItem("Views", "View", true)]
public SchemaList<View, Database> Views { get; private set; }
[ShowItem("Assemblies", "Assembly")]
public SchemaList<Assembly, Database> Assemblies { get; private set; }
[ShowItem("Synonyms")]
public SchemaList<Synonym, Database> Synonyms { get; private set; }
[ShowItem("DLL Triggers")]
public SchemaList<Trigger, Database> DDLTriggers { get; private set; }
[ShowItem("File Groups")]
public SchemaList<FileGroup, Database> FileGroups { get; private set; }
[ShowItem("Rules")]
public SchemaList<Rule, Database> Rules { get; private set; }
[ShowItem("Store Procedures", "Procedure", true)]
public SchemaList<StoreProcedure, Database> Procedures { get; private set; }
[ShowItem("CLR Store Procedures", "CLRProcedure", true)]
public SchemaList<CLRStoreProcedure, Database> CLRProcedures { get; private set; }
[ShowItem("CLR Functions", "CLRFunction", true)]
public SchemaList<CLRFunction, Database> CLRFunctions { get; private set; }
[ShowItem("Schemas", "Schema")]
public SchemaList<Schema, Database> Schemas { get; private set; }
[ShowItem("XML Schemas", "XMLSchema")]
public SchemaList<XMLSchema, Database> XmlSchemas { get; private set; }
[ShowItem("Tables", "Table")]
public SchemaList<Table, Database> Tables { get; private set; }
[ShowItem("User Types", "UDT")]
public SchemaList<UserDataType, Database> UserTypes { get; private set; }
public SqlOption Options { get; set; }
public DatabaseInfo Info
{
get { return _info; }
set { _info = value; }
}
public DatabaseInfo SourceInfo
{
get;
set;
}
/// <summary>
/// Coleccion de dependencias de constraints.
/// </summary>
internal Dependencies Dependencies { get; set; }
private List<DatabaseChangeStatus> ChangesOptions
{
get { return _changesOptions; }
}
#region IDatabase Members
public override ISchemaBase Clone(ISchemaBase parent)
{
//Get a list of all of the objects that are SchemaLists, so that we can clone them all.
var item = new Database() { AllObjects = this.AllObjects };
var explicitProperties = (from properties in this.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)
where properties.PropertyType.GetInterface(typeof(DBDiff.Schema.Model.ISchemaList<Code, Database>).Name) != null
select properties).ToList();
foreach (var property in explicitProperties)
{
object value = property.GetValue(this, null);
//Clone the value
value = value.GetType().GetMethod("Clone").Invoke(value, new object[] { this });
//Set the value to the cloned object
property.SetValue(item, value, null);
}
return item;
}
public SqlAction ActionMessage { get; private set; }
public Boolean IsCaseSensity
{
get
{
bool isCS = false;
if (!String.IsNullOrEmpty(_info.Collation))
isCS = _info.Collation.IndexOf("_CS_") != -1;
if (Options.Comparison.CaseSensityType == SqlOptionComparison.CaseSensityOptions.Automatic)
return isCS;
if (Options.Comparison.CaseSensityType == SqlOptionComparison.CaseSensityOptions.CaseSensity)
return true;
if (Options.Comparison.CaseSensityType == SqlOptionComparison.CaseSensityOptions.CaseInsensity)
return false;
return false;
}
}
public override string ToSql()
{
string sql = "";
sql += FileGroups.ToSql();
sql += Schemas.ToSql();
sql += XmlSchemas.ToSql();
sql += Rules.ToSql();
sql += UserTypes.ToSql();
sql += Assemblies.ToSql();
sql += Tables.ToSql();
sql += Functions.ToSql();
sql += Procedures.ToSql();
sql += CLRProcedures.ToSql();
sql += CLRFunctions.ToSql();
sql += DDLTriggers.ToSql();
sql += Synonyms.ToSql();
sql += Views.ToSql();
sql += Users.ToSql();
sql += PartitionFunctions.ToSql();
sql += FullText.ToSql();
return sql;
}
/*public List<ISchemaBase> FindAllByColumn(String ColumnName)
{
this.t
}*/
public override SQLScriptList ToSqlDiff()
{
return ToSqlDiff(new List<ISchemaBase>());
}
public override SQLScriptList ToSqlDiff(List<ISchemaBase> schemas)
{
var isAzure10 = this.Info.Version == DatabaseInfo.VersionTypeEnum.SQLServerAzure10;
var listDiff = new SQLScriptList();
listDiff.Add(new SQLScript(String.Format(@"/*
Open DBDiff {0}
http://opendbiff.codeplex.com/
Script created by {1}\{2} on {3} at {4}.
Created on: {5}
Source: {6} on {7}
Destination: {8} on {9}
*/
",
System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(),
Environment.UserDomainName,
Environment.UserName,
DateTime.Now.ToShortDateString(),
DateTime.Now.ToLongTimeString(),
Environment.MachineName,
SourceInfo != null ? SourceInfo.Database : "Uknown",
SourceInfo != null ? SourceInfo.Server : "Uknown",
Info != null ? Info.Database : "Uknown",
Info != null ? Info.Server : "Uknown",
0), 0, Enums.ScripActionType.None));
if (!isAzure10)
{
listDiff.Add("USE [" + Name + "]\r\nGO\r\n\r\n", 0, Enums.ScripActionType.UseDatabase);
listDiff.AddRange(Assemblies.ToSqlDiff(schemas));
listDiff.AddRange(UserTypes.ToSqlDiff(schemas));
}
listDiff.AddRange(TablesTypes.ToSqlDiff(schemas));
listDiff.AddRange(Tables.ToSqlDiff(schemas));
listDiff.AddRange(Rules.ToSqlDiff(schemas));
listDiff.AddRange(Schemas.ToSqlDiff(schemas));
listDiff.AddRange(XmlSchemas.ToSqlDiff(schemas));
listDiff.AddRange(Procedures.ToSqlDiff(schemas));
if (!isAzure10)
{
listDiff.AddRange(CLRProcedures.ToSqlDiff(schemas));
listDiff.AddRange(CLRFunctions.ToSqlDiff(schemas));
listDiff.AddRange(FileGroups.ToSqlDiff(schemas));
}
listDiff.AddRange(DDLTriggers.ToSqlDiff(schemas));
listDiff.AddRange(Synonyms.ToSqlDiff(schemas));
listDiff.AddRange(Views.ToSqlDiff(schemas));
listDiff.AddRange(Users.ToSqlDiff(schemas));
listDiff.AddRange(Functions.ToSqlDiff(schemas));
listDiff.AddRange(Roles.ToSqlDiff(schemas));
listDiff.AddRange(PartitionFunctions.ToSqlDiff(schemas));
listDiff.AddRange(PartitionSchemes.ToSqlDiff(schemas));
if (!isAzure10)
{
listDiff.AddRange(FullText.ToSqlDiff(schemas));
}
return listDiff;
}
public override string ToSqlDrop()
{
return "";
}
public override string ToSqlAdd()
{
return "";
}
#endregion
public ISchemaBase Find(int id)
{
try
{
string full = AllObjects.GetFullName(id);
return Find(full);
}
catch
{
return null;
}
}
public ISchemaBase Find(String _FullName)
{
try
{
Enums.ObjectType type = AllObjects.GetType(_FullName);
string parentName = "";
switch (type)
{
case Enums.ObjectType.Table:
return Tables[_FullName];
case Enums.ObjectType.StoreProcedure:
return Procedures[_FullName];
case Enums.ObjectType.Function:
return Functions[_FullName];
case Enums.ObjectType.View:
return Views[_FullName];
case Enums.ObjectType.Assembly:
return Assemblies[_FullName];
case Enums.ObjectType.UserDataType:
return UserTypes[_FullName];
case Enums.ObjectType.TableType:
return TablesTypes[_FullName];
case Enums.ObjectType.XMLSchema:
return XmlSchemas[_FullName];
case Enums.ObjectType.CLRStoreProcedure:
return CLRProcedures[_FullName];
case Enums.ObjectType.CLRFunction:
return CLRFunctions[_FullName];
case Enums.ObjectType.Synonym:
return Synonyms[_FullName];
case Enums.ObjectType.FullText:
return FullText[_FullName];
case Enums.ObjectType.Rule:
return Rules[_FullName];
case Enums.ObjectType.PartitionFunction:
return PartitionFunctions[_FullName];
case Enums.ObjectType.PartitionScheme:
return PartitionSchemes[_FullName];
case Enums.ObjectType.Role:
return Roles[_FullName];
case Enums.ObjectType.Schema:
return Schemas[_FullName];
case Enums.ObjectType.Constraint:
parentName = AllObjects.GetParentName(_FullName);
return Tables[parentName].Constraints[_FullName];
case Enums.ObjectType.Index:
parentName = AllObjects.GetParentName(_FullName);
type = AllObjects.GetType(parentName);
if (type == Enums.ObjectType.Table)
return Tables[parentName].Indexes[_FullName];
return Views[parentName].Indexes[_FullName];
case Enums.ObjectType.Trigger:
parentName = AllObjects.GetParentName(_FullName);
type = AllObjects.GetType(parentName);
if (type == Enums.ObjectType.Table)
return Tables[parentName].Triggers[_FullName];
return Views[parentName].Triggers[_FullName];
case Enums.ObjectType.CLRTrigger:
parentName = AllObjects.GetParentName(_FullName);
type = AllObjects.GetType(parentName);
if (type == Enums.ObjectType.Table)
return Tables[parentName].CLRTriggers[_FullName];
return Views[parentName].CLRTriggers[_FullName];
}
return null;
}
catch
{
return null;
}
}
/*private SQLScriptList CleanScripts(SQLScriptList listDiff)
{
SQLScriptList alters = listDiff.FindAlter();
for (int j = 0; j < alters.Count; j++)
{
//alters[j].
}
return null;
}*/
public void BuildDependency()
{
ISchemaBase schema;
var indexes = new List<Index>();
var constraints = new List<Constraint>();
Tables.ForEach(item => indexes.AddRange(item.Indexes));
Views.ForEach(item => indexes.AddRange(item.Indexes));
Tables.ForEach(item => constraints.AddRange(item.Constraints));
foreach (Index index in indexes)
{
schema = index.Parent;
foreach (IndexColumn icolumn in index.Columns)
{
Dependencies.Add(this, schema.Id, icolumn.Id, schema.Id, icolumn.DataTypeId, index);
}
}
foreach (Constraint con in constraints)
{
schema = con.Parent;
if (con.Type != Constraint.ConstraintType.Check)
{
foreach (ConstraintColumn ccolumn in con.Columns)
{
Dependencies.Add(this, schema.Id, ccolumn.Id, schema.Id, ccolumn.DataTypeId, con);
if (con.Type == Constraint.ConstraintType.ForeignKey)
{
Dependencies.Add(this, con.RelationalTableId, ccolumn.ColumnRelationalId, schema.Id,
ccolumn.ColumnRelationalDataTypeId, con);
}
else
{
if (
((Table) schema).FullTextIndex.Exists(
item => { return item.Index.Equals(con.Name); }))
{
Dependencies.Add(this, schema.Id, 0, schema.Id, 0, con);
}
}
}
}
else
Dependencies.Add(this, schema.Id, 0, schema.Id, 0, con);
}
}
#region Nested type: DatabaseChangeStatus
private enum DatabaseChangeStatus
{
AlterChangeTracking = 1,
AlterCollation = 2
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using Lidgren.Network;
using log4net;
using NetGore.Features.Guilds;
using NetGore.Features.Quests;
using NetGore.Features.Shops;
using NetGore.Network;
namespace NetGore.Features.WorldStats
{
/// <summary>
/// Base class for an implementation of the <see cref="IWorldStatsTracker{T,U,V}"/> that can handle the default world
/// statistics tracking.
/// </summary>
/// <typeparam name="TUser">The type of user character.</typeparam>
/// <typeparam name="TNPC">The type of NPC character.</typeparam>
/// <typeparam name="TItem">The type of item.</typeparam>
[SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")]
public abstract class WorldStatsTracker<TUser, TNPC, TItem> : IWorldStatsTracker<TUser, TNPC, TItem>
where TUser : class where TNPC : class where TItem : class
{
static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly TickCount _logNetStatsRate;
NetPeerStatisticsSnapshot _lastNetStatsValues;
NetPeer _netPeer;
TickCount _nextLogNetStatsTime;
/// <summary>
/// Initializes a new instance of the <see cref="WorldStatsTracker{TUser, TNPC, TItem}"/> class.
/// </summary>
/// <param name="logNetStatsRate">The rate in milliseconds that the <see cref="NetPeerStatisticsSnapshot"/> information is
/// logged to the database.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="logNetStatsRate"/> is less than
/// or equal to zero.</exception>
protected WorldStatsTracker(TickCount logNetStatsRate)
{
if (logNetStatsRate <= 0)
throw new ArgumentOutOfRangeException("logNetStatsRate", "logNetStatsRate must be greater than or equal to zero.");
_logNetStatsRate = logNetStatsRate;
_nextLogNetStatsTime = TickCount.Now;
}
/// <summary>
/// Gets the rate in milliseconds that the <see cref="NetPeerStatisticsSnapshot"/> information is logged to the database.
/// </summary>
public TickCount LogNetStatsRate
{
get { return _logNetStatsRate; }
}
/// <summary>
/// Gets the time to use for the next update.
/// </summary>
/// <param name="currentTime">The current time.</param>
/// <param name="lastUpdateTime">The time the last update happened.</param>
/// <param name="updateRate">The update rate.</param>
/// <returns>The time to use for the next update.</returns>
protected virtual TickCount GetNextUpdateTime(TickCount currentTime, TickCount lastUpdateTime, TickCount updateRate)
{
// Increment by the update rate
var nextTime = lastUpdateTime + updateRate;
// If there is a large gap between updates, do not let it result in a bunch of consecutive updates happening
// as we catch up
if (nextTime < currentTime)
nextTime = currentTime;
return nextTime;
}
/// <summary>
/// When overridden in the derived class, adds to the item purchase counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was purchased from a shop.</param>
/// <param name="amount">The number of items purchased.</param>
protected abstract void InternalAddCountBuyItem(int itemTID, int amount);
/// <summary>
/// When overridden in the derived class, adds to the item consumption counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was consumed.</param>
protected abstract void InternalAddCountConsumeItem(int itemTID);
/// <summary>
/// When overridden in the derived class, adds to the item creation counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was sold to a shop.</param>
/// <param name="amount">The number of items created.</param>
protected abstract void InternalAddCountCreateItem(int itemTID, int amount);
/// <summary>
/// When overridden in the derived class, adds to the NPC kill user counter.
/// </summary>
/// <param name="npcTID">The template ID of the NPC that killed the user.</param>
/// <param name="userID">The template ID of the user that was killed.</param>
protected abstract void InternalAddCountNPCKillUser(int npcTID, int userID);
/// <summary>
/// When overridden in the derived class, adds to the item sell counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was sold to a shop.</param>
/// <param name="amount">The number of items sold.</param>
protected abstract void InternalAddCountSellItem(int itemTID, int amount);
/// <summary>
/// When overridden in the derived class, adds to the item being purchased from a shop counter.
/// </summary>
/// <param name="shopID">The ID of the shop that sold the item.</param>
/// <param name="amount">The number of items the shop sold.</param>
protected abstract void InternalAddCountShopBuy(int shopID, int amount);
/// <summary>
/// When overridden in the derived class, adds to the item being sold to a shop counter.
/// </summary>
/// <param name="shopID">The ID of the shop the item was sold to.</param>
/// <param name="amount">The number of items sold to the shop.</param>
protected abstract void InternalAddCountShopSell(int shopID, int amount);
/// <summary>
/// When overridden in the derived class, adds to the item consumption count.
/// </summary>
/// <param name="userID">The ID of the user who consumed the item.</param>
/// <param name="itemTID">The item template ID of the item consumed.</param>
protected abstract void InternalAddCountUserConsumeItem(int userID, int itemTID);
/// <summary>
/// When overridden in the derived class, adds to the user kill a NPC counter.
/// </summary>
/// <param name="userID">The template ID of the user that killed the NPC.</param>
/// <param name="npcTID">The template ID of the NPC that was killed.</param>
protected abstract void InternalAddCountUserKillNPC(int userID, int npcTID);
/// <summary>
/// When overridden in the derived class, adds when a NPC kills a user.
/// </summary>
/// <param name="npc">The NPC that killed the <paramref name="user"/>.</param>
/// <param name="user">The User that was killed by the <paramref name="npc"/>.</param>
protected abstract void InternalAddNPCKillUser(TNPC npc, TUser user);
/// <summary>
/// When overridden in the derived class, adds when a user accepts a quest.
/// </summary>
/// <param name="user">The user that accepted a quest.</param>
/// <param name="questID">The ID of the quest that the user accepted.</param>
protected abstract void InternalAddQuestAccept(TUser user, QuestID questID);
/// <summary>
/// When overridden in the derived class, adds when a user cancels a quest.
/// </summary>
/// <param name="user">The user that canceled a quest.</param>
/// <param name="questID">The ID of the quest that the user canceled.</param>
protected abstract void InternalAddQuestCancel(TUser user, QuestID questID);
/// <summary>
/// When overridden in the derived class, adds when a user completes a quest.
/// </summary>
/// <param name="user">The user that completed a quest.</param>
/// <param name="questID">The ID of the quest that the user completed.</param>
protected abstract void InternalAddQuestComplete(TUser user, QuestID questID);
/// <summary>
/// When overridden in the derived class, adds when a user consumes a consumable item.
/// </summary>
/// <param name="user">The user that consumed the item.</param>
/// <param name="item">The item that was consumed.</param>
protected abstract void InternalAddUserConsumeItem(TUser user, TItem item);
/// <summary>
/// When overridden in the derived class, adds when a user changes their guild.
/// </summary>
/// <param name="user">The user that changed their guild.</param>
/// <param name="guildID">The ID of the guild the user changed to. If this event is for when the user left a guild,
/// this value will be null.</param>
protected abstract void InternalAddUserGuildChange(TUser user, GuildID? guildID);
/// <summary>
/// When overridden in the derived class, adds when a user kills a NPC.
/// </summary>
/// <param name="user">The user that killed the <paramref name="npc"/>.</param>
/// <param name="npc">The NPC that was killed by the <paramref name="user"/>.</param>
protected abstract void InternalAddUserKillNPC(TUser user, TNPC npc);
/// <summary>
/// When overridden in the derived class, adds when a user gains a level.
/// </summary>
/// <param name="user">The user that leveled up.</param>
protected abstract void InternalAddUserLevel(TUser user);
/// <summary>
/// When overridden in the derived class, adds when a user buys an item from a shop.
/// </summary>
/// <param name="user">The user that bought from a shop.</param>
/// <param name="itemTemplateID">The template ID of the item that was purchased.</param>
/// <param name="amount">How many units of the item was purchased.</param>
/// <param name="cost">How much the user bought the items for. When the amount is greater than one, this includes
/// the cost of all the items together, not a single item. That is, the cost of the transaction as a whole.</param>
/// <param name="shopID">The ID of the shop the transaction took place at.</param>
protected abstract void InternalAddUserShopBuyItem(TUser user, int? itemTemplateID, byte amount, int cost, ShopID shopID);
/// <summary>
/// When overridden in the derived class, adds when a user sells an item to a shop.
/// </summary>
/// <param name="user">The user that sold to a shop.</param>
/// <param name="itemTemplateID">The template ID of the item that was sold.</param>
/// <param name="amount">How many units of the item was sold.</param>
/// <param name="cost">How much the user sold the items for. When the amount is greater than one, this includes
/// the cost of all the items together, not a single item. That is, the cost of the transaction as a whole.</param>
/// <param name="shopID">The ID of the shop the transaction took place at.</param>
protected abstract void InternalAddUserShopSellItem(TUser user, int? itemTemplateID, byte amount, int cost, ShopID shopID);
/// <summary>
/// Updates the statistics.
/// </summary>
/// <param name="currentTime">The current time in milliseconds.</param>
protected virtual void InternalUpdate(TickCount currentTime)
{
// NetStats
if (_nextLogNetStatsTime < currentTime)
{
// Ensure we have the NetPeer set
var netPeer = NetPeerToTrack;
var ss = _lastNetStatsValues;
if (netPeer != null && ss != null)
{
// Grab the current snapshot
var newSS = new NetPeerStatisticsSnapshot(netPeer.Statistics);
// Find the time delta
var deltaMS = newSS.Time - ss.Time;
var deltaSecs = deltaMS / 1000f;
// Find the values (most of which are diffs from the last value, averaged over time)
var conns = (ushort)netPeer.ConnectionsCount;
var recvBytes = NetAvg(newSS.ReceivedBytes, ss.ReceivedBytes, deltaSecs);
var recvPackets = NetAvg(newSS.ReceivedPackets, ss.ReceivedPackets, deltaSecs);
var recvMsgs = NetAvg(newSS.ReceivedMessages, ss.ReceivedMessages, deltaSecs);
var sentBytes = NetAvg(newSS.SentBytes, ss.SentBytes, deltaSecs);
var sentPackets = NetAvg(newSS.SentPackets, ss.SentPackets, deltaSecs);
var sentMsgs = NetAvg(newSS.SentMessages, ss.SentMessages, deltaSecs);
// Update the last snapshot to now
_lastNetStatsValues = newSS;
// Log
LogNetStats(conns, recvBytes, recvPackets, recvMsgs, sentBytes, sentPackets, sentMsgs);
}
// Update the time to perform the next logging
_nextLogNetStatsTime = GetNextUpdateTime(currentTime, _nextLogNetStatsTime, LogNetStatsRate);
}
}
/// <summary>
/// When overridden in the derived class, logs the network statistics to the database.
/// </summary>
/// <param name="connections">The current number of connections.</param>
/// <param name="recvBytes">The average bytes received per second.</param>
/// <param name="recvPackets">The average packets received per second.</param>
/// <param name="recvMsgs">The average messages received per second.</param>
/// <param name="sentBytes">The average bytes sent per second.</param>
/// <param name="sentPackets">The average packets sent per second.</param>
/// <param name="sentMsgs">The average messages sent per second.</param>
protected abstract void LogNetStats(ushort connections, uint recvBytes, uint recvPackets, uint recvMsgs, uint sentBytes,
uint sentPackets, uint sentMsgs);
/// <summary>
/// Gets the average rate per second for a <see cref="NetPeerStatisticsSnapshot"/>.
/// </summary>
/// <param name="curr">The current value.</param>
/// <param name="last">The previous value.</param>
/// <param name="deltaSecs">The time delta between the <paramref name="curr"/> and <paramref name="last"/> in seconds.</param>
/// <returns>The average per second difference between the two values.</returns>
static uint NetAvg(int curr, int last, float deltaSecs)
{
if (curr < last)
{
Debug.Fail("How did the value decrease over time?");
return 0;
}
var diff = curr - last;
// Get the rate per second
var ret = Math.Round(diff / deltaSecs);
// Make sure we don't underflow
return (uint)Math.Max(0, ret);
}
/// <summary>
/// Gets the <see cref="DateTime"/> for the current time.
/// </summary>
/// <returns>The <see cref="DateTime"/> for the current time.</returns>
protected virtual DateTime Now()
{
return DateTime.Now;
}
/// <summary>
/// Handles when an <see cref="Exception"/> is thrown while executing a query in the <see cref="WorldStatsTracker{T,U,V}"/>.
/// </summary>
/// <param name="ex">The <see cref="Exception"/>.</param>
protected virtual void OnQueryException(Exception ex)
{
const string errmsg = "Error executing WorldStatsTracker query on `{0}`. Exception: {1}";
if (log.IsErrorEnabled)
log.ErrorFormat(errmsg, this, ex);
Debug.Fail(string.Format(errmsg, this, ex));
}
#region IWorldStatsTracker<TUser,TNPC,TItem> Members
/// <summary>
/// Gets or sets the <see cref="NetPeer"/> to log the statistics for.
/// If null, the statistics will not be logged.
/// </summary>
public NetPeer NetPeerToTrack
{
get { return _netPeer; }
set
{
if (_netPeer == value)
return;
_netPeer = value;
_nextLogNetStatsTime = TickCount.Now + _logNetStatsRate;
if (NetPeerToTrack != null)
_lastNetStatsValues = new NetPeerStatisticsSnapshot(NetPeerToTrack.Statistics);
else
_lastNetStatsValues = null;
}
}
/// <summary>
/// Adds to the item purchase counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was purchased from a shop.</param>
/// <param name="amount">The number of items purchased.</param>
public void AddCountBuyItem(int itemTID, int amount)
{
try
{
InternalAddCountBuyItem(itemTID, amount);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item consumption counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was consumed.</param>
public void AddCountConsumeItem(int itemTID)
{
try
{
InternalAddCountConsumeItem(itemTID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item creation counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was sold to a shop.</param>
/// <param name="amount">The number of items created.</param>
public void AddCountCreateItem(int itemTID, int amount)
{
try
{
InternalAddCountCreateItem(itemTID, amount);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the NPC kill user counter.
/// </summary>
/// <param name="npcTID">The template ID of the NPC that killed the user.</param>
/// <param name="userID">The template ID of the user that was killed.</param>
public void AddCountNPCKillUser(int npcTID, int userID)
{
try
{
InternalAddCountNPCKillUser(npcTID, userID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item sell counter.
/// </summary>
/// <param name="itemTID">The template ID of the item that was sold to a shop.</param>
/// <param name="amount">The number of items sold.</param>
public void AddCountSellItem(int itemTID, int amount)
{
try
{
InternalAddCountSellItem(itemTID, amount);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item being purchased from a shop counter.
/// </summary>
/// <param name="shopID">The ID of the shop that sold the item.</param>
/// <param name="amount">The number of items the shop sold.</param>
public void AddCountShopBuy(int shopID, int amount)
{
try
{
InternalAddCountShopBuy(shopID, amount);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item being sold to a shop counter.
/// </summary>
/// <param name="shopID">The ID of the shop the item was sold to.</param>
/// <param name="amount">The number of items sold to the shop.</param>
public void AddCountShopSell(int shopID, int amount)
{
try
{
InternalAddCountShopSell(shopID, amount);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the item consumption count.
/// </summary>
/// <param name="userID">The ID of the user who consumed the item.</param>
/// <param name="itemTID">The item template ID of the item consumed.</param>
public void AddCountUserConsumeItem(int userID, int itemTID)
{
try
{
InternalAddCountUserConsumeItem(userID, itemTID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds to the user kill a NPC counter.
/// </summary>
/// <param name="userID">The template ID of the user that killed the NPC.</param>
/// <param name="npcTID">The template ID of the NPC that was killed.</param>
public void AddCountUserKillNPC(int userID, int npcTID)
{
try
{
InternalAddCountUserKillNPC(userID, npcTID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a NPC kills a user.
/// </summary>
/// <param name="npc">The NPC that killed the <paramref name="user"/>.</param>
/// <param name="user">The User that was killed by the <paramref name="npc"/>.</param>
public void AddNPCKillUser(TNPC npc, TUser user)
{
try
{
if (npc == null)
return;
if (user == null)
return;
InternalAddNPCKillUser(npc, user);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user accepts a quest.
/// </summary>
/// <param name="user">The user that accepted a quest.</param>
/// <param name="questID">The ID of the quest that the user accepted.</param>
public void AddQuestAccept(TUser user, QuestID questID)
{
try
{
if (user == null)
return;
InternalAddQuestAccept(user, questID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user cancels a quest.
/// </summary>
/// <param name="user">The user that canceled a quest.</param>
/// <param name="questID">The ID of the quest that the user canceled.</param>
public void AddQuestCancel(TUser user, QuestID questID)
{
try
{
if (user == null)
return;
InternalAddQuestCancel(user, questID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user completes a quest.
/// </summary>
/// <param name="user">The user that completed a quest.</param>
/// <param name="questID">The ID of the quest that the user completed.</param>
public void AddQuestComplete(TUser user, QuestID questID)
{
try
{
if (user == null)
return;
InternalAddQuestComplete(user, questID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user consumes a consumable item.
/// </summary>
/// <param name="user">The user that consumed the item.</param>
/// <param name="item">The item that was consumed.</param>
public void AddUserConsumeItem(TUser user, TItem item)
{
try
{
if (user == null)
return;
if (item == null)
return;
InternalAddUserConsumeItem(user, item);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user changes their guild.
/// </summary>
/// <param name="user">The user that changed their guild.</param>
/// <param name="guildID">The ID of the guild the user changed to. If this event is for when the user left a guild,
/// this value will be null.</param>
public void AddUserGuildChange(TUser user, GuildID? guildID)
{
try
{
if (user == null)
return;
InternalAddUserGuildChange(user, guildID);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user kills a NPC.
/// </summary>
/// <param name="user">The user that killed the <paramref name="npc"/>.</param>
/// <param name="npc">The NPC that was killed by the <paramref name="user"/>.</param>
public void AddUserKillNPC(TUser user, TNPC npc)
{
try
{
if (user == null)
return;
if (npc == null)
return;
InternalAddUserKillNPC(user, npc);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user gains a level.
/// </summary>
/// <param name="user">The user that leveled up.</param>
public void AddUserLevel(TUser user)
{
try
{
if (user == null)
return;
InternalAddUserLevel(user);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user buys an item from a shop.
/// </summary>
/// <param name="user">The user that bought from a shop.</param>
/// <param name="itemTemplateID">The template ID of the item that was purchased.</param>
/// <param name="amount">How many units of the item was purchased.</param>
/// <param name="cost">How much the user bought the items for. When the amount is greater than one, this includes
/// the cost of all the items together, not a single item. That is, the cost of the transaction as a whole.</param>
/// <param name="shopID">The ID of the shop the transaction took place at.</param>
public void AddUserShopBuyItem(TUser user, int? itemTemplateID, byte amount, int cost, ShopID shopID)
{
try
{
if (user == null)
return;
if (amount <= 0)
return;
InternalAddUserLevel(user);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Adds when a user sells an item to a shop.
/// </summary>
/// <param name="user">The user that sold to a shop.</param>
/// <param name="itemTemplateID">The template ID of the item that was sold.</param>
/// <param name="amount">How many units of the item was sold.</param>
/// <param name="cost">How much the user sold the items for. When the amount is greater than one, this includes
/// the cost of all the items together, not a single item. That is, the cost of the transaction as a whole.</param>
/// <param name="shopID">The ID of the shop the transaction took place at.</param>
public void AddUserShopSellItem(TUser user, int? itemTemplateID, byte amount, int cost, ShopID shopID)
{
try
{
if (user == null)
return;
if (amount <= 0)
return;
InternalAddUserLevel(user);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
/// <summary>
/// Updates the statistics that are time-based.
/// </summary>
public void Update()
{
try
{
InternalUpdate(TickCount.Now);
}
catch (Exception ex)
{
OnQueryException(ex);
}
}
#endregion
}
}
| |
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class ZiggeoConnect {
private Ziggeo application;
private string baseUri;
private ZiggeoConfig config;
public ZiggeoConnect(Ziggeo application, string baseUri) {
this.application = application;
this.baseUri = baseUri;
this.config = new ZiggeoConfig();
}
public ZiggeoConnect(Ziggeo application, string baseUri, ZiggeoConfig config) {
this.application = application;
this.baseUri = baseUri;
this.config = config;
}
public Stream makeRequest(string method, string path, Dictionary<string, string> data, string file) {
int statusCode = 0;
for(int i = 0; i < this.config.resilience_factor; i++) {
HttpWebResponse res = this.request(method, path, data, file);
if((int)res.StatusCode >= 200 && (int)res.StatusCode < 500) {
//good to go
return res.GetResponseStream();
}
statusCode = (int)res.StatusCode;
}
Dictionary<string, string> errRes = new Dictionary<string, string>();
//If failed return the default value
errRes["response"] = (string) this.config.resilience_onfail["error"];
if(statusCode == 0) {
errRes["StatusCode"] = "900"; //Just a unique code to recognize that the error is internal in nature. At this point you could grab more details from $result['error']
}
string errorResponse = JsonConvert.SerializeObject(errRes, Formatting.Indented);
var errorResponseStream = new MemoryStream();
this.WriteStringToStream(errorResponseStream, errorResponse);
return errorResponseStream;
}
public Stream makeUploadRequest(string path, Dictionary<string, string> data, string file) {
int statusCode = 0;
for(int i = 0; i < this.config.resilience_factor; i++) {
HttpWebResponse res = this.uploadFileRequest(path, data, file);
if((int)res.StatusCode >= 200 && (int)res.StatusCode < 500) {
//good to go
return res.GetResponseStream();
}
statusCode = (int)res.StatusCode;
}
throw new InvalidOperationException("Too many upload attempts failed");
}
public HttpWebResponse request(string method, string path, Dictionary<string, string> data, string file)
{
string postData = "";
if (data != null) {
foreach (string key in data.Keys)
postData += key + "=" + data[key] + "&";
}
string uri = this.baseUri + path;
if (method != "POST")
uri += "?" + postData;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
string authInfo = this.application.token + ":" + this.application.private_key;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
request.Method = method;
if (method == "POST")
{
byte[] dataEnc = Encoding.ASCII.GetBytes(postData);
if (!string.IsNullOrEmpty(file))
{
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data; boundary=" + boundary;
Stream requestStream = request.GetRequestStream();
WriteMultipartForm(requestStream, boundary, data, file, "video/mp4");
requestStream.Close();
}
else
{
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataEnc.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(dataEnc, 0, dataEnc.Length);
requestStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
public HttpWebResponse uploadFileRequest(string path, Dictionary<string, string> data, string file)
{
Trace.Write(path);
string postData = "";
if (data != null) {
foreach (string key in data.Keys)
postData += key + "=" + data[key] + "&";
}
string uri = path;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
request.Method = "POST";
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
request.ContentType = "multipart/form-data; boundary=" + boundary;
Stream requestStream = request.GetRequestStream();
WriteMultipartForm(requestStream, boundary, data, file, "video/mp4");
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return response;
}
private void WriteMultipartForm(Stream s, string boundary, Dictionary<string, string> data, string fileName, string fileContentType)
{
byte[] boundarybytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
byte[] trailer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
if (data != null)
{
foreach (string key in data.Keys)
{
WriteDataToStream(s, boundarybytes);
WriteStringToStream(s,
string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n",
key,
data[key])
);
}
}
WriteDataToStream(s, boundarybytes);
WriteStringToStream(s,
string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\";\r\nContent-Type: {2}\r\n\r\n",
"file",
System.IO.Path.GetFileName(fileName),
fileContentType)
);
using (FileStream inputFile = File.OpenRead(fileName))
{
inputFile.CopyTo(s);
}
WriteDataToStream(s, trailer);
}
private void WriteStringToStream(Stream s, string str)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
s.Write(bytes, 0, bytes.Length);
}
private void WriteDataToStream(Stream s, byte[] bytes)
{
s.Write(bytes, 0, bytes.Length);
}
public string requestString(string method, string path, Dictionary<string,string> data, string file) {
Stream stream = this.makeRequest(method, path, data, file);
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
reader.Close();
stream.Close();
return result;
}
public JObject requestJSON(string method, string path, Dictionary<string,string> data, string file) {
return JObject.Parse(this.requestString(method, path, data, file));
}
public JArray requestJSONArray(string method, string path, Dictionary<string,string> data, string file) {
return JArray.Parse(this.requestString(method, path, data, file));
}
public Stream get(string path, Dictionary<string,string> data) {
return this.makeRequest("GET", path, data, null);
}
public JObject getJSON(string path, Dictionary<string,string> data) {
return this.requestJSON("GET", path, data, null);
}
public JArray getJSONArray(string path, Dictionary<string,string> data) {
return this.requestJSONArray("GET", path, data, null);
}
public Stream post(string path, Dictionary<string,string> data, string file) {
return this.makeRequest("POST", path, data, file);
}
public JObject postUploadJSON(string path, string scope, Dictionary<string,string> data, string file, string type_key) {
if (type_key != null) {
data[type_key] = Path.GetExtension(file);
}
var resp = this.postJSON(path, data);
var ret = resp[scope];
Dictionary<string, string> urlData = resp["url_data"]["fields"].ToObject<Dictionary<string, string>>();
this.makeUploadRequest((string) resp["url_data"]["url"], urlData, file);
return (JObject) ret;
}
public JObject postJSON(string path, Dictionary<string,string> data, string file) {
return this.requestJSON("POST", path, data, file);
}
public JObject postJSON(string path, Dictionary<string,string> data) {
return this.requestJSON("POST", path, data, null);
}
public JObject postJSON(string path) {
return this.requestJSON("POST", path, null, null);
}
public JArray postJSONArray(string path, Dictionary<string,string> data, string file) {
return this.requestJSONArray("POST", path, data, file);
}
public Stream delete(string path, Dictionary<string,string> data) {
return this.makeRequest("DELETE", path, data, null);
}
public JObject deleteJSON(string path, Dictionary<string,string> data) {
return this.requestJSON("DELETE", path, data, null);
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace ThisToThat
{
public static partial class ToSByteExtensions
{
/// <summary>
/// Converts this Byte to SByte or returns the specified default value
/// </summary>
/// <returns>This Byte converted to SByte</returns>
/// <remarks>
/// Source type: Byte
/// Min value: 0
/// Max value: 255
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this Byte thisByte, SByte defaultValue = default(SByte))
{
return thisByte.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this Byte to SByte?
/// </summary>
/// <returns>This Byte converted to SByte</returns>
/// <remarks>
/// Source type: Byte
/// Min value: 0
/// Max value: 255
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this Byte thisByte)
{
return (thisByte > (byte)127) ? (SByte?)null : (SByte)thisByte;
}
/// <summary>
/// Converts this Int16 to SByte or returns the specified default value
/// </summary>
/// <returns>This Int16 converted to SByte</returns>
/// <remarks>
/// Source type: Int16
/// Min value: -32768
/// Max value: 32767
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this Int16 thisInt16, SByte defaultValue = default(SByte))
{
return thisInt16.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this Int16 to SByte?
/// </summary>
/// <returns>This Int16 converted to SByte</returns>
/// <remarks>
/// Source type: Int16
/// Min value: -32768
/// Max value: 32767
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this Int16 thisInt16)
{
return (thisInt16 < (short)-128 || thisInt16 > (short)127) ? (SByte?)null : (SByte)thisInt16;
}
/// <summary>
/// Converts this UInt16 to SByte or returns the specified default value
/// </summary>
/// <returns>This UInt16 converted to SByte</returns>
/// <remarks>
/// Source type: UInt16
/// Min value: 0
/// Max value: 65535
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this UInt16 thisUInt16, SByte defaultValue = default(SByte))
{
return thisUInt16.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this UInt16 to SByte?
/// </summary>
/// <returns>This UInt16 converted to SByte</returns>
/// <remarks>
/// Source type: UInt16
/// Min value: 0
/// Max value: 65535
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this UInt16 thisUInt16)
{
return (thisUInt16 > (ushort)127) ? (SByte?)null : (SByte)thisUInt16;
}
/// <summary>
/// Converts this Int32 to SByte or returns the specified default value
/// </summary>
/// <returns>This Int32 converted to SByte</returns>
/// <remarks>
/// Source type: Int32
/// Min value: -2147483648
/// Max value: 2147483647
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this Int32 thisInt32, SByte defaultValue = default(SByte))
{
return thisInt32.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this Int32 to SByte?
/// </summary>
/// <returns>This Int32 converted to SByte</returns>
/// <remarks>
/// Source type: Int32
/// Min value: -2147483648
/// Max value: 2147483647
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this Int32 thisInt32)
{
return (thisInt32 < -128 || thisInt32 > 127) ? (SByte?)null : (SByte)thisInt32;
}
/// <summary>
/// Converts this UInt32 to SByte or returns the specified default value
/// </summary>
/// <returns>This UInt32 converted to SByte</returns>
/// <remarks>
/// Source type: UInt32
/// Min value: 0
/// Max value: 4294967295
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this UInt32 thisUInt32, SByte defaultValue = default(SByte))
{
return thisUInt32.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this UInt32 to SByte?
/// </summary>
/// <returns>This UInt32 converted to SByte</returns>
/// <remarks>
/// Source type: UInt32
/// Min value: 0
/// Max value: 4294967295
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this UInt32 thisUInt32)
{
return (thisUInt32 > 127u) ? (SByte?)null : (SByte)thisUInt32;
}
/// <summary>
/// Converts this Int64 to SByte or returns the specified default value
/// </summary>
/// <returns>This Int64 converted to SByte</returns>
/// <remarks>
/// Source type: Int64
/// Min value: -9223372036854775808
/// Max value: 9223372036854775807
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this Int64 thisInt64, SByte defaultValue = default(SByte))
{
return thisInt64.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this Int64 to SByte?
/// </summary>
/// <returns>This Int64 converted to SByte</returns>
/// <remarks>
/// Source type: Int64
/// Min value: -9223372036854775808
/// Max value: 9223372036854775807
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this Int64 thisInt64)
{
return (thisInt64 < -128L || thisInt64 > 127L) ? (SByte?)null : (SByte)thisInt64;
}
/// <summary>
/// Converts this UInt64 to SByte or returns the specified default value
/// </summary>
/// <returns>This UInt64 converted to SByte</returns>
/// <remarks>
/// Source type: UInt64
/// Min value: 0
/// Max value: 18446744073709551615
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte ToSByteOrDefault(this UInt64 thisUInt64, SByte defaultValue = default(SByte))
{
return thisUInt64.ToSByteNullable().GetValueOrDefault(defaultValue);
}
/// <summary>
/// Converts this UInt64 to SByte?
/// </summary>
/// <returns>This UInt64 converted to SByte</returns>
/// <remarks>
/// Source type: UInt64
/// Min value: 0
/// Max value: 18446744073709551615
///
/// Target type: SByte
/// Min value: -128
/// Max value: 127
/// </remarks>
public static SByte? ToSByteNullable(this UInt64 thisUInt64)
{
return (thisUInt64 > 127UL) ? (SByte?)null : (SByte)thisUInt64;
}
/*
Single to SByte: Method omitted.
SByte is an integral type. Single is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Double to SByte: Method omitted.
SByte is an integral type. Double is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/*
Decimal to SByte: Method omitted.
SByte is an integral type. Decimal is non-integral (can contain fractions).
Conversions involving possible rounding or truncation are not currently provided by this library.
*/
/// <summary>
/// Converts and returns this string's value as a nullable SByte.
/// Null is returned if the value does not successfully parse to SByte.
/// </summary>
/// <returns>This string's value converted to a nullable SByte.</returns>
public static SByte? ToSByteNullable(this string strThisString)
{
SByte sbyteReturn;
return SByte.TryParse(strThisString, out sbyteReturn) ? sbyteReturn : (SByte?)null;
}
/// <summary>
/// Converts and returns this string's value as SByte.
/// The default value passed in is returned if the string does not successfully parse to SByte.
/// </summary>
/// <returns>This string converted to SByte, or the default value if conversion unsuccessful.</returns>
public static SByte ToSByteOrDefault(this string strThisString, SByte sbyteDefault = default(SByte))
{
SByte sbyteReturn;
return SByte.TryParse(strThisString, out sbyteReturn) ? sbyteReturn : sbyteDefault;
}
}
}
| |
using Newtonsoft.Json;
using NSubstitute;
using NuKeeper.Abstractions;
using NuKeeper.Abstractions.Logging;
using NuKeeper.AzureDevOps;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Nukeeper.AzureDevOps.Tests
{
public class AzureDevOpsRestClientTests
{
[Test]
public void InitializesCorrectly()
{
var httpClient = new HttpClient();
var restClient = new AzureDevOpsRestClient(httpClient, Substitute.For<INuKeeperLogger>(), "PAT");
var encodedToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{string.Empty}:PAT"));
Assert.IsTrue(httpClient.DefaultRequestHeaders.Accept.Contains(new MediaTypeWithQualityHeaderValue("application/json")));
Assert.IsTrue(httpClient.DefaultRequestHeaders.Authorization.Equals(new AuthenticationHeaderValue("Basic", encodedToken)));
}
[Test]
public void ThrowsWithBadJson()
{
var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject("<body>Login Page</body>"), Encoding.UTF8, "application/json")
});
var fakeHttpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("https://fakebaseAddress.com/") };
var restClient = new AzureDevOpsRestClient(fakeHttpClient, Substitute.For<INuKeeperLogger>(), "PAT");
var exception = Assert.ThrowsAsync<NuKeeperException>(async () => await restClient.GetGitRepositories("Project"));
}
[Test]
public void ThrowsWithUnauthorized()
{
var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("", Encoding.UTF8, "application/json")
});
var fakeHttpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("https://fakebaseAddress.com/") };
var restClient = new AzureDevOpsRestClient(fakeHttpClient, Substitute.For<INuKeeperLogger>(), "PAT");
var exception = Assert.ThrowsAsync<NuKeeperException>(async () => await restClient.GetGitRepositories("Project"));
Assert.IsTrue(exception.Message.Contains("Unauthorised", StringComparison.InvariantCultureIgnoreCase));
}
[Test]
public void ThrowsWithForbidden()
{
var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage
{
StatusCode = HttpStatusCode.Forbidden,
Content = new StringContent("", Encoding.UTF8, "application/json")
});
var fakeHttpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("https://fakebaseAddress.com/") };
var restClient = new AzureDevOpsRestClient(fakeHttpClient, Substitute.For<INuKeeperLogger>(), "PAT");
var exception = Assert.ThrowsAsync<NuKeeperException>(async () => await restClient.GetGitRepositories("Project"));
Assert.IsTrue(exception.Message.Contains("Forbidden", StringComparison.InvariantCultureIgnoreCase));
}
[Test]
public void ThrowsWithBadStatusCode()
{
var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage
{
StatusCode = HttpStatusCode.BadRequest,
Content = new StringContent("", Encoding.UTF8, "application/json")
});
var fakeHttpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("https://fakebaseAddress.com/") };
var restClient = new AzureDevOpsRestClient(fakeHttpClient, Substitute.For<INuKeeperLogger>(), "PAT");
var exception = Assert.ThrowsAsync<NuKeeperException>(async () => await restClient.GetGitRepositories("Project"));
Assert.IsTrue(exception.Message.Contains("Error", StringComparison.InvariantCultureIgnoreCase));
}
[Test]
public async Task GetsProjects()
{
var projectResource = new ProjectResource
{
Count = 3,
value = new List<Project>
{
new Project
{
id = "eb6e4656-77fc-42a1-9181-4c6d8e9da5d1",
name = "Fabrikam-Fiber-TFVC",
description = "Team Foundation Version Control projects.",
url = "https://dev.azure.com/fabrikam/_apis/projects/eb6e4656-77fc-42a1-9181-4c6d8e9da5d1",
state = "wellFormed",
visibility = "private",
},
new Project
{
id = "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
name = "Fabrikam-Fiber-Git",
description = "Git projects.",
url = "https://dev.azure.com/fabrikam/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
state = "wellFormed",
visibility = "private",
revision = 51
},
new Project
{
id = "281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0",
name = "TestGit",
url = "https://dev.azure.com/fabrikam/_apis/projects/281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0",
state = "wellFormed",
visibility = "private",
revision = 2
}
}
};
var restClient = GetFakeClient(projectResource);
var projects = (await restClient.GetProjects()).ToList();
Assert.IsNotNull(projects);
Assert.IsTrue(projects.Count == 3);
}
[Test]
public async Task GetsGitRepositories()
{
var gitRepositories = new GitRepositories
{
count = 3,
value = new List<AzureRepository>
{
new AzureRepository
{
id = "5febef5a-833d-4e14-b9c0-14cb638f91e6",
name = "AnotherRepository",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/5febef5a-833d-4e14-b9c0-14cb638f91e6",
project = new Project
{
id = "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
name = "Fabrikam-Fiber-Git",
url = "https://dev.azure.com/fabrikam/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
state = "wellFormed"
},
remoteUrl = "https://dev.azure.com/fabrikam/Fabrikam-Fiber-Git/_git/AnotherRepository"
},
new AzureRepository
{
id = "278d5cd2-584d-4b63-824a-2ba458937249",
name = "Fabrikam-Fiber-Git",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249",
project = new Project
{
id = "6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
name = "Fabrikam-Fiber-Git",
url = "https://dev.azure.com/fabrikam/_apis/projects/6ce954b1-ce1f-45d1-b94d-e6bf2464ba2c",
state = "wellFormed"
},
remoteUrl = "https://dev.azure.com/fabrikam/_git/Fabrikam-Fiber-Git",
defaultBranch = "refs/heads/master"
},
new AzureRepository
{
id = "66efb083-777a-4cac-a350-a24b046be6be",
name = "AnotherRepository",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/66efb083-777a-4cac-a350-a24b046be6be",
project = new Project
{
id = "281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0",
name = "TestGit",
url = "https://dev.azure.com/fabrikam/_apis/projects/281f9a5b-af0d-49b4-a1df-fe6f5e5f84d0",
state = "wellFormed"
},
remoteUrl = "https://dev.azure.com/fabrikam/_git/TestGit",
defaultBranch = "refs/heads/master"
}
}
};
var restClient = GetFakeClient(gitRepositories);
var azureRepositories = (await restClient.GetGitRepositories("ProjectName")).ToList();
Assert.IsNotNull(azureRepositories);
Assert.IsTrue(azureRepositories.Count == 3);
}
[Test]
public async Task GetsGitRefs()
{
var gitRefsResource = new GitRefsResource
{
count = 3,
value = new List<GitRefs>
{
new GitRefs
{
name = "refs/heads/develop",
objectId = "67cae2b029dff7eb3dc062b49403aaedca5bad8d",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/develop"
},
new GitRefs
{
name = "refs/heads/master",
objectId = "23d0bc5b128a10056dc68afece360d8a0fabb014",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/heads/master"
},
new GitRefs
{
name = "refs/tags/v1.0",
objectId = "23d0bc5b128a10056dc68afece360d8a0fabb014",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/278d5cd2-584d-4b63-824a-2ba458937249/refs/tags/v1.0"
}
}
};
var restClient = GetFakeClient(gitRefsResource);
var gitRefs = (await restClient.GetRepositoryRefs("ProjectName", "RepoId")).ToList();
Assert.IsNotNull(gitRefs);
Assert.IsTrue(gitRefs.Count == 3);
}
[Test]
public async Task GetPullRequests()
{
var pullRequestResource = new PullRequestResource
{
Count = 1,
value = new[]
{
new PullRequest
{
AzureRepository = new AzureRepository
{
id = "3411ebc1-d5aa-464f-9615-0b527bc66719",
name = "2016_10_31",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/3411ebc1-d5aa-464f-9615-0b527bc66719",
project = new Project
{
id = "a7573007-bbb3-4341-b726-0c4148a07853",
name = "2016_10_31",
description = "test project created on Halloween 2016",
url = "https://dev.azure.com/fabrikam/_apis/projects/a7573007-bbb3-4341-b726-0c4148a07853",
state = "wellFormed",
revision = 7
},
remoteUrl = "https://dev.azure.com/fabrikam/_git/2016_10_31"
},
PullRequestId = 22,
CodeReviewId = 22,
Status = "active",
CreationDate = new DateTime(2016, 11, 01, 16, 30, 31),
Title = "A new feature",
Description = "Adding a new feature",
SourceRefName = "refs/heads/npaulk/my_work",
TargetRefName = "refs/heads/new_feature",
MergeStatus = "queued",
MergeId = "f5fc8381-3fb2-49fe-8a0d-27dcc2d6ef82",
Url = "https: //dev.azure.com/fabrikam/_apis/git/repositories/3411ebc1-d5aa-464f-9615-0b527bc66719/commits/b60280bc6e62e2f880f1b63c1e24987664d3bda3",
SupportsIterations = true,
}
}
};
var restClient = GetFakeClient(pullRequestResource);
var foundPullRequests = await restClient.GetPullRequests("ProjectName", "RepoId", "head", "base");
Assert.IsNotNull(foundPullRequests);
Assert.AreEqual(1, foundPullRequests.Count());
}
[Test]
public async Task CreatesPullRequest()
{
var pullRequest = new PullRequest
{
AzureRepository = new AzureRepository
{
id = "3411ebc1-d5aa-464f-9615-0b527bc66719",
name = "2016_10_31",
url = "https://dev.azure.com/fabrikam/_apis/git/repositories/3411ebc1-d5aa-464f-9615-0b527bc66719",
project = new Project
{
id = "a7573007-bbb3-4341-b726-0c4148a07853",
name = "2016_10_31",
description = "test project created on Halloween 2016",
url = "https://dev.azure.com/fabrikam/_apis/projects/a7573007-bbb3-4341-b726-0c4148a07853",
state = "wellFormed",
revision = 7
},
remoteUrl = "https://dev.azure.com/fabrikam/_git/2016_10_31"
},
PullRequestId = 22,
CodeReviewId = 22,
Status = "active",
CreationDate = new DateTime(2016, 11, 01, 16, 30, 31),
Title = "A new feature",
Description = "Adding a new feature",
SourceRefName = "refs/heads/npaulk/my_work",
TargetRefName = "refs/heads/new_feature",
MergeStatus = "queued",
MergeId = "f5fc8381-3fb2-49fe-8a0d-27dcc2d6ef82",
Url = "https: //dev.azure.com/fabrikam/_apis/git/repositories/3411ebc1-d5aa-464f-9615-0b527bc66719/commits/b60280bc6e62e2f880f1b63c1e24987664d3bda3",
SupportsIterations = true,
};
var restClient = GetFakeClient(pullRequest);
var request = new PRRequest { title = "A Pr" };
var createdPullRequest = await restClient.CreatePullRequest(request, "ProjectName", "RepoId");
Assert.IsNotNull(createdPullRequest);
}
[Test]
public async Task CreatesPullRequestLabel()
{
var labelResource = new LabelResource
{
value = new List<Label>
{
new Label
{
active = true,
id = "id",
name = "nukeeper"
}
}
};
var restClient = GetFakeClient(labelResource);
var request = new LabelRequest { name = "nukeeper" };
var pullRequestLabel = await restClient.CreatePullRequestLabel(request, "ProjectName", "RepoId", 100);
Assert.IsNotNull(pullRequestLabel);
}
[Test]
public async Task RetrievesFileNames()
{
var gitItemResource = new GitItemResource()
{
value = new List<GitItem>
{
new GitItem { path = "/src/file.cs"},
new GitItem { path = "/src/project.csproj"},
new GitItem { path = "/README.md"},
},
count = 3
};
var restClient = GetFakeClient(gitItemResource);
var request = new LabelRequest { name = "nukeeper" };
var fileNames = await restClient.GetGitRepositoryFileNames("ProjectName", "RepoId");
Assert.IsNotNull(fileNames);
Assert.That(fileNames, Is.EquivalentTo(new [] { "/src/file.cs", "/src/project.csproj", "/README.md"}));
}
[TestCase("proj/_apis/git/repositories/Id/pullrequests", false, "proj/_apis/git/repositories/Id/pullrequests?api-version=4.1")]
[TestCase("proj/_apis/git/repositories/Id/pullrequests", true, "proj/_apis/git/repositories/Id/pullrequests?api-version=4.1-preview.1")]
[TestCase("proj/_apis/git/repositories/Id/pullrequests?searchCriteria.sourceRefName=head", false, "proj/_apis/git/repositories/Id/pullrequests?searchCriteria.sourceRefName=head&api-version=4.1")]
[TestCase("proj/_apis/git/repositories/Id/pullrequests?searchCriteria.sourceRefName=head", true, "proj/_apis/git/repositories/Id/pullrequests?searchCriteria.sourceRefName=head&api-version=4.1-preview.1")]
public void BuildAzureDevOpsUri(string relativePath, bool previewApi, Uri expectedUri)
{
var uri = AzureDevOpsRestClient.BuildAzureDevOpsUri(relativePath, previewApi);
Assert.AreEqual(expectedUri, uri);
}
private static AzureDevOpsRestClient GetFakeClient(object returnObject)
{
var a = JsonConvert.SerializeObject(returnObject);
var fakeHttpMessageHandler = new FakeHttpMessageHandler(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(JsonConvert.SerializeObject(returnObject), Encoding.UTF8, "application/json")
});
var fakeHttpClient = new HttpClient(fakeHttpMessageHandler) { BaseAddress = new Uri("https://fakebaseAddress.com/") };
return new AzureDevOpsRestClient(fakeHttpClient, Substitute.For<INuKeeperLogger>(), "PAT");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using Telligent.Evolution.Components.Search;
using Telligent.Evolution.Extensibility.Api.Entities.Version1;
using Telligent.Evolution.Extensibility.Api.Version1;
using Telligent.Evolution.Extensibility.Content.Version1;
using Telligent.Evolution.Extensibility.Version1;
using Telligent.Evolution.Extensions.SharePoint.Client.Api.Version1;
using Telligent.Evolution.Extensions.SharePoint.Client.InternalApi;
using Telligent.Evolution.Extensions.SharePoint.Client.Plugins.Content.Search;
using Telligent.Evolution.Extensions.SharePoint.Components.Data.Log;
using PublicApi = Telligent.Evolution.Extensions.SharePoint.Client.Api.Version1.PublicApi;
using TEApi = Telligent.Evolution.Extensibility.Api.Version1.PublicApi;
namespace Telligent.Evolution.Extensions.SharePoint.Client.Plugins.Content.List
{
public class ItemContentType : ITranslatablePlugin, ISearchableContentType, IWebContextualContentType, ISecuredContentType, ISecuredCommentViewContentType, ICommentableContentType, ITaggableContentType, IRateableContentType, IViewableContentType
{
private static readonly IListItemService listItemService = ServiceLocator.Get<IListItemService>();
private static readonly IListDataService listDataService = ServiceLocator.Get<IListDataService>();
private static readonly IListItemDataService listItemDataService = ServiceLocator.Get<IListItemDataService>();
private ITranslatablePluginController translationController;
private IContentStateChanges contentStateChanges;
public static Guid Id { get { return new Guid("97F36A1D-F92F-4E44-AF7A-E30A3DD8B8E8"); } }
#region IPlugin Members
public string Name
{
get { return "List Item content type"; }
}
public string Description
{
get { return "Provides content type information for SharePoint List Items."; }
}
public void Initialize()
{
PublicApi.ListItems.Events.AfterCreate += EventsAfterCreate;
PublicApi.ListItems.Events.AfterUpdate += EventsAfterUpdate;
PublicApi.ListItems.Events.Render += EventsRender;
PublicApi.ListItems.Events.AfterDelete += EventsAfterDelete;
}
#endregion
#region ITranslatablePlugin Members
public Translation[] DefaultTranslations
{
get
{
var enUS = new Translation("en-us");
enUS.Set("content_type_name", "SharePoint List Item");
enUS.Set("application_no_permissions", "Permission denied");
enUS.Set("application_no_permissions_description", "Sorry access to this item has been denied by SharePoint.");
enUS.Set("application_short_type_name", "ListItem");
return new[] { enUS };
}
}
public void SetController(ITranslatablePluginController controller)
{
translationController = controller;
}
#endregion
#region IContentType Members
public Guid[] ApplicationTypes
{
get { return new[] { ListApplicationType.Id }; }
}
public Guid ContentTypeId
{
get { return Id; }
}
public string ContentTypeName
{
get { return translationController.GetLanguageResourceValue("content_type_name"); }
}
public void AttachChangeEvents(IContentStateChanges stateChanges)
{
contentStateChanges = stateChanges;
}
public IContent Get(Guid itemUniqueId)
{
var listId = EnsureListId(itemUniqueId);
if (listId != Guid.Empty)
{
return PublicApi.ListItems.Get(listId, new SPListItemGetOptions(itemUniqueId));
}
return null;
}
#endregion
#region ISecuredContentType Members
public Guid GetSecurableId(IContent content)
{
return content.Application.ApplicationId;
}
public Guid GetContentPermissionId(IContent content)
{
return ContentTypeId;
}
public Guid DefaultContentPermissionId
{
get { return ContentTypeId; }
}
public Guid DefaultPermissionId
{
get { return SharePointPermissionIds.ViewList; }
}
#endregion
#region ICommentableContentType Members
public bool CanCreateComment(Guid contentId, int userId)
{
return HasPermission(contentId, userId, SharePointPermissionIds.ViewList);
}
public bool CanDeleteComment(Guid commentId, int userId)
{
var comment = TEApi.Comments.Get(commentId);
return comment != null && HasPermission(comment.ContentId, userId, SharePointPermissionIds.ViewList);
}
public bool CanModifyComment(Guid commentId, int userId)
{
var comment = TEApi.Comments.Get(commentId);
return comment != null && HasPermission(comment.ContentId, userId, SharePointPermissionIds.ViewList);
}
public bool CanReadComment(Guid commentId, int userId)
{
return true;
}
#endregion
#region ISecuredCommentViewContentType Members
public Guid ContentPermissionId
{
get { return ContentTypeId; }
}
public Guid PermissionId
{
get { return SharePointPermissionIds.ViewList; }
}
#endregion
#region IRateableContentType Members
public bool CanDeleteRating(Guid contentId, int ratingUserId, int userId)
{
return HasPermission(contentId, userId, SharePointPermissionIds.ViewList);
}
public bool CanRate(Guid contentId, int userId)
{
return HasPermission(contentId, userId, SharePointPermissionIds.ViewList);
}
#endregion
#region ITaggableContentType Members
public bool CanAddTags(Guid contentId, int userId)
{
return HasPermission(contentId, userId, SharePointPermissionIds.ViewList);
}
public bool CanRemoveTags(Guid contentId, int userId)
{
return HasPermission(contentId, userId, SharePointPermissionIds.ViewList);
}
#endregion
#region ISearchableContentType Members
public IList<SearchIndexDocument> GetContentToIndex()
{
var searchDocuments = new List<SearchIndexDocument>();
var searchConfig = Telligent.Common.Services.Get<SearchConfiguration>();
var maxFileSizeInBytes = searchConfig.MaxAttachmentFileSizeMB * 1024 * 1024;
var credentialsManager = ServiceLocator.Get<ICredentialsManager>();
var items = listItemService.ListItemsToReindex(ListApplicationType.Id, 500);
foreach (var item in items)
{
var doc = TEApi.SearchIndexing.NewDocument(
item.ContentId,
Id,
"ListItem",
PublicApi.SharePointUrls.ListItem(item.ContentId),
item.DisplayName,
PublicApi.ListItems.Events.OnRender(item, "Description", item.DisplayName, "unknown"));
var list = PublicApi.Lists.Get(item.ListId);
doc.AddField(TEApi.SearchIndexing.Constants.RelatedId, item.ContentId.ToString());
doc.AddField(TEApi.SearchIndexing.Constants.IsContent, true.ToString());
doc.AddField(TEApi.SearchIndexing.Constants.ContentID, item.ContentId.ToString());
doc.AddField(TEApi.SearchIndexing.Constants.ApplicationId, list.Id.ToString());
doc.AddField(TEApi.SearchIndexing.Constants.GroupID, list.GroupId.ToString(CultureInfo.InvariantCulture));
doc.AddField(TEApi.SearchIndexing.Constants.ContainerId, list.Container.ContainerId.ToString());
doc.AddField(TEApi.SearchIndexing.Constants.CollapseField, string.Format("listitem:{0}", item.ContentId));
doc.AddField(TEApi.SearchIndexing.Constants.Date, TEApi.SearchIndexing.FormatDate(item.CreatedDate));
doc.AddField(TEApi.SearchIndexing.Constants.Category, "ListItems");
var user = TEApi.Users.Get(new UsersGetOptions { Email = item.Author.Email });
if (user != null && !user.HasErrors())
{
doc.AddField(TEApi.SearchIndexing.Constants.UserDisplayName, user.DisplayName);
doc.AddField(TEApi.SearchIndexing.Constants.Username, user.Username);
doc.AddField(TEApi.SearchIndexing.Constants.CreatedBy, user.DisplayName);
}
var tags = TEApi.Tags.Get(item.ContentId, Id, null);
if (tags != null)
{
foreach (var tag in tags)
{
doc.AddField(TEApi.SearchIndexing.Constants.TagKeyword, tag.TagName.ToLower());
doc.AddField(TEApi.SearchIndexing.Constants.Tag, tag.TagName);
}
}
foreach (var field in item.EditableFields())
{
if (field.FieldTypeKind == Microsoft.SharePoint.Client.FieldType.Attachments)
{
var webUrl = list.SPWebUrl.ToLowerInvariant();
var atachments = PublicApi.Attachments.List(item.ListId, new AttachmentsGetOptions(item.ContentId, field.InternalName));
foreach (var attachment in atachments)
{
string attachmentUrl = attachment.Uri.ToString().ToLowerInvariant();
if (attachmentUrl.StartsWith(webUrl))
{
string path = attachmentUrl.Replace(webUrl, string.Empty);
doc.AddField(string.Format("sp_{0}_{1}_name", field.InternalName.ToLowerInvariant(), attachment.Name.ToLowerInvariant()), attachment.Name);
doc.AddField(string.Format("sp_{0}_{1}_text", field.InternalName.ToLowerInvariant(), attachment.Name.ToLowerInvariant()), RemoteAttachment.GetText(webUrl, attachment.Name, path, credentialsManager, maxFileSizeInBytes));
}
}
}
else
{
var key = string.Format("sp_{0}", field.InternalName.ToLowerInvariant());
var value = item.ValueAsText(field.InternalName);
if (value != null)
{
doc.AddField(key, value.ToLowerInvariant());
}
}
}
searchDocuments.Add(doc);
}
return searchDocuments;
}
public int[] GetViewSecurityRoles(Guid contentId)
{
var listId = EnsureListId(contentId);
if (listId != Guid.Empty)
{
var listItem = PublicApi.ListItems.Get(listId, new SPListItemGetOptions(contentId));
if (listItem != null)
{
var list = PublicApi.Lists.Get(new SPListGetOptions(listId));
var group = TEApi.Groups.Get(new GroupsGetOptions { Id = list.GroupId });
var roles = TEApi.Roles.List(group.ApplicationId, SharePointPermissionIds.ViewLibrary);
return roles.Any() ? roles.Select(r => r.Id.GetValueOrDefault()).ToArray() : new int[0];
}
}
return new int[] { };
}
public bool IsCacheable
{
get { return true; }
}
public void SetIndexStatus(Guid[] contentIds, bool isIndexed)
{
listItemService.UpdateIndexingStatus(contentIds, isIndexed);
}
public bool VaryCacheByUser
{
get { return true; }
}
#endregion
#region IViewableContentType
public string GetViewHtml(IContent content, Target target)
{
if (content == null || content.ContentId == Guid.Empty) return null;
var contentId = content.ContentId;
var listId = EnsureListId(contentId);
if (listId != Guid.Empty)
{
var listItem = PublicApi.ListItems.Get(listId, new SPListItemGetOptions(contentId));
if (listItem != null)
{
var options = new RenderedSearchResultOptions
{
Target = target,
Title = listItem.DisplayName,
Url = PublicApi.SharePointUrls.ListItem(listItem.ContentId),
Date = listItem.CreatedDate,
ContainerName = content.Application.Container != null ? content.Application.Container.HtmlName(target.ToString()) : null,
ContainerUrl = content.Application.Container != null ? content.Application.Container.Url : null,
ApplicationName = content.Application.HtmlName(target.ToString()),
ApplicationUrl = PublicApi.SharePointUrls.BrowseDocuments(listItem.ListId),
TypeCssClass = "sharepoint-listItem",
User = content.CreatedByUserId.HasValue ? TEApi.Users.Get(new UsersGetOptions { Id = content.CreatedByUserId.Value }) : null,
RemoteAttachments = new List<RenderedSearchResultAttachment>(
PublicApi.Attachments.List(listItem.ListId, new AttachmentsGetOptions(listItem.ContentId, "Attachments"))
.Select(_ =>
new RenderedSearchResultAttachment
{
FileName = _.Name,
Url = _.Uri.ToString()
}))
};
return content.ToRenderedSearchResult(options);
}
}
return null;
}
#endregion
#region IWebContextualContentType
public IContent GetCurrentContent(Extensibility.UI.Version1.IWebContext context)
{
var contentId = SPCoreService.Context.ListItemId;
if (contentId != Guid.Empty)
{
return Get(contentId);
}
return null;
}
#endregion
#region Event handlers
private void EventsAfterCreate(ListItemAfterCreateEventArgs e)
{
}
private void EventsAfterUpdate(ListItemAfterUpdateEventArgs e)
{
if (contentStateChanges != null)
contentStateChanges.Updated(Get(e.ContentId));
SetIndexStatus(new[] { e.ContentId }, false);
}
private void EventsRender(ListItemRenderEventArgs e)
{
var content = new StringBuilder();
foreach (var field in e.EditableFields())
{
var value = e.ValueAsText(field.InternalName);
if (string.IsNullOrEmpty(value)) continue;
content.Append(string.Format(" {0}", value));
}
e.RenderedHtml = content.ToString();
}
private void EventsAfterDelete(ListItemAfterDeleteEventArgs e)
{
if (e.ContentId == Guid.Empty) return;
if (contentStateChanges != null)
contentStateChanges.Deleted(e.ContentId);
try
{
TEApi.Search.Delete(e.ContentId.ToString());
}
catch (Exception)
{
SPLog.Event(string.Format("Warning: Could not remove index for {0}", e.ContentId));
}
}
#endregion
internal static string ViewUrl(int groupId, Guid contentId)
{
return (groupId > 0) ? TEApi.Url.Adjust(TEApi.GroupUrls.Custom(groupId, "list-item"), string.Concat("itemId=", contentId.ToString())) : string.Empty;
}
internal static string EditUrl(int groupId, Guid contentId)
{
return (groupId > 0) ? TEApi.Url.Adjust(TEApi.GroupUrls.Custom(groupId, "list-item-create-edit"), string.Concat("itemId=", contentId.ToString())) : string.Empty;
}
internal static bool HasGroupPermission(int groupId, int userId, Guid permissionId)
{
var group = TEApi.Groups.Get(new GroupsGetOptions { Id = groupId });
var permission = TEApi.Permissions.Get(permissionId, userId, group.ContainerId, TEApi.Groups.ApplicationTypeId);
return (permission != null && permission.IsAllowed);
}
private bool HasPermission(Guid contentId, int userId, params Guid[] permissions)
{
var listId = EnsureListId(contentId);
if (listId != Guid.Empty)
{
var list = PublicApi.Lists.Get(listId);
if (list != null)
{
var groupId = list.GroupId;
return permissions.Aggregate(false, (hasPermission, permission) => hasPermission || HasGroupPermission(groupId, userId, permission));
}
}
return false;
}
#region Utility
private Guid EnsureListId(Guid itemUniqueId)
{
var listId = SPCoreService.Context.ListId;
if (listId != Guid.Empty) return listId;
var itemBase = listItemDataService.Get(itemUniqueId);
if (itemBase != null)
{
listId = itemBase.ApplicationId;
}
return listId;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using MyDownloader.App;
using MyDownloader.App.UI;
using MyDownloader.App.SingleInstancing;
using MyDownloader.Core;
using MyDownloader.Core.Extensions;
using MyDownloader.Core.UI;
using MyDownloader.Extension;
using MyDownloader.Extension.Protocols;
using MyDownloader.Extension.Notifications;
using MyDownloader.Extension.Video;
using MyDownloader.Extension.AutoDownloads;
using MyDownloader.Extension.SpeedLimit;
using MyDownloader.Extension.PersistedList;
using MyDownloader.Extension.WindowsIntegration;
namespace MyDownloader.App
{
[Serializable]
public class App : IApp
{
#region Singleton
private static App instance = new App();
public static App Instance
{
get
{
return instance;
}
}
private App()
{
AppManager.Instance.Initialize(this);
extensions = new List<IExtension>();
extensions.Add(new CoreExtention());
extensions.Add(new HttpFtpProtocolExtension());
extensions.Add(new VideoDownloadExtension());
extensions.Add(new PersistedListExtension());
extensions.Add(new NotificationsExtension());
extensions.Add(new AutoDownloadsExtension());
extensions.Add(new WindowsIntegrationExtension());
}
#endregion
#region Fields
private List<IExtension> extensions;
private SingleInstanceTracker tracker = null;
private bool disposed = false;
#endregion
#region Properties
public Form MainForm
{
get
{
return (MainDownloadForm)tracker.Enforcer;
}
}
public List<IExtension> Extensions
{
get
{
return extensions;
}
}
#endregion
#region Methods
public IExtension GetExtensionByType(Type type)
{
for (int i = 0; i < this.extensions.Count; i++)
{
if (this.extensions[i].GetType() == type)
{
return this.extensions[i];
}
}
return null;
}
private ISingleInstanceEnforcer GetSingleInstanceEnforcer()
{
return new MainDownloadForm();
}
public void InitExtensions()
{
for (int i = 0; i < Extensions.Count; i++)
{
if (Extensions[i] is IInitializable)
{
((IInitializable)Extensions[i]).Init();
}
}
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
for (int i = 0; i < Extensions.Count; i++)
{
if (Extensions[i] is IDisposable)
{
try
{
((IDisposable)Extensions[i]).Dispose();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
}
}
}
public void Start()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
{
// Attempt to create a tracker
tracker = new SingleInstanceTracker("SingleInstanceSample", new SingleInstanceEnforcerRetriever(GetSingleInstanceEnforcer));
// If this is the first instance of the application, run the main form
if (tracker.IsFirstInstance)
{
try
{
MainDownloadForm form = (MainDownloadForm)tracker.Enforcer;
//form.downloadList1.AddDownloadURLs(ResourceLocation.FromURLArray(args), 1, null, 0);
form.Load += delegate(object sender, EventArgs e)
{
InitExtensions();
if (form.WindowState == FormWindowState.Minimized)
{
form.HideForm();
}
};
form.FormClosing += delegate(object sender, FormClosingEventArgs e)
{
Dispose();
};
Application.Run(form);
}
finally
{
Dispose();
}
}
else
{
// This is not the first instance of the application, so do nothing but send a message to the first instance
}
}
catch (SingleInstancingException ex)
{
MessageBox.Show("Could not create a SingleInstanceTracker object:\n" + ex.Message + "\nApplication will now terminate.\n" + ex.InnerException.ToString());
return;
}
finally
{
if (tracker != null)
tracker.Dispose();
}
}
#endregion
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) 2014 Microsoft Corporation
//
// 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.
// ------------------------------------------------------------------------------
namespace Microsoft.Live
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Security.Authentication.Web;
using Microsoft.Live.Operations;
public partial class LiveAuthClient
{
private const string SignInOfferName = "wl.signin";
private List<string> currentScopes;
private ThemeType? theme;
#region Constructor
/// <summary>
/// Creates a new instance of the auth client. Takes no parameters.
/// The application client id is the same as the application package sid.
/// </summary>
public LiveAuthClient()
: this(null)
{
}
/// <summary>
/// Creates a new instance of the auth client.
/// The application client id is the same as the application package sid.
/// </summary>
/// <param name="redirectUri">The application's redirect uri as specified in application management portal.</param>
public LiveAuthClient(string redirectUri)
{
if (!string.IsNullOrEmpty(redirectUri) && !IsValidRedirectDomain(redirectUri))
{
throw new ArgumentException(
redirectUri,
String.Format(CultureInfo.CurrentUICulture, ResourceHelper.GetString("UrlInvalid"), "redirectUri"));
}
this.AuthClient = new TailoredAuthClient(this);
if (string.IsNullOrEmpty(redirectUri))
{
redirectUri = TailoredAuthClient.Win8ReturnUriScheme;
}
this.InitializeMembers(string.Empty, redirectUri);
}
#endregion
#region Properties
/// <summary>
/// Gets and sets the theme used for the consent request.
/// </summary>
public ThemeType Theme
{
get
{
if (!this.theme.HasValue)
{
this.theme = Platform.GetThemeType();
}
return this.theme.Value;
}
set
{
this.theme = value;
}
}
/// <summary>
/// Gets whether or not sign out is supported for the logged in user.
/// </summary>
/// <remarks>Sign out is only supported for non-connected user accounts.</remarks>
public bool CanLogout
{
get
{
return this.AuthClient.CanSignOut;
}
}
#endregion
#region Public Methods
/// <summary>
/// Initializes the auth client. Detects if user is already signed in,
/// If user is already signed in, creates a valid Session.
/// This call is UI-less.
/// </summary>
public Task<LiveLoginResult> InitializeAsync()
{
return this.InitializeAsync(new List<string>());
}
/// <summary>
/// Initializes the auth client. Detects if user is already signed in,
/// If user is already signed in, creates a valid Session.
/// This call is UI-less.
/// </summary>
/// <param name="scopes">The list of offers that the application is requesting user consent for.</param>
public Task<LiveLoginResult> InitializeAsync(IEnumerable<string> scopes)
{
if (scopes != null)
{
return InitializeAsync(scopes.ToArray());
}
else
{
return InitializeAsync(null);
}
}
/// <summary>
/// Initializes the auth client. Detects if user is already signed in,
/// If user is already signed in, creates a valid Session.
/// This call is UI-less.
/// </summary>
/// <param name="scopes"></param>
/// <returns></returns>
public Task<LiveLoginResult> InitializeAsync(params string[] scopes)
{
if (scopes == null)
{
throw new ArgumentNullException("scopes");
}
return this.ExecuteAuthTaskAsync(scopes, true);
}
/// <summary>
/// Displays the login/consent UI and returns a Session object when user completes the auth flow.
/// </summary>
/// <param name="scopes">The list of offers that the application is requesting user consent for.</param>
public Task<LiveLoginResult> LoginAsync(IEnumerable<string> scopes)
{
if (scopes != null)
{
return LoginAsync(scopes.ToArray());
}
else
{
return LoginAsync(null);
}
}
/// <summary>
/// Displays the login/consent UI and returns a Session object when user completes the auth flow.
/// </summary>
/// <param name="scopes">The list of offers that the application is requesting user consent for.</param>
public Task<LiveLoginResult> LoginAsync(params string[] scopes)
{
if (scopes == null && this.scopes == null)
{
throw new ArgumentNullException("scopes");
}
return this.ExecuteAuthTaskAsync(scopes, false);
}
/// <summary>
/// Logs user out of the application. Clears any cached Session data.
/// </summary>
public void Logout()
{
if (!this.CanLogout)
{
throw new LiveConnectException(ApiOperation.ApiClientErrorCode, ResourceHelper.GetString("CantLogout"));
}
this.AuthClient.CloseSession();
}
#endregion
#region Internal/Private Methods
/// <summary>
/// Creates a LiveConnectSession object based on the parsed response.
/// </summary>
internal static LiveConnectSession CreateSession(LiveAuthClient client, IDictionary<string, object> result)
{
var session = new LiveConnectSession(client);
Debug.Assert(result.ContainsKey(AuthConstants.AccessToken));
if (result.ContainsKey(AuthConstants.AccessToken))
{
session.AccessToken = result[AuthConstants.AccessToken] as string;
if (result.ContainsKey(AuthConstants.AuthenticationToken))
{
session.AuthenticationToken = result[AuthConstants.AuthenticationToken] as string;
}
}
return session;
}
/// <summary>
/// Gets current user login status.
/// </summary>
/// <returns></returns>
internal async Task<LiveLoginResult> GetLoginStatusAsync()
{
LiveLoginResult result = await this.AuthClient.AuthenticateAsync(
LiveAuthClient.BuildScopeString(this.currentScopes),
true);
if (result.Status == LiveConnectSessionStatus.NotConnected &&
this.currentScopes.Count > 1)
{
// The user might have revoked one of the scopes while the app is running. Try getting a token for the remaining scopes
// by passing in only the "wl.signin" scope. The server should return a token that contains all remaining scopes.
this.currentScopes = new List<string>(new string[] { LiveAuthClient.SignInOfferName });
result = await this.AuthClient.AuthenticateAsync(
LiveAuthClient.BuildScopeString(this.currentScopes),
true);
}
if (result.Status == LiveConnectSessionStatus.Unknown)
{
// If the auth result indicates that the current account is not connected, we should clear the session
this.Session = null;
}
else if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session))
{
this.Session = result.Session;
}
return result;
}
/// <summary>
/// Retrieve a new access token based on current session information.
/// </summary>
internal bool RefreshToken(Action<LiveLoginResult> completionCallback)
{
this.TryRefreshToken(completionCallback);
return true;
}
private async Task<LiveLoginResult> ExecuteAuthTaskAsync(IEnumerable<string> scopes, bool silent)
{
if (scopes != null)
{
this.scopes = new List<string>(scopes);
}
this.EnsureSignInScope();
this.PrepareForAsync();
LiveLoginResult result = await this.AuthClient.AuthenticateAsync(
LiveAuthClient.BuildScopeString(this.scopes),
silent);
if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session))
{
this.MergeScopes();
this.Session = result.Session;
}
Interlocked.Decrement(ref this.asyncInProgress);
if (result.Error != null)
{
throw result.Error;
}
return result;
}
private static bool AreSessionsSame(LiveConnectSession session1, LiveConnectSession session2)
{
if (session1 != null && session2 != null)
{
return
session1.AccessToken == session2.AccessToken &&
session1.AuthenticationToken == session2.AuthenticationToken;
}
return session1 == session2;
}
private static bool IsValidRedirectDomain(string redirectDomain)
{
if (!redirectDomain.StartsWith("https://", StringComparison.OrdinalIgnoreCase) &&
!redirectDomain.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
{
return false;
}
try
{
var redirectUri = new Uri(redirectDomain, UriKind.Absolute);
return redirectUri.IsWellFormedOriginalString();
}
catch (FormatException)
{
return false;
}
}
private void EnsureSignInScope()
{
Debug.Assert(this.scopes != null);
if (string.IsNullOrEmpty(this.scopes.Find(s => string.CompareOrdinal(s, LiveAuthClient.SignInOfferName) == 0)))
{
this.scopes.Insert(0, LiveAuthClient.SignInOfferName);
}
}
private string GetAppPackageSid()
{
Uri redirectUri = WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
Debug.Assert(redirectUri != null);
return redirectUri.AbsoluteUri;
}
private void MergeScopes()
{
Debug.Assert(this.scopes != null);
if (this.currentScopes == null)
{
this.currentScopes = new List<string>(this.scopes);
return;
}
foreach (string newScope in this.scopes)
{
if (!this.currentScopes.Contains(newScope))
{
this.currentScopes.Add(newScope);
}
}
}
private async void TryRefreshToken(Action<LiveLoginResult> completionCallback)
{
LiveLoginResult result = await this.AuthClient.AuthenticateAsync(
LiveAuthClient.BuildScopeString(this.currentScopes),
true);
if (result.Status == LiveConnectSessionStatus.NotConnected &&
this.currentScopes.Count > 1)
{
// The user might have revoked one of the scopes while the app is running. Try getting a token for the remaining scopes
// by passing in only the "wl.signin" scope. The server should return a token that contains all remaining scopes.
this.currentScopes = new List<string>(new string[] { LiveAuthClient.SignInOfferName });
result = await this.AuthClient.AuthenticateAsync(
LiveAuthClient.BuildScopeString(this.currentScopes),
true);
}
if (result.Status == LiveConnectSessionStatus.Unknown)
{
// If the auth result indicates that the current account is not connected, we should clear the session
this.Session = null;
}
else if (result.Session != null && !LiveAuthClient.AreSessionsSame(this.Session, result.Session))
{
this.Session = result.Session;
}
completionCallback(result);
}
#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.
/*=============================================================================
**
**
**
** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded
** program.
**
**
=============================================================================*/
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
public static class Monitor
{
#region Object->Lock/Condition mapping
#if !FEATURE_SYNCTABLE
private static ConditionalWeakTable<object, Lock> s_lockTable = new ConditionalWeakTable<object, Lock>();
private static ConditionalWeakTable<object, Lock>.CreateValueCallback s_createLock = (o) => new Lock();
#endif
private static ConditionalWeakTable<object, Condition> s_conditionTable = new ConditionalWeakTable<object, Condition>();
private static ConditionalWeakTable<object, Condition>.CreateValueCallback s_createCondition = (o) => new Condition(GetLock(o));
internal static Lock GetLock(object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
Debug.Assert(!(obj is Lock),
"Do not use Monitor.Enter or TryEnter on a Lock instance; use Lock methods directly instead.");
#if FEATURE_SYNCTABLE
return ObjectHeader.GetLockObject(obj);
#else
return s_lockTable.GetValue(obj, s_createLock);
#endif
}
private static Condition GetCondition(object obj)
{
Debug.Assert(
!(obj is Condition || obj is Lock),
"Do not use Monitor.Pulse or Wait on a Lock or Condition instance; use the methods on Condition instead.");
return s_conditionTable.GetValue(obj, s_createCondition);
}
#endregion
#region Public Enter/Exit methods
public static void Enter(object obj)
{
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
return;
TryAcquireContended(lck, obj, Timeout.Infinite);
}
public static void Enter(object obj, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
{
lockTaken = true;
return;
}
TryAcquireContended(lck, obj, Timeout.Infinite);
lockTaken = true;
}
public static bool TryEnter(object obj)
{
return GetLock(obj).TryAcquire(0);
}
public static void TryEnter(object obj, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
lockTaken = GetLock(obj).TryAcquire(0);
}
public static bool TryEnter(object obj, int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
return true;
return TryAcquireContended(lck, obj, millisecondsTimeout);
}
public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken)
{
if (lockTaken)
throw new ArgumentException(SR.Argument_MustBeFalse, nameof(lockTaken));
if (millisecondsTimeout < -1)
throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
Lock lck = GetLock(obj);
if (lck.TryAcquire(0))
{
lockTaken = true;
return;
}
lockTaken = TryAcquireContended(lck, obj, millisecondsTimeout);
}
public static bool TryEnter(object obj, TimeSpan timeout) =>
TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken) =>
TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken);
public static void Exit(object obj)
{
GetLock(obj).Release();
}
public static bool IsEntered(object obj)
{
return GetLock(obj).IsAcquired;
}
#endregion
#region Public Wait/Pulse methods
// Remoting is not supported, ignore exitContext
public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) =>
Wait(obj, millisecondsTimeout);
// Remoting is not supported, ignore exitContext
public static bool Wait(object obj, TimeSpan timeout, bool exitContext) =>
Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static bool Wait(object obj, int millisecondsTimeout)
{
Condition condition = GetCondition(obj);
DebugBlockingItem blockingItem;
using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorEvent, millisecondsTimeout, out blockingItem))
{
return condition.Wait(millisecondsTimeout);
}
}
public static bool Wait(object obj, TimeSpan timeout) => Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout));
public static bool Wait(object obj) => Wait(obj, Timeout.Infinite);
public static void Pulse(object obj)
{
GetCondition(obj).SignalOne();
}
public static void PulseAll(object obj)
{
GetCondition(obj).SignalAll();
}
#endregion
#region Slow path for Entry/TryEnter methods.
internal static bool TryAcquireContended(Lock lck, object obj, int millisecondsTimeout)
{
DebugBlockingItem blockingItem;
using (new DebugBlockingScope(obj, DebugBlockingItemType.MonitorCriticalSection, millisecondsTimeout, out blockingItem))
{
return lck.TryAcquire(millisecondsTimeout);
}
}
#endregion
#region Debugger support
// The debugger binds to the fields below by name. Do not change any names or types without
// updating the debugger!
// The head of the list of DebugBlockingItem stack objects used by the debugger to implement
// ICorDebugThread4::GetBlockingObjects. Usually the list either is empty or contains a single
// item. However, a wait on an STA thread may reenter via the message pump and cause the thread
// to be blocked on a second object.
[ThreadStatic]
private static IntPtr t_firstBlockingItem;
// Different ways a thread can be blocked that the debugger will expose.
// Do not change or add members without updating the debugger code.
private enum DebugBlockingItemType
{
MonitorCriticalSection = 0,
MonitorEvent = 1
}
// Represents an item a thread is blocked on. This structure is allocated on the stack and accessed by the debugger.
// Fields are volatile to avoid potential compiler optimizations.
private struct DebugBlockingItem
{
// The object the thread is waiting on
public volatile object _object;
// Indicates how the thread is blocked on the item
public volatile DebugBlockingItemType _blockingType;
// Blocking timeout in milliseconds or Timeout.Infinite for no timeout
public volatile int _timeout;
// Next pointer in the linked list of DebugBlockingItem records
public volatile IntPtr _next;
}
private unsafe struct DebugBlockingScope : IDisposable
{
public DebugBlockingScope(object obj, DebugBlockingItemType blockingType, int timeout, out DebugBlockingItem blockingItem)
{
blockingItem._object = obj;
blockingItem._blockingType = blockingType;
blockingItem._timeout = timeout;
blockingItem._next = t_firstBlockingItem;
t_firstBlockingItem = (IntPtr)Unsafe.AsPointer(ref blockingItem);
}
public void Dispose()
{
t_firstBlockingItem = Unsafe.Read<DebugBlockingItem>((void*)t_firstBlockingItem)._next;
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections.Generic;
using System.Threading;
namespace OpenSim.Framework
{
/// <summary>
/// Manage client circuits
/// </summary>
public class AgentCircuitManager
{
/// <summary>
/// Agent circuits indexed by circuit code.
/// </summary>
/// <remarks>
/// We lock this for operations both on this dictionary and on m_agentCircuitsByUUID
/// </remarks>
private ThreadedClasses.RwLockedDoubleDictionary<uint, UUID, AgentCircuitData> m_agentCircuits = new ThreadedClasses.RwLockedDoubleDictionary<uint, UUID, AgentCircuitData>();
public virtual AuthenticateResponse AuthenticateSession(UUID sessionID, UUID agentID, uint circuitcode)
{
AgentCircuitData validcircuit = null;
AuthenticateResponse user = new AuthenticateResponse();
try
{
validcircuit = m_agentCircuits[circuitcode];
}
catch(KeyNotFoundException)
{
//don't have this circuit code in our list
user.Authorised = false;
return user;
}
if ((sessionID == validcircuit.SessionID) && (agentID == validcircuit.AgentID))
{
user.Authorised = true;
user.LoginInfo = new Login();
user.LoginInfo.Agent = agentID;
user.LoginInfo.Session = sessionID;
user.LoginInfo.SecureSession = validcircuit.SecureSessionID;
user.LoginInfo.First = validcircuit.firstname;
user.LoginInfo.Last = validcircuit.lastname;
user.LoginInfo.InventoryFolder = validcircuit.InventoryFolder;
user.LoginInfo.BaseFolder = validcircuit.BaseFolder;
user.LoginInfo.StartPos = validcircuit.startpos;
}
else
{
// Invalid
user.Authorised = false;
}
return user;
}
/// <summary>
/// Add information about a new circuit so that later on we can authenticate a new client session.
/// </summary>
/// <param name="circuitCode"></param>
/// <param name="agentData"></param>
public virtual void AddNewCircuit(uint circuitCode, AgentCircuitData agentData)
{
try
{
m_agentCircuits.Add(circuitCode, agentData.AgentID, agentData);
}
catch(ArgumentException)
{
m_agentCircuits.Remove(circuitCode);
m_agentCircuits.Remove(agentData.AgentID);
m_agentCircuits.Add(circuitCode, agentData.AgentID, agentData);
}
}
public virtual void RemoveCircuit(uint circuitCode)
{
m_agentCircuits.Remove(circuitCode);
}
public virtual void RemoveCircuit(UUID agentID)
{
m_agentCircuits.Remove(agentID);
}
public AgentCircuitData GetAgentCircuitData(uint circuitCode)
{
AgentCircuitData agentCircuit = null;
m_agentCircuits.TryGetValue(circuitCode, out agentCircuit);
return agentCircuit;
}
public AgentCircuitData GetAgentCircuitData(UUID agentID)
{
AgentCircuitData agentCircuit = null;
m_agentCircuits.TryGetValue(agentID, out agentCircuit);
return agentCircuit;
}
/// <summary>
/// Get all current agent circuits indexed by agent UUID.
/// </summary>
/// <returns></returns>
public Dictionary<UUID, AgentCircuitData> GetAgentCircuits()
{
Dictionary<UUID, AgentCircuitData> val;
m_agentCircuits.CopyTo(out val);
return val;
}
public void UpdateAgentData(AgentCircuitData agentData)
{
AgentCircuitData circuit;
try
{
circuit = m_agentCircuits[agentData.circuitcode];
}
catch(KeyNotFoundException)
{
return;
}
circuit.firstname = agentData.firstname;
circuit.lastname = agentData.lastname;
circuit.startpos = agentData.startpos;
/* Updated for when we don't know them before calling Scene.NewUserConnection */
circuit.SecureSessionID = agentData.SecureSessionID;
circuit.SessionID = agentData.SessionID;
}
/// <summary>
/// Sometimes the circuitcode may not be known before setting up the connection
/// </summary>
/// <param name="circuitcode"></param>
/// <param name="newcircuitcode"></param>
public bool TryChangeCiruitCode(uint circuitcode, uint newcircuitcode)
{
try
{
m_agentCircuits.ChangeKey(newcircuitcode, circuitcode);
return true;
}
catch(Exception)
{
return false;
}
}
public void UpdateAgentChildStatus(uint circuitcode, bool childstatus)
{
try
{
m_agentCircuits[circuitcode].child = childstatus;
}
catch(KeyNotFoundException)
{
}
}
public bool GetAgentChildStatus(uint circuitcode)
{
try
{
return m_agentCircuits[circuitcode].child;
}
catch(KeyNotFoundException)
{
return false;
}
}
}
}
| |
//Copyright (c) Service Stack LLC. All Rights Reserved.
//License: https://raw.github.com/ServiceStack/ServiceStack/master/license.txt
using System;
using System.Globalization;
using System.IO;
using ServiceStack.Text.Common;
using ServiceStack.Text.Json;
namespace ServiceStack.Text.Jsv
{
public class JsvTypeSerializer
: ITypeSerializer
{
public static ITypeSerializer Instance = new JsvTypeSerializer();
public bool IncludeNullValues
{
get { return false; } //Doesn't support null values, treated as "null" string literal
}
public string TypeAttrInObject
{
get { return JsConfig.JsvTypeAttrInObject; }
}
internal static string GetTypeAttrInObject(string typeAttr)
{
return string.Format("{{{0}:", typeAttr);
}
public WriteObjectDelegate GetWriteFn<T>()
{
return JsvWriter<T>.WriteFn();
}
public WriteObjectDelegate GetWriteFn(Type type)
{
return JsvWriter.GetWriteFn(type);
}
static readonly TypeInfo DefaultTypeInfo = new TypeInfo { EncodeMapKey = false };
public TypeInfo GetTypeInfo(Type type)
{
return DefaultTypeInfo;
}
public void WriteRawString(TextWriter writer, string value)
{
writer.Write(value.EncodeJsv());
}
public void WritePropertyName(TextWriter writer, string value)
{
writer.Write(value);
}
public void WriteBuiltIn(TextWriter writer, object value)
{
writer.Write(value);
}
public void WriteObjectString(TextWriter writer, object value)
{
if (value != null)
{
var strValue = value as string;
if (strValue != null)
{
WriteString(writer, strValue);
}
else
{
writer.Write(value.ToString().EncodeJsv());
}
}
}
public void WriteException(TextWriter writer, object value)
{
writer.Write(((Exception)value).Message.EncodeJsv());
}
public void WriteString(TextWriter writer, string value)
{
if(JsState.QueryStringMode && !string.IsNullOrEmpty(value) && value.StartsWith(JsWriter.QuoteString) && value.EndsWith(JsWriter.QuoteString))
value = String.Concat(JsWriter.QuoteChar, value, JsWriter.QuoteChar);
else if (JsState.QueryStringMode && !string.IsNullOrEmpty(value) && value.Contains(JsWriter.ItemSeperatorString))
value = String.Concat(JsWriter.QuoteChar, value, JsWriter.QuoteChar);
writer.Write(value == "" ? "\"\"" : value.EncodeJsv());
}
public void WriteFormattableObjectString(TextWriter writer, object value)
{
var f = (IFormattable)value;
writer.Write(f.ToString(null,CultureInfo.InvariantCulture).EncodeJsv());
}
public void WriteDateTime(TextWriter writer, object oDateTime)
{
var dateTime = (DateTime)oDateTime;
switch (JsConfig.DateHandler)
{
case DateHandler.UnixTime:
writer.Write(dateTime.ToUnixTime());
return;
case DateHandler.UnixTimeMs:
writer.Write(dateTime.ToUnixTimeMs());
return;
}
writer.Write(DateTimeSerializer.ToShortestXsdDateTimeString((DateTime)oDateTime));
}
public void WriteNullableDateTime(TextWriter writer, object dateTime)
{
if (dateTime == null) return;
WriteDateTime(writer, dateTime);
}
public void WriteDateTimeOffset(TextWriter writer, object oDateTimeOffset)
{
writer.Write(((DateTimeOffset) oDateTimeOffset).ToString("o"));
}
public void WriteNullableDateTimeOffset(TextWriter writer, object dateTimeOffset)
{
if (dateTimeOffset == null) return;
this.WriteDateTimeOffset(writer, dateTimeOffset);
}
public void WriteTimeSpan(TextWriter writer, object oTimeSpan)
{
writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan)oTimeSpan));
}
public void WriteNullableTimeSpan(TextWriter writer, object oTimeSpan)
{
if (oTimeSpan == null) return;
writer.Write(DateTimeSerializer.ToXsdTimeSpanString((TimeSpan?)oTimeSpan));
}
public void WriteGuid(TextWriter writer, object oValue)
{
writer.Write(((Guid)oValue).ToString("N"));
}
public void WriteNullableGuid(TextWriter writer, object oValue)
{
if (oValue == null) return;
writer.Write(((Guid)oValue).ToString("N"));
}
public void WriteBytes(TextWriter writer, object oByteValue)
{
if (oByteValue == null) return;
writer.Write(Convert.ToBase64String((byte[])oByteValue));
}
public void WriteChar(TextWriter writer, object charValue)
{
if (charValue == null) return;
writer.Write((char)charValue);
}
public void WriteByte(TextWriter writer, object byteValue)
{
if (byteValue == null) return;
writer.Write((byte)byteValue);
}
public void WriteInt16(TextWriter writer, object intValue)
{
if (intValue == null) return;
writer.Write((short)intValue);
}
public void WriteUInt16(TextWriter writer, object intValue)
{
if (intValue == null) return;
writer.Write((ushort)intValue);
}
public void WriteInt32(TextWriter writer, object intValue)
{
if (intValue == null) return;
writer.Write((int)intValue);
}
public void WriteUInt32(TextWriter writer, object uintValue)
{
if (uintValue == null) return;
writer.Write((uint)uintValue);
}
public void WriteUInt64(TextWriter writer, object ulongValue)
{
if (ulongValue == null) return;
writer.Write((ulong)ulongValue);
}
public void WriteInt64(TextWriter writer, object longValue)
{
if (longValue == null) return;
writer.Write((long)longValue);
}
public void WriteBool(TextWriter writer, object boolValue)
{
if (boolValue == null) return;
writer.Write((bool)boolValue);
}
public void WriteFloat(TextWriter writer, object floatValue)
{
if (floatValue == null) return;
var floatVal = (float)floatValue;
if (Equals(floatVal, float.MaxValue) || Equals(floatVal, float.MinValue))
writer.Write(floatVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(floatVal.ToString(CultureInfo.InvariantCulture));
}
public void WriteDouble(TextWriter writer, object doubleValue)
{
if (doubleValue == null) return;
var doubleVal = (double)doubleValue;
if (Equals(doubleVal, double.MaxValue) || Equals(doubleVal, double.MinValue))
writer.Write(doubleVal.ToString("r", CultureInfo.InvariantCulture));
else
writer.Write(doubleVal.ToString(CultureInfo.InvariantCulture));
}
public void WriteDecimal(TextWriter writer, object decimalValue)
{
if (decimalValue == null) return;
writer.Write(((decimal)decimalValue).ToString(CultureInfo.InvariantCulture));
}
public void WriteEnum(TextWriter writer, object enumValue)
{
if (enumValue == null) return;
if (JsConfig.TreatEnumAsInteger)
JsWriter.WriteEnumFlags(writer, enumValue);
else
writer.Write(enumValue.ToString());
}
public void WriteEnumFlags(TextWriter writer, object enumFlagValue)
{
JsWriter.WriteEnumFlags(writer, enumFlagValue);
}
public void WriteLinqBinary(TextWriter writer, object linqBinaryValue)
{
#if !(__IOS__ || SL5 || XBOX || ANDROID || PCL)
WriteRawString(writer, Convert.ToBase64String(((System.Data.Linq.Binary)linqBinaryValue).ToArray()));
#endif
}
public object EncodeMapKey(object value)
{
return value;
}
public ParseStringDelegate GetParseFn<T>()
{
return JsvReader.Instance.GetParseFn<T>();
}
public ParseStringDelegate GetParseFn(Type type)
{
return JsvReader.GetParseFn(type);
}
public string UnescapeSafeString(string value)
{
return value.FromCsvField();
}
public string ParseRawString(string value)
{
return value;
}
public string ParseString(string value)
{
return value.FromCsvField();
}
public string UnescapeString(string value)
{
return value.FromCsvField();
}
public string EatTypeValue(string value, ref int i)
{
return EatValue(value, ref i);
}
public bool EatMapStartChar(string value, ref int i)
{
var success = value[i] == JsWriter.MapStartChar;
if (success) i++;
return success;
}
public string EatMapKey(string value, ref int i)
{
var tokenStartPos = i;
var valueLength = value.Length;
var valueChar = value[tokenStartPos];
switch (valueChar)
{
case JsWriter.QuoteChar:
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar != JsWriter.QuoteChar) continue;
var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar;
i++; //skip quote
if (!isLiteralQuote)
break;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
//Is Type/Map, i.e. {...}
case JsWriter.MapStartChar:
var endsToEat = 1;
var withinQuotes = false;
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.MapStartChar)
endsToEat++;
if (valueChar == JsWriter.MapEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
while (value[++i] != JsWriter.MapKeySeperator) { }
return value.Substring(tokenStartPos, i - tokenStartPos);
}
public bool EatMapKeySeperator(string value, ref int i)
{
return value[i++] == JsWriter.MapKeySeperator;
}
public bool EatItemSeperatorOrMapEndChar(string value, ref int i)
{
if (i == value.Length) return false;
var success = value[i] == JsWriter.ItemSeperator
|| value[i] == JsWriter.MapEndChar;
i++;
return success;
}
public void EatWhitespace(string value, ref int i)
{
}
public string EatValue(string value, ref int i)
{
var tokenStartPos = i;
var valueLength = value.Length;
if (i == valueLength) return null;
var valueChar = value[i];
var withinQuotes = false;
var endsToEat = 1;
switch (valueChar)
{
//If we are at the end, return.
case JsWriter.ItemSeperator:
case JsWriter.MapEndChar:
return null;
//Is Within Quotes, i.e. "..."
case JsWriter.QuoteChar:
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar != JsWriter.QuoteChar) continue;
var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar;
i++; //skip quote
if (!isLiteralQuote)
break;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
//Is Type/Map, i.e. {...}
case JsWriter.MapStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.MapStartChar)
endsToEat++;
if (valueChar == JsWriter.MapEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
//Is List, i.e. [...]
case JsWriter.ListStartChar:
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.ListStartChar)
endsToEat++;
if (valueChar == JsWriter.ListEndChar)
endsToEat--;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
//Is Value
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar == JsWriter.ItemSeperator
|| valueChar == JsWriter.MapEndChar)
{
break;
}
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.