context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Security.Principal; using Microsoft.SharePoint; using Microsoft.SharePoint.Administration; using WebsitePanel.Providers.SharePoint; using WebsitePanel.Providers.Utils; namespace WebsitePanel.Providers.HostedSolution { public class HostedSharePointServer2013Impl : MarshalByRefObject { #region Fields private static RunspaceConfiguration runspaceConfiguration; #endregion #region Properties private string SharepointSnapInName { get { return "Microsoft.SharePoint.Powershell"; } } #endregion #region Methods /// <summary>Gets list of SharePoint collections within root web application.</summary> /// <param name="rootWebApplicationUri"> The root web application Uri. </param> /// <returns>List of SharePoint collections within root web application.</returns> public SharePointSiteCollection[] GetSiteCollections(Uri rootWebApplicationUri) { return GetSPSiteCollections(rootWebApplicationUri).Select(pair => NewSiteCollection(pair.Value)).ToArray(); } /// <summary>Gets list of supported languages by this installation of SharePoint.</summary> /// <param name="rootWebApplicationUri"> The root web application Uri. </param> /// <returns>List of supported languages</returns> public int[] GetSupportedLanguages(Uri rootWebApplicationUri) { var languages = new List<int>(); try { WindowsImpersonationContext wic = WindowsIdentity.GetCurrent().Impersonate(); try { languages.AddRange(from SPLanguage lang in SPRegionalSettings.GlobalInstalledLanguages select lang.LCID); } finally { wic.Undo(); } } catch (Exception ex) { throw new InvalidOperationException("Failed to create site collection.", ex); } return languages.ToArray(); } /// <summary>Gets site collection size in bytes.</summary> /// <param name="rootWebApplicationUri">The root web application uri.</param> /// <param name="url">The site collection url.</param> /// <returns>Size in bytes.</returns> public long GetSiteCollectionSize(Uri rootWebApplicationUri, string url) { Dictionary<string, long> sizes = GetSitesCollectionSize(rootWebApplicationUri, new[] {url}); if (sizes.Count() == 1) { return sizes.First().Value; } throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url)); } /// <summary>Gets sites disk space.</summary> /// <param name="rootWebApplicationUri">The root web application uri.</param> /// <param name="urls">The sites urls.</param> /// <returns>The disk space.</returns> public SharePointSiteDiskSpace[] CalculateSiteCollectionDiskSpace(Uri rootWebApplicationUri, string[] urls) { return GetSitesCollectionSize(rootWebApplicationUri, urls).Select(pair => new SharePointSiteDiskSpace {Url = pair.Key, DiskSpace = (long) Math.Round(pair.Value/1024.0/1024.0)}).ToArray(); } /// <summary>Calculates size of the required seti collections.</summary> /// <param name="rootWebApplicationUri">The root web application uri.</param> /// <param name="urls">The sites urls.</param> /// <returns>Calculated sizes.</returns> private Dictionary<string, long> GetSitesCollectionSize(Uri rootWebApplicationUri, IEnumerable<string> urls) { Runspace runspace = null; var result = new Dictionary<string, long>(); try { runspace = OpenRunspace(); foreach (string url in urls) { string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); var scripts = new List<string> {string.Format("$site=Get-SPSite -Identity \"{0}\"", siteCollectionUrl), "$site.RecalculateStorageUsed()", "$site.Usage.Storage"}; Collection<PSObject> scriptResult = ExecuteShellCommand(runspace, scripts); if (scriptResult != null && scriptResult.Any()) { result.Add(url, Convert.ToInt64(scriptResult.First().BaseObject)); } } } finally { CloseRunspace(runspace); } return result; } /// <summary>Sets people picker OU.</summary> /// <param name="site">The site.</param> /// <param name="ou">OU.</param> public void SetPeoplePickerOu(string site, string ou) { HostedSolutionLog.LogStart("SetPeoplePickerOu"); HostedSolutionLog.LogInfo(" Site: {0}", site); HostedSolutionLog.LogInfo(" OU: {0}", ou); Runspace runspace = null; try { runspace = OpenRunspace(); var cmd = new Command("Set-SPSite"); cmd.Parameters.Add("Identity", site); cmd.Parameters.Add("UserAccountDirectoryPath", ou); ExecuteShellCommand(runspace, cmd); } finally { CloseRunspace(runspace); } HostedSolutionLog.LogEnd("SetPeoplePickerOu"); } /// <summary>Gets SharePoint collection within root web application with given name.</summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="url">Url that uniquely identifies site collection to be loaded.</param> /// <returns>SharePoint collection within root web application with given name.</returns> public SharePointSiteCollection GetSiteCollection(Uri rootWebApplicationUri, string url) { return NewSiteCollection(GetSPSiteCollection(rootWebApplicationUri, url)); } /// <summary>Deletes quota.</summary> /// <param name="name">The quota name.</param> private static void DeleteQuotaTemplate(string name) { SPFarm farm = SPFarm.Local; var webService = farm.Services.GetValue<SPWebService>(""); SPQuotaTemplateCollection quotaColl = webService.QuotaTemplates; quotaColl.Delete(name); } /// <summary>Updates site collection quota.</summary> /// <param name="root">The root uri.</param> /// <param name="url">The site collection url.</param> /// <param name="maxStorage">The max storage.</param> /// <param name="warningStorage">The warning storage value.</param> public void UpdateQuotas(Uri root, string url, long maxStorage, long warningStorage) { if (maxStorage != -1) { maxStorage = maxStorage*1024*1024; } else { maxStorage = 0; } if (warningStorage != -1 && maxStorage != -1) { warningStorage = Math.Min(warningStorage, maxStorage)*1024*1024; } else { warningStorage = 0; } Runspace runspace = null; try { runspace = OpenRunspace(); GrantAccess(runspace, root); string siteCollectionUrl = String.Format("{0}:{1}", url, root.Port); var command = new Command("Set-SPSite"); command.Parameters.Add("Identity", siteCollectionUrl); command.Parameters.Add("MaxSize", maxStorage); command.Parameters.Add("WarningSize", warningStorage); ExecuteShellCommand(runspace, command); } finally { CloseRunspace(runspace); } } /// <summary>Grants acces to current user.</summary> /// <param name="runspace">The runspace.</param> /// <param name="rootWebApplicationUri">The root web application uri.</param> private void GrantAccess(Runspace runspace, Uri rootWebApplicationUri) { ExecuteShellCommand(runspace, new List<string> {string.Format("$webApp=Get-SPWebApplication {0}", rootWebApplicationUri.AbsoluteUri), string.Format("$webApp.GrantAccessToProcessIdentity(\"{0}\")", WindowsIdentity.GetCurrent().Name)}); } /// <summary>Deletes site collection.</summary> /// <param name="runspace">The runspace.</param> /// <param name="url">The site collection url.</param> /// <param name="deleteADAccounts">True - if active directory accounts should be deleted.</param> private void DeleteSiteCollection(Runspace runspace, string url, bool deleteADAccounts) { var command = new Command("Remove-SPSite"); command.Parameters.Add("Identity", url); command.Parameters.Add("DeleteADAccounts", deleteADAccounts); ExecuteShellCommand(runspace, command); } /// <summary> Creates site collection within predefined root web application.</summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="siteCollection">Information about site coolection to be created.</param> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> public void CreateSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection) { HostedSolutionLog.LogStart("CreateSiteCollection"); WindowsImpersonationContext wic = null; Runspace runspace = null; try { wic = WindowsIdentity.GetCurrent().Impersonate(); runspace = OpenRunspace(); CreateCollection(runspace, rootWebApplicationUri, siteCollection); } finally { CloseRunspace(runspace); HostedSolutionLog.LogEnd("CreateSiteCollection"); if (wic != null) { wic.Undo(); } } } /// <summary> Creates site collection within predefined root web application.</summary> /// <param name="runspace"> The runspace.</param> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="siteCollection">Information about site coolection to be created.</param> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> private void CreateCollection(Runspace runspace, Uri rootWebApplicationUri, SharePointSiteCollection siteCollection) { string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port); HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl); try { SPWebApplication rootWebApplication = SPWebApplication.Lookup(rootWebApplicationUri); rootWebApplication.Sites.Add(siteCollectionUrl, siteCollection.Title, siteCollection.Description, (uint) siteCollection.LocaleId, String.Empty, siteCollection.OwnerLogin, siteCollection.OwnerName, siteCollection.OwnerEmail, null, null, null, true); rootWebApplication.Update(); } catch (Exception) { DeleteSiteCollection(runspace, siteCollectionUrl, true); throw; } try { GrantAccess(runspace, rootWebApplicationUri); var command = new Command("Set-SPSite"); command.Parameters.Add("Identity", siteCollectionUrl); if (siteCollection.MaxSiteStorage != -1) { command.Parameters.Add("MaxSize", siteCollection.MaxSiteStorage*1024*1024); } if (siteCollection.WarningStorage != -1 && siteCollection.MaxSiteStorage != -1) { command.Parameters.Add("WarningSize", Math.Min(siteCollection.WarningStorage, siteCollection.MaxSiteStorage)*1024*1024); } ExecuteShellCommand(runspace, command); } catch (Exception) { DeleteQuotaTemplate(siteCollection.Title); DeleteSiteCollection(runspace, siteCollectionUrl, true); throw; } AddHostsRecord(siteCollection); } /// <summary>Deletes site collection under given url.</summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="siteCollection">The site collection to be deleted.</param> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> public void DeleteSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection) { HostedSolutionLog.LogStart("DeleteSiteCollection"); Runspace runspace = null; try { string siteCollectionUrl = String.Format("{0}:{1}", siteCollection.Url, rootWebApplicationUri.Port); HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl); runspace = OpenRunspace(); DeleteSiteCollection(runspace, siteCollectionUrl, false); RemoveHostsRecord(siteCollection); } catch (Exception ex) { throw new InvalidOperationException("Failed to delete site collection.", ex); } finally { CloseRunspace(runspace); HostedSolutionLog.LogEnd("DeleteSiteCollection"); } } /// <summary> Backups site collection under give url.</summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="url">Url that uniquely identifies site collection to be deleted.</param> /// <param name="filename">Resulting backup file name.</param> /// <param name="zip">A value which shows whether created backup must be archived.</param> /// <param name="tempPath">Custom temp path for backup</param> /// <returns>Full path to created backup.</returns> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> public string BackupSiteCollection(Uri rootWebApplicationUri, string url, string filename, bool zip, string tempPath) { try { string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); HostedSolutionLog.LogStart("BackupSiteCollection"); HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl); if (String.IsNullOrEmpty(tempPath)) { tempPath = Path.GetTempPath(); } string backupFileName = Path.Combine(tempPath, (zip ? StringUtils.CleanIdentifier(siteCollectionUrl) + ".bsh" : StringUtils.CleanIdentifier(filename))); HostedSolutionLog.DebugInfo("backupFilePath: {0}", backupFileName); Runspace runspace = null; try { runspace = OpenRunspace(); var command = new Command("Backup-SPSite"); command.Parameters.Add("Identity", siteCollectionUrl); command.Parameters.Add("Path", backupFileName); ExecuteShellCommand(runspace, command); if (zip) { string zipFile = Path.Combine(tempPath, filename); string zipRoot = Path.GetDirectoryName(backupFileName); FileUtils.ZipFiles(zipFile, zipRoot, new[] {Path.GetFileName(backupFileName)}); FileUtils.DeleteFile(backupFileName); backupFileName = zipFile; } return backupFileName; } finally { CloseRunspace(runspace); HostedSolutionLog.LogEnd("BackupSiteCollection"); } } catch (Exception ex) { throw new InvalidOperationException("Failed to backup site collection.", ex); } } /// <summary>Restores site collection under given url from backup.</summary> /// <param name="rootWebApplicationUri">Root web application uri.</param> /// <param name="siteCollection">Site collection to be restored.</param> /// <param name="filename">Backup file name to restore from.</param> /// <exception cref="InvalidOperationException">Is thrown in case requested operation fails for any reason.</exception> public void RestoreSiteCollection(Uri rootWebApplicationUri, SharePointSiteCollection siteCollection, string filename) { string url = siteCollection.Url; try { string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); HostedSolutionLog.LogStart("RestoreSiteCollection"); HostedSolutionLog.DebugInfo("siteCollectionUrl: {0}", siteCollectionUrl); HostedSolutionLog.DebugInfo("backupFilePath: {0}", filename); Runspace runspace = null; try { string tempPath = Path.GetTempPath(); string expandedFile = filename; if (Path.GetExtension(filename).ToLower() == ".zip") { expandedFile = FileUtils.UnzipFiles(filename, tempPath)[0]; // Delete zip archive. FileUtils.DeleteFile(filename); } runspace = OpenRunspace(); DeleteSiteCollection(runspace, siteCollectionUrl, false); var command = new Command("Restore-SPSite"); command.Parameters.Add("Identity", siteCollectionUrl); command.Parameters.Add("Path", filename); ExecuteShellCommand(runspace, command); command = new Command("Set-SPSite"); command.Parameters.Add("Identity", siteCollectionUrl); command.Parameters.Add("OwnerAlias", siteCollection.OwnerLogin); ExecuteShellCommand(runspace, command); command = new Command("Set-SPUser"); command.Parameters.Add("Identity", siteCollection.OwnerLogin); command.Parameters.Add("Email", siteCollection.OwnerEmail); command.Parameters.Add("DisplayName", siteCollection.Name); ExecuteShellCommand(runspace, command); FileUtils.DeleteFile(expandedFile); } finally { CloseRunspace(runspace); HostedSolutionLog.LogEnd("RestoreSiteCollection"); } } catch (Exception ex) { throw new InvalidOperationException("Failed to restore site collection.", ex); } } /// <summary>Creates new site collection with information from administration object.</summary> /// <param name="site">Administration object.</param> private static SharePointSiteCollection NewSiteCollection(SPSite site) { var siteUri = new Uri(site.Url); string url = (siteUri.Port > 0) ? site.Url.Replace(String.Format(":{0}", siteUri.Port), String.Empty) : site.Url; return new SharePointSiteCollection {Url = url, OwnerLogin = site.Owner.LoginName, OwnerName = site.Owner.Name, OwnerEmail = site.Owner.Email, LocaleId = site.RootWeb.Locale.LCID, Title = site.RootWeb.Title, Description = site.RootWeb.Description, Bandwidth = site.Usage.Bandwidth, Diskspace = site.Usage.Storage, MaxSiteStorage = site.Quota.StorageMaximumLevel, WarningStorage = site.Quota.StorageWarningLevel}; } /// <summary>Gets SharePoint sites collection.</summary> /// <param name="rootWebApplicationUri">The root web application uri.</param> /// <returns>The SharePoint sites.</returns> private Dictionary<string, SPSite> GetSPSiteCollections(Uri rootWebApplicationUri) { Runspace runspace = null; var collections = new Dictionary<string, SPSite>(); try { runspace = OpenRunspace(); var cmd = new Command("Get-SPSite"); cmd.Parameters.Add("WebApplication", rootWebApplicationUri.AbsoluteUri); Collection<PSObject> result = ExecuteShellCommand(runspace, cmd); if (result != null) { foreach (PSObject psObject in result) { var spSite = psObject.BaseObject as SPSite; if (spSite != null) { collections.Add(spSite.Url, spSite); } } } } finally { CloseRunspace(runspace); } return collections; } /// <summary>Gets SharePoint site collection.</summary> /// <param name="rootWebApplicationUri">The root web application uri.</param> /// <param name="url">The required site url.</param> /// <returns>The SharePoint sites.</returns> private SPSite GetSPSiteCollection(Uri rootWebApplicationUri, string url) { Runspace runspace = null; try { string siteCollectionUrl = String.Format("{0}:{1}", url, rootWebApplicationUri.Port); runspace = OpenRunspace(); var cmd = new Command("Get-SPSite"); cmd.Parameters.Add("Identity", siteCollectionUrl); Collection<PSObject> result = ExecuteShellCommand(runspace, cmd); if (result != null && result.Count() == 1) { var spSite = result.First().BaseObject as SPSite; if (spSite == null) { throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url)); } return result.First().BaseObject as SPSite; } else { throw new ApplicationException(string.Format("SiteCollection {0} does not exist", url)); } } catch (Exception ex) { HostedSolutionLog.LogError(ex); throw; } finally { CloseRunspace(runspace); } } /// <summary>Opens PowerShell runspace.</summary> /// <returns>The runspace.</returns> private Runspace OpenRunspace() { HostedSolutionLog.LogStart("OpenRunspace"); if (runspaceConfiguration == null) { runspaceConfiguration = RunspaceConfiguration.Create(); PSSnapInException exception; runspaceConfiguration.AddPSSnapIn(SharepointSnapInName, out exception); HostedSolutionLog.LogInfo("Sharepoint snapin loaded"); if (exception != null) { HostedSolutionLog.LogWarning("SnapIn error", exception); } } Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration); runspace.Open(); runspace.SessionStateProxy.SetVariable("ConfirmPreference", "none"); HostedSolutionLog.LogEnd("OpenRunspace"); return runspace; } /// <summary>Closes runspace.</summary> /// <param name="runspace">The runspace.</param> private void CloseRunspace(Runspace runspace) { try { if (runspace != null && runspace.RunspaceStateInfo.State == RunspaceState.Opened) { runspace.Close(); } } catch (Exception ex) { HostedSolutionLog.LogError("Runspace error", ex); } } /// <summary>Executes shell command.</summary> /// <param name="runspace">The runspace.</param> /// <param name="cmd">The command to be executed.</param> /// <returns>PSobjecs collection.</returns> private Collection<PSObject> ExecuteShellCommand(Runspace runspace, object cmd) { object[] errors; var command = cmd as Command; if (command != null) { return ExecuteShellCommand(runspace, command, out errors); } return ExecuteShellCommand(runspace, cmd as List<string>, out errors); } /// <summary>Executes shell command.</summary> /// <param name="runspace">The runspace.</param> /// <param name="cmd">The command to be executed.</param> /// <param name="errors">The errors.</param> /// <returns>PSobjecs collection.</returns> private Collection<PSObject> ExecuteShellCommand(Runspace runspace, Command cmd, out object[] errors) { HostedSolutionLog.LogStart("ExecuteShellCommand"); var errorList = new List<object>(); Collection<PSObject> results; using (Pipeline pipeLine = runspace.CreatePipeline()) { pipeLine.Commands.Add(cmd); results = pipeLine.Invoke(); if (pipeLine.Error != null && pipeLine.Error.Count > 0) { foreach (object item in pipeLine.Error.ReadToEnd()) { errorList.Add(item); string errorMessage = string.Format("Invoke error: {0}", item); HostedSolutionLog.LogWarning(errorMessage); } } } errors = errorList.ToArray(); HostedSolutionLog.LogEnd("ExecuteShellCommand"); return results; } /// <summary>Executes shell command.</summary> /// <param name="runspace">The runspace.</param> /// <param name="scripts">The scripts to be executed.</param> /// <param name="errors">The errors.</param> /// <returns>PSobjecs collection.</returns> private Collection<PSObject> ExecuteShellCommand(Runspace runspace, List<string> scripts, out object[] errors) { HostedSolutionLog.LogStart("ExecuteShellCommand"); var errorList = new List<object>(); Collection<PSObject> results; using (Pipeline pipeLine = runspace.CreatePipeline()) { foreach (string script in scripts) { pipeLine.Commands.AddScript(script); } results = pipeLine.Invoke(); if (pipeLine.Error != null && pipeLine.Error.Count > 0) { foreach (object item in pipeLine.Error.ReadToEnd()) { errorList.Add(item); string errorMessage = string.Format("Invoke error: {0}", item); HostedSolutionLog.LogWarning(errorMessage); throw new ArgumentException(scripts.First()); } } } errors = errorList.ToArray(); HostedSolutionLog.LogEnd("ExecuteShellCommand"); return results; } /// <summary>Adds record to hosts file.</summary> /// <param name="siteCollection">The site collection object.</param> public void AddHostsRecord(SharePointSiteCollection siteCollection) { try { if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty) { string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc"); string path = dirPath + "\\hosts"; if (FileUtils.FileExists(path)) { string content = FileUtils.GetFileTextContent(path); content = content.Replace("\r\n", "\n").Replace("\n\r", "\n"); string[] contentArr = content.Split(new[] {'\n'}); bool bRecordExist = false; foreach (string s in contentArr) { if (s != string.Empty) { string hostName = string.Empty; if (s[0] != '#') { bool bSeperator = false; foreach (char c in s) { if ((c != ' ') & (c != '\t')) { if (bSeperator) { hostName += c; } } else { bSeperator = true; } } if (hostName.ToLower() == siteCollection.RootWebApplicationFQDN.ToLower()) { bRecordExist = true; break; } } } } if (!bRecordExist) { string outPut = contentArr.Where(o => o != string.Empty).Aggregate(string.Empty, (current, o) => current + (o + "\r\n")); outPut += siteCollection.RootWebApplicationInteralIpAddress + '\t' + siteCollection.RootWebApplicationFQDN + "\r\n"; FileUtils.UpdateFileTextContent(path, outPut); } } } } catch (Exception ex) { HostedSolutionLog.LogError(ex); } } /// <summary>Removes record from hosts file.</summary> /// <param name="siteCollection">The site collection object.</param> private void RemoveHostsRecord(SharePointSiteCollection siteCollection) { try { if (siteCollection.RootWebApplicationInteralIpAddress != string.Empty) { string dirPath = FileUtils.EvaluateSystemVariables(@"%windir%\system32\drivers\etc"); string path = dirPath + "\\hosts"; if (FileUtils.FileExists(path)) { string content = FileUtils.GetFileTextContent(path); content = content.Replace("\r\n", "\n").Replace("\n\r", "\n"); string[] contentArr = content.Split(new[] {'\n'}); string outPut = string.Empty; foreach (string s in contentArr) { if (s != string.Empty) { string hostName = string.Empty; if (s[0] != '#') { bool bSeperator = false; foreach (char c in s) { if ((c != ' ') & (c != '\t')) { if (bSeperator) { hostName += c; } } else { bSeperator = true; } } if (hostName.ToLower() != siteCollection.RootWebApplicationFQDN.ToLower()) { outPut += s + "\r\n"; } } else { outPut += s + "\r\n"; } } } FileUtils.UpdateFileTextContent(path, outPut); } } } catch (Exception ex) { HostedSolutionLog.LogError(ex); } } #endregion } }
namespace Epi.Windows.Analysis.Dialogs { partial class ComplexSampleTablesDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ComplexSampleTablesDialog)); this.cmbWeight = new System.Windows.Forms.ComboBox(); this.lblWeight = new System.Windows.Forms.Label(); this.lblOutput = new System.Windows.Forms.Label(); this.txtOutput = new System.Windows.Forms.TextBox(); this.cmbOutcome = new System.Windows.Forms.ComboBox(); this.lblOutcomeVar = new System.Windows.Forms.Label(); this.cmbStratifyBy = new System.Windows.Forms.ComboBox(); this.lblStratifyBy = new System.Windows.Forms.Label(); this.pbxheight = new System.Windows.Forms.PictureBox(); this.cbxMatch = new System.Windows.Forms.CheckBox(); this.lbxStratifyBy = new System.Windows.Forms.ListBox(); this.gbxPageSettings = new System.Windows.Forms.GroupBox(); this.label1 = new System.Windows.Forms.Label(); this.txtNumCol = new System.Windows.Forms.TextBox(); this.cbxNoLineWrap = new System.Windows.Forms.CheckBox(); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.cmbExposure = new System.Windows.Forms.ComboBox(); this.lblExposure = new System.Windows.Forms.Label(); this.cmbPSU = new System.Windows.Forms.ComboBox(); this.lblPSU = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pbxheight)).BeginInit(); this.gbxPageSettings.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // cmbWeight // this.cmbWeight.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbWeight.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbWeight.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbWeight, "cmbWeight"); this.cmbWeight.Name = "cmbWeight"; this.cmbWeight.Sorted = true; this.cmbWeight.SelectedIndexChanged += new System.EventHandler(this.cmbWeight_SelectedIndexChanged); this.cmbWeight.Click += new System.EventHandler(this.cmbWeight_Click); this.cmbWeight.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cmbWeight_KeyDown); // // lblWeight // this.lblWeight.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblWeight, "lblWeight"); this.lblWeight.Name = "lblWeight"; // // lblOutput // this.lblOutput.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblOutput, "lblOutput"); this.lblOutput.Name = "lblOutput"; // // txtOutput // resources.ApplyResources(this.txtOutput, "txtOutput"); this.txtOutput.Name = "txtOutput"; // // cmbOutcome // this.cmbOutcome.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbOutcome.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbOutcome.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbOutcome, "cmbOutcome"); this.cmbOutcome.Name = "cmbOutcome"; this.cmbOutcome.Sorted = true; this.cmbOutcome.SelectedIndexChanged += new System.EventHandler(this.cmbOutcome_SelectedIndexChanged); this.cmbOutcome.Click += new System.EventHandler(this.cmbOutcome_Click); // // lblOutcomeVar // this.lblOutcomeVar.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblOutcomeVar, "lblOutcomeVar"); this.lblOutcomeVar.Name = "lblOutcomeVar"; // // cmbStratifyBy // this.cmbStratifyBy.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbStratifyBy.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbStratifyBy.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbStratifyBy, "cmbStratifyBy"); this.cmbStratifyBy.Name = "cmbStratifyBy"; this.cmbStratifyBy.Sorted = true; this.cmbStratifyBy.SelectedIndexChanged += new System.EventHandler(this.cmbStratifyBy_SelectedIndexChanged); // // lblStratifyBy // this.lblStratifyBy.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblStratifyBy, "lblStratifyBy"); this.lblStratifyBy.Name = "lblStratifyBy"; // // pbxheight // resources.ApplyResources(this.pbxheight, "pbxheight"); this.pbxheight.Name = "pbxheight"; this.pbxheight.TabStop = false; // // cbxMatch // resources.ApplyResources(this.cbxMatch, "cbxMatch"); this.cbxMatch.Name = "cbxMatch"; this.cbxMatch.Click += new System.EventHandler(this.cbxMatch_Click); // // lbxStratifyBy // resources.ApplyResources(this.lbxStratifyBy, "lbxStratifyBy"); this.lbxStratifyBy.Name = "lbxStratifyBy"; this.lbxStratifyBy.SelectedIndexChanged += new System.EventHandler(this.lbxStratifyBy_SelectedIndexChanged); // // gbxPageSettings // this.gbxPageSettings.Controls.Add(this.label1); this.gbxPageSettings.Controls.Add(this.txtNumCol); this.gbxPageSettings.Controls.Add(this.cbxNoLineWrap); this.gbxPageSettings.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.gbxPageSettings, "gbxPageSettings"); this.gbxPageSettings.Name = "gbxPageSettings"; this.gbxPageSettings.TabStop = false; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // txtNumCol // resources.ApplyResources(this.txtNumCol, "txtNumCol"); this.txtNumCol.Name = "txtNumCol"; this.txtNumCol.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtNumCol_KeyPress); this.txtNumCol.Leave += new System.EventHandler(this.txtNumCol_Leave); // // cbxNoLineWrap // resources.ApplyResources(this.cbxNoLineWrap, "cbxNoLineWrap"); this.cbxNoLineWrap.Name = "cbxNoLineWrap"; // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // cmbExposure // this.cmbExposure.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbExposure.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbExposure.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbExposure, "cmbExposure"); this.cmbExposure.Name = "cmbExposure"; this.cmbExposure.Sorted = true; this.cmbExposure.SelectedIndexChanged += new System.EventHandler(this.cmbExposure_SelectedIndexChanged); this.cmbExposure.Click += new System.EventHandler(this.cmbExposure_Click); // // lblExposure // resources.ApplyResources(this.lblExposure, "lblExposure"); this.lblExposure.Name = "lblExposure"; // // cmbPSU // this.cmbPSU.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; this.cmbPSU.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.cmbPSU.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.cmbPSU, "cmbPSU"); this.cmbPSU.Name = "cmbPSU"; this.cmbPSU.Sorted = true; this.cmbPSU.SelectedIndexChanged += new System.EventHandler(this.cmbPSU_SelectedIndexChanged); this.cmbPSU.Click += new System.EventHandler(this.cmbPSU_Click); // // lblPSU // this.lblPSU.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblPSU, "lblPSU"); this.lblPSU.Name = "lblPSU"; // // ComplexSampleTablesDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.cmbPSU); this.Controls.Add(this.lblPSU); this.Controls.Add(this.lblExposure); this.Controls.Add(this.cmbExposure); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.gbxPageSettings); this.Controls.Add(this.lbxStratifyBy); this.Controls.Add(this.cbxMatch); this.Controls.Add(this.pbxheight); this.Controls.Add(this.cmbStratifyBy); this.Controls.Add(this.lblStratifyBy); this.Controls.Add(this.cmbOutcome); this.Controls.Add(this.lblOutcomeVar); this.Controls.Add(this.lblOutput); this.Controls.Add(this.txtOutput); this.Controls.Add(this.cmbWeight); this.Controls.Add(this.lblWeight); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ComplexSampleTablesDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.TablesDialog_Load); ((System.ComponentModel.ISupportInitialize)(this.pbxheight)).EndInit(); this.gbxPageSettings.ResumeLayout(false); this.gbxPageSettings.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox cmbWeight; private System.Windows.Forms.Label lblWeight; private System.Windows.Forms.Label lblOutput; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.ComboBox cmbOutcome; private System.Windows.Forms.Label lblOutcomeVar; private System.Windows.Forms.ComboBox cmbStratifyBy; private System.Windows.Forms.Label lblStratifyBy; private System.Windows.Forms.CheckBox cbxMatch; private System.Windows.Forms.ListBox lbxStratifyBy; private System.Windows.Forms.GroupBox gbxPageSettings; private System.Windows.Forms.TextBox txtNumCol; private System.Windows.Forms.CheckBox cbxNoLineWrap; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.PictureBox pbxheight; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.ComboBox cmbExposure; private System.Windows.Forms.Label lblExposure; private System.Windows.Forms.ComboBox cmbPSU; private System.Windows.Forms.Label lblPSU; private System.Windows.Forms.Label label1; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using OpenTK; using OpenTK.Graphics; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Overlays.SearchableList; using osu.Game.Overlays.Social; using osu.Game.Users; using osu.Framework.Configuration; using osu.Framework.Threading; namespace osu.Game.Overlays { public class SocialOverlay : SearchableListOverlay<SocialTab, SocialSortCriteria, SortDirection>, IOnlineComponent { private APIAccess api; private readonly LoadingAnimation loading; private FillFlowContainer<SocialPanel> panels; protected override Color4 BackgroundColour => OsuColour.FromHex(@"60284b"); protected override Color4 TrianglesColourLight => OsuColour.FromHex(@"672b51"); protected override Color4 TrianglesColourDark => OsuColour.FromHex(@"5c2648"); protected override SearchableListHeader<SocialTab> CreateHeader() => new Header(); protected override SearchableListFilterControl<SocialSortCriteria, SortDirection> CreateFilterControl() => new FilterControl(); private IEnumerable<User> users; public IEnumerable<User> Users { get { return users; } set { if (users?.Equals(value) ?? false) return; users = value?.ToList(); } } public SocialOverlay() { Waves.FirstWaveColour = OsuColour.FromHex(@"cb5fa0"); Waves.SecondWaveColour = OsuColour.FromHex(@"b04384"); Waves.ThirdWaveColour = OsuColour.FromHex(@"9b2b6e"); Waves.FourthWaveColour = OsuColour.FromHex(@"6d214d"); Add(loading = new LoadingAnimation()); Filter.Search.Current.ValueChanged += text => { if (!string.IsNullOrEmpty(text)) { // force searching in players until searching for friends is supported Header.Tabs.Current.Value = SocialTab.AllPlayers; if (Filter.Tabs.Current.Value != SocialSortCriteria.Rank) Filter.Tabs.Current.Value = SocialSortCriteria.Rank; } }; Header.Tabs.Current.ValueChanged += tab => Scheduler.AddOnce(updateSearch); Filter.Tabs.Current.ValueChanged += sortCriteria => Scheduler.AddOnce(updateSearch); Filter.DisplayStyleControl.DisplayStyle.ValueChanged += recreatePanels; Filter.DisplayStyleControl.Dropdown.Current.ValueChanged += sortOrder => Scheduler.AddOnce(updateSearch); currentQuery.ValueChanged += query => { queryChangedDebounce?.Cancel(); if (string.IsNullOrEmpty(query)) Scheduler.AddOnce(updateSearch); else queryChangedDebounce = Scheduler.AddDelayed(updateSearch, 500); }; currentQuery.BindTo(Filter.Search.Current); } [BackgroundDependencyLoader] private void load(APIAccess api) { this.api = api; api.Register(this); } private void recreatePanels(PanelDisplayStyle displayStyle) { clearPanels(); if (Users == null) return; var newPanels = new FillFlowContainer<SocialPanel> { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Spacing = new Vector2(10f), Margin = new MarginPadding { Top = 10 }, ChildrenEnumerable = Users.Select(u => { SocialPanel panel; switch (displayStyle) { case PanelDisplayStyle.Grid: panel = new SocialGridPanel(u) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre }; break; default: panel = new SocialListPanel(u); break; } panel.Status.BindTo(u.Status); return panel; }) }; LoadComponentAsync(newPanels, f => { if(panels != null) ScrollFlow.Remove(panels); ScrollFlow.Add(panels = newPanels); }); } private APIRequest getUsersRequest; private readonly Bindable<string> currentQuery = new Bindable<string>(); private ScheduledDelegate queryChangedDebounce; private void updateSearch() { queryChangedDebounce?.Cancel(); if (!IsLoaded) return; Users = null; clearPanels(); loading.Hide(); getUsersRequest?.Cancel(); if (api?.IsLoggedIn != true) return; switch (Header.Tabs.Current.Value) { case SocialTab.Friends: var friendRequest = new GetFriendsRequest(); // TODO filter arguments? friendRequest.Success += updateUsers; api.Queue(getUsersRequest = friendRequest); break; default: var userRequest = new GetUsersRequest(); // TODO filter arguments! userRequest.Success += response => updateUsers(response.Select(r => r.User)); api.Queue(getUsersRequest = userRequest); break; } loading.Show(); } private void updateUsers(IEnumerable<User> newUsers) { Users = newUsers; loading.Hide(); recreatePanels(Filter.DisplayStyleControl.DisplayStyle.Value); } private void clearPanels() { if (panels != null) { panels.Expire(); panels = null; } } public void APIStateChanged(APIAccess api, APIState state) { switch (state) { case APIState.Online: Scheduler.AddOnce(updateSearch); break; default: Users = null; clearPanels(); break; } } } public enum SortDirection { Ascending, Descending } }
using NQuery.Authoring.CodeActions; using NQuery.Authoring.CodeActions.Issues; namespace NQuery.Authoring.Tests.CodeActions.Issues { public class OrderByExpressionsTests : CodeIssueTests { protected override ICodeIssueProvider CreateProvider() { return new OrderByExpressionsCodeIssueProvider(); } [Fact] public void OrderByExpressions_DoesNotTrigger_ForColumnExpressions() { var query = @" SELECT FirstName, e.LastName FROM Employees e ORDER BY FirstName, e.LastName "; var issues = GetIssues(query); Assert.Empty(issues); } [Fact] public void OrderByExpressions_DoesNotTrigger_ForOrdinalReferences() { var query = @" SELECT FirstName + ' ' + e.LastName FROM Employees e ORDER BY 1 "; var issues = GetIssues(query); Assert.Empty(issues); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithOrdinal() { var query = @" SELECT e.FirstName + ' ' + e.LastName FROM Employees e ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e.FirstName /* marker */ + ' ' + e.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithOrdinal() { var query = @" SELECT e.FirstName + ' ' + e.LastName FROM Employees e ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var fixedQuery = @" SELECT e.FirstName + ' ' + e.LastName FROM Employees e ORDER BY 1 "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithAlias() { var query = @" SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e.FirstName /* marker */ + ' ' + e.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithAlias() { var query = @" SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var fixedQuery = @" SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ORDER BY FullName "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithOrdinal_IfAppliedToParenthesizedQuery() { var query = @" ( SELECT e.FirstName + ' ' + e.LastName FROM Employees e ) ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e.FirstName /* marker */ + ' ' + e.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithOrdinal_IfAppliedToParenthesizedQuery() { var query = @" ( SELECT e.FirstName + ' ' + e.LastName FROM Employees e ) ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var fixedQuery = @" ( SELECT e.FirstName + ' ' + e.LastName FROM Employees e ) ORDER BY 1 "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithAlias_IfAppliedToParenthesizedQuery() { var query = @" ( SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ) ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e.FirstName /* marker */ + ' ' + e.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithAlias_IfAppliedToParenthesizedQuery() { var query = @" ( SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ) ORDER BY e.FirstName /* marker */ + ' ' + e.LastName "; var fixedQuery = @" ( SELECT e.FirstName + ' ' + e.LastName AS FullName FROM Employees e ) ORDER BY FullName "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithOrdinal_IfAppliedToUnionQuery() { var query = @" ( SELECT e1.FirstName + ' ' + e1.LastName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY e1.FirstName /* marker */ + ' ' + e1.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e1.FirstName /* marker */ + ' ' + e1.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithOrdinal_IfAppliedToUnionQuery() { var query = @" ( SELECT e1.FirstName + ' ' + e1.LastName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY e1.FirstName /* marker */ + ' ' + e1.LastName "; var fixedQuery = @" ( SELECT e1.FirstName + ' ' + e1.LastName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY 1 "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } [Fact] public void OrderByExpressions_FindsUsageOfExpressionThatCanBeReplacedWithAlias_IfAppliedToUnionQuery() { var query = @" ( SELECT e1.FirstName + ' ' + e1.LastName AS FullName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY e1.FirstName /* marker */ + ' ' + e1.LastName "; var issues = GetIssues(query); Assert.Single(issues); Assert.Equal(CodeIssueKind.Warning, issues[0].Kind); Assert.Equal("e1.FirstName /* marker */ + ' ' + e1.LastName", query.Substring(issues[0].Span)); } [Fact] public void OrderByExpressions_FixesUsageOfExpressionThatCanBeReplacedWithAlias_IfAppliedToUnionQuery() { var query = @" ( SELECT e1.FirstName + ' ' + e1.LastName AS FullName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY e1.FirstName /* marker */ + ' ' + e1.LastName "; var fixedQuery = @" ( SELECT e1.FirstName + ' ' + e1.LastName AS FullName FROM Employees e1 UNION SELECT e2.FirstName + ' ' + e2.LastName FROM Employees e2 ) ORDER BY FullName "; var issues = GetIssues(query); Assert.Single(issues); var action = issues.First().Actions.First(); Assert.Equal("Replace expression by SELECT column reference", action.Description); var syntaxTree = action.GetEdit(); Assert.Equal(fixedQuery, syntaxTree.Text.GetText()); } } }
/****************************************************************************** * Spine Runtimes Software License v2.5 * * Copyright (c) 2013-2016, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable, and * non-transferable license to use, install, execute, and perform the Spine * Runtimes software and derivative works solely for personal or internal * use. Without the written permission of Esoteric Software (see Section 2 of * the Spine Software License Agreement), you may not (a) modify, translate, * adapt, or develop new applications using the Spine Runtimes or otherwise * create derivative works or improvements of the Spine Runtimes or (b) remove, * delete, alter, or obscure any trademarks or any copyright, trademark, patent, * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF * USE, DATA, OR PROFITS) 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. *****************************************************************************/ // Contributed by: Mitch Thompson using UnityEngine; using Spine; namespace Spine.Unity { /// <summary>Sets a GameObject's transform to match a bone on a Spine skeleton.</summary> [ExecuteInEditMode] [AddComponentMenu("Spine/SkeletonUtilityBone")] public class SkeletonUtilityBone : MonoBehaviour { public enum Mode { Follow, Override } #region Inspector /// <summary>If a bone isn't set, boneName is used to find the bone.</summary> public string boneName; public Transform parentReference; public Mode mode; public bool position, rotation, scale, zPosition = true; [Range(0f, 1f)] public float overrideAlpha = 1; #endregion [System.NonSerialized] public SkeletonUtility skeletonUtility; [System.NonSerialized] public Bone bone; [System.NonSerialized] public bool transformLerpComplete; [System.NonSerialized] public bool valid; Transform cachedTransform; Transform skeletonTransform; bool incompatibleTransformMode; public bool IncompatibleTransformMode { get { return incompatibleTransformMode; } } public void Reset () { bone = null; cachedTransform = transform; valid = skeletonUtility != null && skeletonUtility.skeletonRenderer != null && skeletonUtility.skeletonRenderer.valid; if (!valid) return; skeletonTransform = skeletonUtility.transform; skeletonUtility.OnReset -= HandleOnReset; skeletonUtility.OnReset += HandleOnReset; DoUpdate(); } void OnEnable () { skeletonUtility = transform.GetComponentInParent<SkeletonUtility>(); if (skeletonUtility == null) return; skeletonUtility.RegisterBone(this); skeletonUtility.OnReset += HandleOnReset; } void HandleOnReset () { Reset(); } void OnDisable () { if (skeletonUtility != null) { skeletonUtility.OnReset -= HandleOnReset; skeletonUtility.UnregisterBone(this); } } public void DoUpdate () { if (!valid) { Reset(); return; } var skeleton = skeletonUtility.skeletonRenderer.skeleton; if (bone == null) { if (string.IsNullOrEmpty(boneName)) return; bone = skeleton.FindBone(boneName); if (bone == null) { Debug.LogError("Bone not found: " + boneName, this); return; } } float skeletonFlipRotation = (skeleton.flipX ^ skeleton.flipY) ? -1f : 1f; if (mode == Mode.Follow) { if (!bone.appliedValid) bone.UpdateAppliedTransform(); if (position) cachedTransform.localPosition = new Vector3(bone.ax, bone.ay, 0); if (rotation) { if (bone.data.transformMode.InheritsRotation()) { cachedTransform.localRotation = Quaternion.Euler(0, 0, bone.AppliedRotation); } else { Vector3 euler = skeletonTransform.rotation.eulerAngles; cachedTransform.rotation = Quaternion.Euler(euler.x, euler.y, euler.z + (bone.WorldRotationX * skeletonFlipRotation)); } } if (scale) { cachedTransform.localScale = new Vector3(bone.ascaleX, bone.ascaleY, 1f); incompatibleTransformMode = BoneTransformModeIncompatible(bone); } } else if (mode == Mode.Override) { if (transformLerpComplete) return; if (parentReference == null) { if (position) { Vector3 clp = cachedTransform.localPosition; bone.x = Mathf.Lerp(bone.x, clp.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, clp.y, overrideAlpha); } if (rotation) { float angle = Mathf.LerpAngle(bone.Rotation, cachedTransform.localRotation.eulerAngles.z, overrideAlpha); bone.Rotation = angle; bone.AppliedRotation = angle; } if (scale) { Vector3 cls = cachedTransform.localScale; bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha); } } else { if (transformLerpComplete) return; if (position) { Vector3 pos = parentReference.InverseTransformPoint(cachedTransform.position); bone.x = Mathf.Lerp(bone.x, pos.x, overrideAlpha); bone.y = Mathf.Lerp(bone.y, pos.y, overrideAlpha); } if (rotation) { float angle = Mathf.LerpAngle(bone.Rotation, Quaternion.LookRotation(Vector3.forward, parentReference.InverseTransformDirection(cachedTransform.up)).eulerAngles.z, overrideAlpha); bone.Rotation = angle; bone.AppliedRotation = angle; } if (scale) { Vector3 cls = cachedTransform.localScale; bone.scaleX = Mathf.Lerp(bone.scaleX, cls.x, overrideAlpha); bone.scaleY = Mathf.Lerp(bone.scaleY, cls.y, overrideAlpha); } incompatibleTransformMode = BoneTransformModeIncompatible(bone); } transformLerpComplete = true; } } public static bool BoneTransformModeIncompatible (Bone bone) { return !bone.data.transformMode.InheritsScale(); } public void AddBoundingBox (string skinName, string slotName, string attachmentName) { SkeletonUtility.AddBoundingBoxGameObject(bone.skeleton, skinName, slotName, attachmentName, transform); } #if UNITY_EDITOR void OnDrawGizmos () { if (IncompatibleTransformMode) Gizmos.DrawIcon(transform.position + new Vector3(0, 0.128f, 0), "icon-warning"); } #endif } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Alachisoft.NCache.Integrations.Memcached.ProxyServer.Commands; using System.Threading; using Alachisoft.NCache.Integrations.Memcached.ProxyServer.NetworkGateway; using System.Collections; using Alachisoft.NCache.Integrations.Memcached.ProxyServer.Common; namespace Alachisoft.NCache.Integrations.Memcached.ProxyServer.Parsing { class TextProtocolParser : ProtocolParser { public TextProtocolParser(DataStream inputStream, MemTcpClient parent, LogManager logManager) : base(inputStream, parent, logManager) { } /// <summary> /// Parses an <see cref="Alachisoft.NCache.Integrations.Memcached.ProxyServer.Commands.AbstractCommand"/> from string /// </summary> /// <param name="command">string command to pe parsed</param> public void Parse(string command) { string[] commandParts = command.Split(new char[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); if (commandParts == null || commandParts.Length == 0) { _command = new InvalidCommand(); this.State = ParserState.ReadyToDispatch; return; } string arguments = null; if (commandParts.Length > 1) arguments = commandParts[1]; switch (commandParts[0]) { case "get": CreateRetrievalCommand(arguments, Opcode.Get); break; case "gets": CreateRetrievalCommand(arguments, Opcode.Gets); break; case "set": CreateStorageCommand(arguments, Opcode.Set); break; case "add": CreateStorageCommand(arguments, Opcode.Add); break; case "replace": CreateStorageCommand(arguments, Opcode.Replace); break; case "append": CreateStorageCommand(arguments, Opcode.Append); break; case "prepend": CreateStorageCommand(arguments, Opcode.Prepend); break; case "cas": CreateStorageCommand(arguments, Opcode.CAS); break; case "delete": CreateDeleteCommand(arguments); break; case "incr": CreateCounterCommand(arguments, Opcode.Increment); break; case "decr": CreateCounterCommand(arguments, Opcode.Decrement); break; case "touch": CreateTouchCommand(arguments); break; case "flush_all": CreateFlushCommand(arguments); break; case "stats": CreateStatsCommand(arguments); break; case "slabs": break; case "version": CreateVersionCommand(arguments); break; case "verbosity": CreateVerbosityCommand(arguments); break; case "quit": CreateQuitCommand(); break; default: CreateInvalidCommand(); break; } } private void CreateQuitCommand() { _command = new QuitCommand(Opcode.Quit); this.State = ParserState.ReadyToDispatch; } private void CreateVerbosityCommand(string arguments) { if (string.IsNullOrEmpty(arguments)) { CreateInvalidCommand(); return; } string[] argumentsArray; argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 2 || argumentsArray.Length < 1) { CreateInvalidCommand(); return; } int level; bool noreply = false; try { level = int.Parse(argumentsArray[0]); noreply = (argumentsArray.Length > 1 && argumentsArray[1] == "noreply") ? true : false; } catch (Exception) { CreateInvalidCommand(); return; } _command = new VerbosityCommand(); _command.NoReply = noreply; this.State = ParserState.ReadyToDispatch; } private void CreateVersionCommand(string arguments) { if (!string.IsNullOrEmpty(arguments)) { CreateInvalidCommand(); return; } _command = new VersionCommand(); this.State = ParserState.ReadyToDispatch; } private void CreateStatsCommand(string arguments) { if (string.IsNullOrEmpty(arguments)) { _command = new StatsCommand(); this.State = ParserState.ReadyToDispatch; return; } string[] argumentsArray; argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); switch (argumentsArray[0]) { case "settings": case "items": case "sizes": case "slabs": _command = new StatsCommand(argumentsArray[0]); this.State = ParserState.ReadyToDispatch; break; default: CreateInvalidCommand(); break; } } private void CreateSlabsCommand(string arguments) { if (string.IsNullOrEmpty(arguments)) { CreateInvalidCommand(); return; } string[] argumentsArray; argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 3 || argumentsArray.Length < 2) { CreateInvalidCommand(); return; } try { bool noreply = false; switch (argumentsArray[0]) { case "reasign": int sourceClass = int.Parse(argumentsArray[1]); int destClass = int.Parse(argumentsArray[2]); noreply = argumentsArray.Length > 2 && argumentsArray[3] == "noreply"; _command = new SlabsReassignCommand(sourceClass, destClass); _command.NoReply = noreply; break; case "automove": int option = int.Parse(argumentsArray[1]); noreply = argumentsArray.Length > 2 && argumentsArray[2] == "noreply"; _command = new SlabsAuomoveCommand(option); _command.NoReply = noreply; break; default: _command = new InvalidCommand(); break; } this.State = ParserState.ReadyToDispatch; } catch (Exception) { CreateInvalidCommand(); } } private void CreateTouchCommand(string arguments) { if (string.IsNullOrEmpty(arguments)) { CreateInvalidCommand(); return; } string[] argumentsArray; argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 3 || argumentsArray.Length < 2) { CreateInvalidCommand(); return; } string key; long expTime; bool noreply = false; try { key = argumentsArray[0]; expTime = long.Parse(argumentsArray[1]); if (argumentsArray.Length > 2 && argumentsArray[2] == "noreply") noreply = true; } catch (Exception) { CreateInvalidCommand("CLIENT_ERROR bad command line format"); return; } _command = new TouchCommand(key, expTime); _command.NoReply = noreply; this.State = ParserState.ReadyToDispatch; } private void CreateFlushCommand(string arguments) { int delay = 0; bool noreply = false; string[] argumentsArray; if (string.IsNullOrEmpty(arguments)) { delay = 0; } else { argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 2) { CreateInvalidCommand(); return; } try { delay = int.Parse(argumentsArray[0]); if (argumentsArray.Length > 1 && argumentsArray[1] == "noreply") noreply = true; } catch (Exception e) { CreateInvalidCommand("CLIENT_ERROR bad command line format"); return; } } _command = new FlushCommand(Opcode.Flush,delay); _command.NoReply = noreply; this.State = ParserState.ReadyToDispatch; } private void CreateCounterCommand(string arguments, Opcode cmdType) { string[] argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 3 || argumentsArray.Length < 2) { CreateInvalidCommand(); return; } CounterCommand command = new CounterCommand(cmdType); try { command.Key = argumentsArray[0]; command.Delta = ulong.Parse(argumentsArray[1]); if (argumentsArray.Length > 2 && argumentsArray[2] == "noreply") command.NoReply = true; } catch (Exception) { command.ErrorMessage = "CLIENT_ERROR bad command line format"; } _command = command; this.State = ParserState.ReadyToDispatch; } private void CreateDeleteCommand(string arguments) { if (String.IsNullOrEmpty(arguments)) { CreateInvalidCommand(); return; } string[] argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length > 2 || argumentsArray.Length < 1) { CreateInvalidCommand(); return; } DeleteCommand command = new DeleteCommand(Opcode.Delete); switch (argumentsArray.Length) { case 1: command.Key = argumentsArray[0]; break; case 2: if (argumentsArray[1] != "noreply") command.ErrorMessage = "CLIENT_ERROR bad command line format. Usage: delete <key> [noreply]"; else { command.Key = argumentsArray[0]; command.NoReply = true; } break; default: command.ErrorMessage = "CLIENT_ERROR bad command line format. Usage: delete <key> [noreply]"; break; } _command = command; this.State = ParserState.ReadyToDispatch; } private void CreateRetrievalCommand(string arguments, Opcode cmdType) { if (arguments == null) { CreateInvalidCommand(); return; } string[] argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length == 0) { _command = new InvalidCommand(); } else { GetCommand getCommand = new GetCommand(cmdType); getCommand.Keys = argumentsArray; _command = getCommand; } this.State = ParserState.ReadyToDispatch; } private void CreateStorageCommand(string arguments, Opcode cmdType) { if (arguments == null) { CreateInvalidCommand(); return; } string[] argumentsArray = arguments.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (argumentsArray.Length < 4 || argumentsArray.Length > 6) { CreateInvalidCommand("CLIENT_ERROR bad command line format"); return; } else { try { string key = argumentsArray[0]; uint flags = UInt32.Parse(argumentsArray[1]); long expTime = long.Parse(argumentsArray[2]); int bytes = int.Parse(argumentsArray[3]); if (cmdType == Opcode.CAS) { ulong casUnique = ulong.Parse(argumentsArray[4]); _command = new StorageCommand(cmdType, key, flags, expTime, casUnique, bytes); if (argumentsArray.Length > 5 && argumentsArray[5] == "noreply") _command.NoReply = true; } else { _command = new StorageCommand(cmdType, key, flags, expTime, bytes); if (argumentsArray.Length > 4 && argumentsArray[4] == "noreply") _command.NoReply = true; } this.State = ParserState.WaitingForData; } catch (Exception e) { CreateInvalidCommand("CLIENT_ERROR bad command line format"); return; } } } private void CreateInvalidCommand(string error = null) { _command = new InvalidCommand(error); this.State = ParserState.ReadyToDispatch; return; } public void Build(byte[] data) { StorageCommand command = (StorageCommand)_command; if ((char)data[command.DataSize] != '\r' || (char)data[command.DataSize + 1] != '\n') { command.ErrorMessage = "CLIENT_ERROR bad data chunk"; } else { byte[] dataToStore = new byte[command.DataSize]; Buffer.BlockCopy(data, 0, dataToStore, 0, command.DataSize); command.DataBlock = (object)dataToStore; } this.State = ParserState.ReadyToDispatch; } public int CommandDataSize { get { StorageCommand cmd=_command as StorageCommand; return cmd!=null?cmd.DataSize:0; } } public override void StartParser() { try { string command = null; int noOfBytes = 0; bool go = true; do { lock (this) { if (_inputDataStream.Lenght == 0 && this.State != ParserState.ReadyToDispatch) { this.Alive = false; return; } } switch (this.State) { case ParserState.Ready: noOfBytes = _inputDataStream.Read(_rawData, _rawDataOffset, 1); _rawDataOffset += noOfBytes; if (_rawDataOffset > 1 && (char)_rawData[_rawDataOffset - 2] == '\r' && (char)_rawData[_rawDataOffset - 1] == '\n') { command = MemcachedEncoding.BinaryConverter.GetString(_rawData, 0, (_rawDataOffset - 2)); this.Parse(command); _rawDataOffset = 0; } if (_rawDataOffset == _rawData.Length) { byte[] newBuffer = new byte[_rawData.Length * 2]; Buffer.BlockCopy(_rawData, 0, newBuffer, 0, _rawData.Length); _rawData = newBuffer; } if (_rawDataOffset > MemConfiguration.MaximumCommandLength) { TcpNetworkGateway.DisposeClient(_memTcpClient); return; } break; case ParserState.WaitingForData: noOfBytes = _inputDataStream.Read(_rawData, _rawDataOffset, this.CommandDataSize + 2 - _rawDataOffset); _rawDataOffset += noOfBytes; if (_rawDataOffset == this.CommandDataSize + 2) { _rawDataOffset = 0; this.Build(_rawData); } break; case ParserState.ReadyToDispatch: _logManager.Debug("TextProtocolParser", _command.Opcode + " command recieved."); ConsumerStatus executionMgrStatus = _commandConsumer.RegisterCommand(_command); this.State = ParserState.Ready; go = executionMgrStatus == ConsumerStatus.Running; break; } } while (go); } catch (Exception e) { _logManager.Fatal("TextProtocolParser", "Exception occured while parsing text command. " + e.Message); TcpNetworkGateway.DisposeClient(_memTcpClient); return; } this.Dispatch(); } } }
using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Logic; using IRTaktiks.Components.Menu; using IRTaktiks.Components.Manager; using IRTaktiks.Input; using IRTaktiks.Input.EventArgs; using IRTaktiks.Components.Action; namespace IRTaktiks.Components.Playable { /// <summary> /// Representation of one combat unit of the game. /// </summary> public class Unit : DrawableGameComponent { #region Statuses /// <summary> /// The actual life points of the unit. /// </summary> private int LifeField; /// <summary> /// The actual life points of the unit. /// </summary> public int Life { get { return LifeField; } set { if (value >= this.Attributes.MaximumLife) { LifeField = this.Attributes.MaximumLife; } else if (value <= 0) { LifeField = 0; } else { LifeField = value; } } } /// <summary> /// The actual mana points of the unit. /// </summary> private int ManaField; /// <summary> /// The actual mana points of the unit. /// </summary> public int Mana { get { return ManaField; } set { if (value >= this.Attributes.MaximumMana) { ManaField = this.Attributes.MaximumMana; } else if (value <= 0) { ManaField = 0; } else { ManaField = value; } } } /// <summary> /// The actual time of the wait to act. /// Mininum value is 0 and maximum is 1. /// </summary> private double TimeField; /// <summary> /// The actual time of the wait to act. /// Mininum value is 0 and maximum is 1. /// </summary> public double Time { get { return TimeField; } set { if (value >= 1) { TimeField = 1; } else if (value <= 0) { TimeField = 0; } else { TimeField = value; } } } /// <summary> /// The orientation of the unit. /// </summary> private Orientation OrientationField; /// <summary> /// The orientation of the unit. /// </summary> public Orientation Orientation { get { return OrientationField; } set { OrientationField = value; } } #endregion #region Verifications /// <summary> /// True if the unit is dead. Else otherwise. /// </summary> public bool IsDead { get { return this.Life <= 0; } } /// <summary> /// True if the unit is waiting. Else otherwise. /// </summary> public bool IsWaiting { get { return this.Time < 1; } } /// <summary> /// True if the actual life of the unit is above 50%. /// </summary> public bool IsStatusAlive { get { return ((float)this.Life / (float)this.Attributes.MaximumLife) > 0.5; } } /// <summary> /// True if the actual life of the unit is above 10% and less 50%. /// </summary> public bool IsStatusDamaged { get { return (((float)this.Life / (float)this.Attributes.MaximumLife) <= 0.5 && (((float)this.Life / (float)this.Attributes.MaximumLife) >= 0.1)); } } /// <summary> /// True if the actual life of the unit is less 10%. /// </summary> public bool IsStatusDeading { get { return ((float)this.Life / (float)this.Attributes.MaximumLife) < 0.1; } } /// <summary> /// True if the unit can act on the menu. /// </summary> public bool CanAct { get { return this.Time == 1; } } #endregion #region Properties /// <summary> /// The owner of the unit. /// </summary> private Player PlayerField; /// <summary> /// The owner of the unit. /// </summary> public Player Player { get { return PlayerField; } } /// <summary> /// Name of unit. /// </summary> private String NameField; /// <summary> /// Name of unit. /// </summary> public String Name { get { return NameField; } } /// <summary> /// Menu of the status of the unit. /// </summary> private StatusMenu StatusMenuField; /// <summary> /// Menu of the status of the unit. /// </summary> public StatusMenu StatusMenu { get { return StatusMenuField; } } /// <summary> /// The attributes of the unit. /// </summary> private Attributes AttributesField; /// <summary> /// The attributes of the unit. /// </summary> public Attributes Attributes { get { return AttributesField; } } /// <summary> /// The position of the Unit. /// </summary> private Vector2 PositionField; /// <summary> /// The position of the Unit. /// </summary> public Vector2 Position { get { return PositionField; } set { PositionField = value; } } /// <summary> /// The character texture of the unit. /// </summary> private Texture2D TextureField; /// <summary> /// The character texture of the unit. /// </summary> public Texture2D Texture { get { return TextureField; } } #endregion #region Actions /// <summary> /// The attack list of the unit. /// </summary> private List<Attack> AttacksField; /// <summary> /// The attack list of the unit. /// </summary> public List<Attack> Attacks { get { return AttacksField; } } /// <summary> /// The skill list of the unit. /// </summary> private List<Skill> SkillsField; /// <summary> /// The skill list of the unit. /// </summary> public List<Skill> Skills { get { return SkillsField; } } /// <summary> /// The item list of the unit. /// </summary> private List<Item> ItemsField; /// <summary> /// The item list of the unit. /// </summary> public List<Item> Items { get { return ItemsField; } } #endregion #region Managers /// <summary> /// The action manager of the unit. /// </summary> private ActionManager ActionManagerField; /// <summary> /// The action manager of the unit. /// </summary> public ActionManager ActionManager { get { return ActionManagerField; } } #endregion #region Logic Properties /// <summary> /// Indicates that the unit is selected. /// </summary> private bool IsSelectedField; /// <summary> /// Indicates that the unit is selected. /// </summary> public bool IsSelected { get { return IsSelectedField; } set { IsSelectedField = value; } } #endregion #region Constructor /// <summary> /// Constructor of class. /// </summary> /// <param name="game">The instance of game that is running.</param> /// <param name="player">The owner of the unit.</param> /// <param name="position">The position of the unit.</param> /// <param name="attributes">The attributes of the unit.</param> /// <param name="orientation">The orientation of the unit.</param> /// <param name="texture">The texture of the unit.</param> /// <param name="name">The name of unit.</param> public Unit(Game game, Player player, Vector2 position, Attributes attributes, Orientation orientation, Texture2D texture, String name) : base(game) { // Set the properties. this.PositionField = position; this.AttributesField = attributes; this.OrientationField = orientation; this.TextureField = texture; this.PlayerField = player; this.NameField = name; // Set the logic properties. this.LifeField = this.Attributes.MaximumLife; this.ManaField = this.Attributes.MaximumMana; this.TimeField = 0; this.IsSelectedField = false; // Load the actions this.AttacksField = AttackManager.Instance.Construct(this); this.SkillsField = SkillManager.Instance.Construct(this); this.ItemsField = ItemManager.Instance.Construct(this); // Create the menus. this.ActionManagerField = new ActionManager(game, this); this.StatusMenuField = new StatusMenu(game, this); InputManager.Instance.CursorDown += new EventHandler<CursorDownArgs>(CursorDown_Handler); } #endregion #region Component Methods /// <summary> /// Allows the game component to perform any initialization it needs to before starting /// to run. This is where it can query for any required services and load content. /// </summary> public override void Initialize() { base.Initialize(); } /// <summary> /// Allows the game component to update itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Update(GameTime gameTime) { // Update the status of the StatusMenu. this.StatusMenu.Enabled = this.IsSelected && !this.IsDead; this.StatusMenu.Visible = this.IsSelected && !this.IsDead; // Update the status of the ActionManager. this.ActionManager.Enabled = this.IsSelected && !this.IsDead && this.CanAct; this.ActionManager.Visible = this.IsSelected && !this.IsDead && this.CanAct; // Update the actual time of the unit. this.Time += this.Attributes.Delay; base.Update(gameTime); } /// <summary> /// Called when the DrawableGameComponent needs to be drawn. Override this method // with component-specific drawing code. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> public override void Draw(GameTime gameTime) { IRTGame game = this.Game as IRTGame; // Draws the unit character. game.SpriteManager.Draw(this.Texture, this.Position, new Rectangle(0, 48 * (int)this.Orientation, 32, 48), Color.White, 30); // Draws the quick status. Vector2 statusPosition = new Vector2(this.Position.X + (this.Texture.Width / 2) - (TextureManager.Instance.Sprites.Unit.QuickStatus.Width / 2), this.Position.Y + 50); game.SpriteManager.Draw(TextureManager.Instance.Sprites.Unit.QuickStatus, statusPosition, Color.White, 31); // Measure the maximum width and height for the bars. int barMaxWidth = TextureManager.Instance.Sprites.Unit.QuickStatus.Width - 2; int barMaxHeight = (TextureManager.Instance.Sprites.Unit.QuickStatus.Height - 2) / 3; // Calculates the position of the life, mana and time bars Vector2 lifePosition = new Vector2(statusPosition.X + 1, statusPosition.Y + 1); Vector2 manaPosition = new Vector2(statusPosition.X + 1, statusPosition.Y + 2 + (1 * barMaxHeight)); Vector2 timePosition = new Vector2(statusPosition.X + 1, statusPosition.Y + 3 + (2 * barMaxHeight)); // Calculates the area of the life, mana and time bars, based in unit's values. Rectangle lifeBar = new Rectangle((int)lifePosition.X, (int)lifePosition.Y, (int)((barMaxWidth * this.Life) / this.Attributes.MaximumLife), barMaxHeight); Rectangle manaBar = new Rectangle((int)manaPosition.X, (int)manaPosition.Y, (int)((barMaxWidth * this.Mana) / this.Attributes.MaximumMana), barMaxHeight); Rectangle timeBar = new Rectangle((int)timePosition.X, (int)timePosition.Y, (int)(barMaxWidth * this.Time), barMaxHeight); // Draws the life, mana and time bars. game.SpriteManager.Draw(TextureManager.Instance.Sprites.Unit.LifeBar, lifeBar, Color.White, 32); game.SpriteManager.Draw(TextureManager.Instance.Sprites.Unit.ManaBar, manaBar, Color.White, 32); game.SpriteManager.Draw(TextureManager.Instance.Sprites.Unit.TimeBar, timeBar, Color.White, 32); // Draws the arrow, if the unit is selected. if (this.IsSelected) { Vector2 arrowPosition = new Vector2(this.Position.X + (this.Texture.Width / 2) - (TextureManager.Instance.Sprites.Unit.Arrow.Width / 2), this.Position.Y - TextureManager.Instance.Sprites.Unit.Arrow.Height); game.SpriteManager.Draw(TextureManager.Instance.Sprites.Unit.Arrow, arrowPosition, Color.White, 31); } base.Draw(gameTime); } #endregion #region Input Handling /// <summary> /// Handles the CursorDown event. /// </summary> /// <param name="sender">Always null.</param> /// <param name="e">Data of event</param> private void CursorDown_Handler(object sender, CursorDownArgs e) { // Test if the unit can be selected if (!this.IsDead && !this.IsSelected) { // Touch was inside of the X area of the character. if (e.Position.X < (this.Position.X + this.Texture.Width) && e.Position.X > this.Position.X) { // Touch was inside of the Y area of the character. if (e.Position.Y < (this.Position.Y + this.Texture.Height / 4) && e.Position.Y > this.Position.Y) { // Unselect the player's units. foreach (Unit unit in this.Player.Units) { unit.IsSelected = false; } this.IsSelected = true; } } } } #endregion } }
// FIXMEs: // - some bad mappings: // - C int -> C# int // - C long -> C# int // not sure what they should be. // The sources are wrong. Those C code should not use int and long for each. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using PmDeviceID = System.Int32; using PmTimestamp = System.Int32; using PortMidiStream = System.IntPtr; using PmMessage = System.Int32; using PmError = PortMidiSharp.MidiErrorType; namespace PortMidiSharp { public class MidiDeviceManager { static MidiDeviceManager () { PortMidiMarshal.Pm_Initialize (); AppDomain.CurrentDomain.DomainUnload += delegate (object o, EventArgs e) { PortMidiMarshal.Pm_Terminate (); }; } public static int DeviceCount { get { return PortMidiMarshal.Pm_CountDevices (); } } public static int DefaultInputDeviceID { get { return PortMidiMarshal.Pm_GetDefaultInputDeviceID (); } } public static int DefaultOutputDeviceID { get { return PortMidiMarshal.Pm_GetDefaultOutputDeviceID (); } } public static IEnumerable<MidiDeviceInfo> AllDevices { get { for (int i = 0; i < DeviceCount; i++) yield return GetDeviceInfo (i); } } public static MidiDeviceInfo GetDeviceInfo (PmDeviceID id) { return new MidiDeviceInfo (id, PortMidiMarshal.Pm_GetDeviceInfo (id)); } public static MidiInput OpenInput (PmDeviceID inputDevice) { return OpenInput (inputDevice, default_buffer_size); } const int default_buffer_size = 1024; public static MidiInput OpenInput (PmDeviceID inputDevice, int bufferSize) { PortMidiStream stream; var e = PortMidiMarshal.Pm_OpenInput (out stream, inputDevice, IntPtr.Zero, bufferSize, null, IntPtr.Zero); if (e != PmError.NoError) throw new MidiException (e, String.Format ("Failed to open MIDI input device {0}", e)); return new MidiInput (stream, inputDevice); } public static MidiOutput OpenOutput (PmDeviceID outputDevice) { PortMidiStream stream; var e = PortMidiMarshal.Pm_OpenOutput (out stream, outputDevice, IntPtr.Zero, 0, null, IntPtr.Zero, 0); if (e != PmError.NoError) throw new MidiException (e, String.Format ("Failed to open MIDI output device {0}", e)); return new MidiOutput (stream, outputDevice, 0); } } public enum MidiErrorType { NoError = 0, NoData = 0, GotData = 1, HostError = -10000, InvalidDeviceId, InsufficientMemory, BufferTooSmall, BufferOverflow, BadPointer, BadData, InternalError, BufferMaxSize, } public class MidiException : Exception { PmError error_type; public MidiException (PmError errorType, string message) : this (errorType, message, null) { } public MidiException (PmError errorType, string message, Exception innerException) : base (message, innerException) { error_type = errorType; } public PmError ErrorType { get { return error_type; } } } public struct MidiDeviceInfo { PmDeviceInfo info; internal MidiDeviceInfo (int id, IntPtr ptr) { ID = id; this.info = (PmDeviceInfo) Marshal.PtrToStructure (ptr, typeof (PmDeviceInfo)); } public int ID { get; set; } public string Interface { get { return Marshal.PtrToStringAnsi (info.Interface); } } public string Name { get { return Marshal.PtrToStringAnsi (info.Name); } } public bool IsInput { get { return info.Input != 0; } } public bool IsOutput { get { return info.Output != 0; } } public bool IsOpened { get { return info.Opened != 0; } } public override string ToString () { return String.Format ("{0} - {1} ({2} {3})", Interface, Name, IsInput ? (IsOutput ? "I/O" : "Input") : (IsOutput ? "Output" : "N/A"), IsOpened ? "open" : String.Empty); } } public abstract class MidiStream : IDisposable { internal PortMidiStream stream; internal PmDeviceID device; protected MidiStream (PortMidiStream stream, PmDeviceID deviceID) { this.stream = stream; device = deviceID; } public void Abort () { PortMidiMarshal.Pm_Abort (stream); } public void Close () { Dispose (); } public void Dispose () { PortMidiMarshal.Pm_Close (stream); } public void SetFilter (MidiFilter filters) { PortMidiMarshal.Pm_SetFilter (stream, filters); } public void SetChannelMask (int mask) { PortMidiMarshal.Pm_SetChannelMask (stream, mask); } } public class MidiInput : MidiStream { public static IEnumerable<MidiEvent> Convert (byte [] bytes, int index, int size) { int i = index; int end = index + size; while (i < end) { if (bytes [i] == 0xF0 || bytes [i] == 0xF7) { var tmp = new byte [size]; Array.Copy (bytes, i, tmp, 0, tmp.Length); yield return new MidiEvent () {Message = new MidiMessage (0xF0, 0, 0), SysEx = tmp}; i += size + 1; } else { if (end < i + 3) throw new MidiException (MidiErrorType.NoError, "Received data was incomplete to build MIDI status message"); yield return new MidiEvent () {Message = new MidiMessage (bytes [i], bytes [i + 1], bytes [i + 2])}; i += 3; } } } public MidiInput (PortMidiStream stream, PmDeviceID inputDevice) : base (stream, inputDevice) { } public bool HasData { get { return PortMidiMarshal.Pm_Poll (stream) == MidiErrorType.GotData; } } public int Read (byte [] buffer, int index, int length) { var gch = GCHandle.Alloc (buffer); try { var ptr = Marshal.UnsafeAddrOfPinnedArrayElement (buffer, index); int size = PortMidiMarshal.Pm_Read (stream, ptr, length); if (size < 0) throw new MidiException ((MidiErrorType) size, PortMidiMarshal.Pm_GetErrorText ((PmError) size)); return size * 4; } finally { gch.Free (); } } } public class MidiOutput : MidiStream { public MidiOutput (PortMidiStream stream, PmDeviceID outputDevice, int latency) : base (stream, outputDevice) { } public void Write (MidiEvent mevent) { if (mevent.SysEx != null) WriteSysEx (mevent.Timestamp, mevent.SysEx); else Write (mevent.Timestamp, mevent.Message); } public void Write (PmTimestamp when, MidiMessage msg) { var ret = PortMidiMarshal.Pm_WriteShort (stream, when, msg); if (ret != PmError.NoError) throw new MidiException (ret, String.Format ("Failed to write message {0} : {1}", msg.Value, PortMidiMarshal.Pm_GetErrorText ((PmError) ret))); } public void WriteSysEx (PmTimestamp when, byte [] sysex) { var ret = PortMidiMarshal.Pm_WriteSysEx (stream, when, sysex); if (ret != PmError.NoError) throw new MidiException (ret, String.Format ("Failed to write sysex message : {0}", PortMidiMarshal.Pm_GetErrorText ((PmError) ret))); } public void Write (MidiEvent [] buffer) { Write (buffer, 0, buffer.Length); } public void Write (MidiEvent [] buffer, int index, int length) { var gch = GCHandle.Alloc (buffer); try { var ptr = Marshal.UnsafeAddrOfPinnedArrayElement (buffer, index); var ret = PortMidiMarshal.Pm_Write (stream, ptr, length); if (ret != PmError.NoError) throw new MidiException (ret, String.Format ("Failed to write messages : {0}", PortMidiMarshal.Pm_GetErrorText ((PmError) ret))); } finally { gch.Free (); } } } [StructLayout (LayoutKind.Sequential)] public struct MidiEvent { MidiMessage msg; PmTimestamp ts; [NonSerialized] byte [] sysex; public MidiMessage Message { get { return msg; } set { msg = value; } } public PmTimestamp Timestamp { get { return ts; } set { ts = value; } } // FIXME: this should be renamed as "Data" (meta events also make use of it) public byte [] SysEx { get { return sysex; } set { sysex = value; } } } public struct MidiMessage { PmMessage v; public MidiMessage (PmMessage value) { v = value; } public MidiMessage (int status, int data1, int data2) { v = ((((data2) << 16) & 0xFF0000) | (((data1) << 8) & 0xFF00) | ((status) & 0xFF)); } public PmMessage Value { get { return v; } } } public delegate PmTimestamp MidiTimeProcDelegate (IntPtr timeInfo); [Flags] public enum MidiFilter : int { Active = 1 << 0x0E, SysEx = 1 << 0x00, Clock = 1 << 0x08, Play = ((1 << 0x0A) | (1 << 0x0C) | (1 << 0x0B)), Tick = (1 << 0x09), FD = (1 << 0x0D), Undefined = FD, Reset = (1 << 0x0F), RealTime = (Active | SysEx | Clock | Play | Undefined | Reset | Tick), Note = ((1 << 0x19) | (1 << 0x18)), CAF = (1 << 0x1D), PAF = (1 << 0x1A), AF = (CAF | PAF), Program = (1 << 0x1C), Control = (1 << 0x1B), PitchBend = (1 << 0x1E), MTC = (1 << 0x01), SongPosition = (1 << 0x02), SongSelect = (1 << 0x03), Tune = (1 << 0x06), SystemCommon = (MTC | SongPosition | SongSelect | Tune) } // Marshal types class PortMidiMarshal { [DllImport ("portmidi")] public static extern PmError Pm_Initialize (); [DllImport ("portmidi")] public static extern PmError Pm_Terminate (); // TODO [DllImport ("portmidi")] public static extern int Pm_HasHostError (PortMidiStream stream); // TODO [DllImport ("portmidi")] public static extern string Pm_GetErrorText (PmError errnum); // TODO [DllImport ("portmidi")] public static extern void Pm_GetHostErrorText (IntPtr msg, uint len); const int HDRLENGTH = 50; const uint PM_HOST_ERROR_MSG_LEN = 256; // Device enumeration const PmDeviceID PmNoDevice = -1; [DllImport ("portmidi")] public static extern int Pm_CountDevices (); [DllImport ("portmidi")] public static extern PmDeviceID Pm_GetDefaultInputDeviceID (); [DllImport ("portmidi")] public static extern PmDeviceID Pm_GetDefaultOutputDeviceID (); [DllImport ("portmidi")] public static extern IntPtr Pm_GetDeviceInfo (PmDeviceID id); [DllImport ("portmidi")] public static extern PmError Pm_OpenInput ( out PortMidiStream stream, PmDeviceID inputDevice, IntPtr inputDriverInfo, int bufferSize, MidiTimeProcDelegate timeProc, IntPtr timeInfo); [DllImport ("portmidi")] public static extern PmError Pm_OpenOutput ( out PortMidiStream stream, PmDeviceID outputDevice, IntPtr outputDriverInfo, int bufferSize, MidiTimeProcDelegate time_proc, IntPtr time_info, int latency); [DllImport ("portmidi")] public static extern PmError Pm_SetFilter (PortMidiStream stream, MidiFilter filters); // TODO public static int Pm_Channel (int channel) { return 1 << channel; } [DllImport ("portmidi")] public static extern PmError Pm_SetChannelMask (PortMidiStream stream, int mask); [DllImport ("portmidi")] public static extern PmError Pm_Abort (PortMidiStream stream); [DllImport ("portmidi")] public static extern PmError Pm_Close (PortMidiStream stream); // TODO public static int Pm_MessageStatus (int msg) { return ((msg) & 0xFF); } // TODO public static int Pm_MessageData1 (int msg) { return (((msg) >> 8) & 0xFF); } // TODO public static int Pm_MessageData2 (int msg) { return (((msg) >> 16) & 0xFF); } [DllImport ("portmidi")] public static extern int Pm_Read (PortMidiStream stream, IntPtr buffer, int length); [DllImport ("portmidi")] public static extern PmError Pm_Poll (PortMidiStream stream); [DllImport ("portmidi")] public static extern PmError Pm_Write (PortMidiStream stream, IntPtr buffer, int length); [DllImport ("portmidi")] public static extern PmError Pm_WriteShort (PortMidiStream stream, PmTimestamp when, MidiMessage msg); [DllImport ("portmidi")] public static extern PmError Pm_WriteSysEx (PortMidiStream stream, PmTimestamp when, byte [] msg); } [StructLayout (LayoutKind.Sequential)] struct PmDeviceInfo { public int StructVersion; // it is not actually used. public IntPtr Interface; // char* public IntPtr Name; // char* public int Input; // 1 or 0 public int Output; // 1 or 0 public int Opened; public override string ToString () { return String.Format ("{0},{1:X},{2:X},{3},{4},{5}", StructVersion, Interface, Name, Input, Output, Opened); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.IO; using System.Globalization; using System.Runtime.Serialization; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// This class provides functionality for retrieving scheduled job run results /// from the scheduled job store. An instance of this object will be registered /// with the PowerShell JobManager so that GetJobs commands will retrieve schedule /// job runs from the file based scheduled job store. This allows scheduled job /// runs to be managed from PowerShell in the same way workflow jobs are managed. /// </summary> public sealed class ScheduledJobSourceAdapter : JobSourceAdapter { #region Private Members private static FileSystemWatcher StoreWatcher; private static object SyncObject = new object(); private static ScheduledJobRepository JobRepository = new ScheduledJobRepository(); internal const string AdapterTypeName = "PSScheduledJob"; #endregion #region Public Strings /// <summary> /// BeforeFilter. /// </summary> public const string BeforeFilter = "Before"; /// <summary> /// AfterFilter. /// </summary> public const string AfterFilter = "After"; /// <summary> /// NewestFilter. /// </summary> public const string NewestFilter = "Newest"; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public ScheduledJobSourceAdapter() { Name = AdapterTypeName; } #endregion #region JobSourceAdapter Implementation /// <summary> /// Create a new Job2 results instance. /// </summary> /// <param name="specification">Job specification.</param> /// <returns>Job2.</returns> public override Job2 NewJob(JobInvocationInfo specification) { if (specification == null) { throw new PSArgumentNullException("specification"); } ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition( specification, null, null, null); return new ScheduledJob( specification.Command, specification.Name, scheduledJobDef); } /// <summary> /// Creates a new Job2 object based on a definition name /// that can be run manually. If the path parameter is /// null then a default location will be used to find the /// job definition by name. /// </summary> /// <param name="definitionName">ScheduledJob definition name.</param> /// <param name="definitionPath">ScheduledJob definition file path.</param> /// <returns>Job2 object.</returns> public override Job2 NewJob(string definitionName, string definitionPath) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } Job2 rtnJob = null; try { ScheduledJobDefinition scheduledJobDef = ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath); rtnJob = new ScheduledJob( scheduledJobDef.Command, scheduledJobDef.Name, scheduledJobDef); } catch (FileNotFoundException) { // Return null if no job definition exists. } return rtnJob; } /// <summary> /// Get the list of jobs that are currently available in this /// store. /// </summary> /// <returns>Collection of job objects.</returns> public override IList<Job2> GetJobs() { RefreshRepository(); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { rtnJobs.Add(job); } return rtnJobs; } /// <summary> /// Get list of jobs that matches the specified names. /// </summary> /// <param name="name">names to match, can support /// wildcard if the store supports</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the specified /// criteria.</returns> public override IList<Job2> GetJobsByName(string name, bool recurse) { if (string.IsNullOrEmpty(name)) { throw new PSArgumentException("name"); } RefreshRepository(); WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (namePattern.IsMatch(job.Name)) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get list of jobs that run the specified command. /// </summary> /// <param name="command">Command to match.</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the specified /// criteria.</returns> public override IList<Job2> GetJobsByCommand(string command, bool recurse) { if (string.IsNullOrEmpty(command)) { throw new PSArgumentException("command"); } RefreshRepository(); WildcardPattern commandPattern = new WildcardPattern(command, WildcardOptions.IgnoreCase); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (commandPattern.IsMatch(job.Command)) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get job that has the specified id. /// </summary> /// <param name="instanceId">Guid to match.</param> /// <param name="recurse"></param> /// <returns>Job with the specified guid.</returns> public override Job2 GetJobByInstanceId(Guid instanceId, bool recurse) { RefreshRepository(); foreach (var job in JobRepository.Jobs) { if (Guid.Equals(job.InstanceId, instanceId)) { return job; } } return null; } /// <summary> /// Get job that has specific session id. /// </summary> /// <param name="id">Id to match.</param> /// <param name="recurse"></param> /// <returns>Job with the specified id.</returns> public override Job2 GetJobBySessionId(int id, bool recurse) { RefreshRepository(); foreach (var job in JobRepository.Jobs) { if (id == job.Id) { return job; } } return null; } /// <summary> /// Get list of jobs that are in the specified state. /// </summary> /// <param name="state">State to match.</param> /// <param name="recurse"></param> /// <returns>Collection of jobs with the specified /// state.</returns> public override IList<Job2> GetJobsByState(JobState state, bool recurse) { RefreshRepository(); List<Job2> rtnJobs = new List<Job2>(); foreach (var job in JobRepository.Jobs) { if (state == job.JobStateInfo.State) { rtnJobs.Add(job); } } return rtnJobs; } /// <summary> /// Get list of jobs based on the adapter specific /// filter parameters. /// </summary> /// <param name="filter">dictionary containing name value /// pairs for adapter specific filters</param> /// <param name="recurse"></param> /// <returns>Collection of jobs that match the /// specified criteria.</returns> public override IList<Job2> GetJobsByFilter(Dictionary<string, object> filter, bool recurse) { if (filter == null) { throw new PSArgumentNullException("filter"); } List<Job2> rtnJobs = new List<Job2>(); foreach (var filterItem in filter) { switch (filterItem.Key) { case BeforeFilter: GetJobsBefore((DateTime)filterItem.Value, ref rtnJobs); break; case AfterFilter: GetJobsAfter((DateTime)filterItem.Value, ref rtnJobs); break; case NewestFilter: GetNewestJobs((int)filterItem.Value, ref rtnJobs); break; } } return rtnJobs; } /// <summary> /// Remove a job from the store. /// </summary> /// <param name="job">Job object to remove.</param> public override void RemoveJob(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } RefreshRepository(); try { JobRepository.Remove(job); ScheduledJobStore.RemoveJobRun( job.Name, job.PSBeginTime ?? DateTime.MinValue); } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } } /// <summary> /// Saves job to scheduled job run store. /// </summary> /// <param name="job">ScheduledJob.</param> public override void PersistJob(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } SaveJobToStore(job as ScheduledJob); } #endregion #region Save Job /// <summary> /// Serializes a ScheduledJob and saves it to store. /// </summary> /// <param name="job">ScheduledJob.</param> internal static void SaveJobToStore(ScheduledJob job) { string outputPath = job.Definition.OutputPath; if (string.IsNullOrEmpty(outputPath)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified, job.Name); throw new ScheduledJobException(msg); } FileStream fsStatus = null; FileStream fsResults = null; try { // Check the job store results and if maximum number of results exist // remove the oldest results folder to make room for these new results. CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength); fsStatus = ScheduledJobStore.CreateFileForJobRunItem( outputPath, job.PSBeginTime ?? DateTime.MinValue, ScheduledJobStore.JobRunItem.Status); // Save status only in status file stream. SaveStatusToFile(job, fsStatus); fsResults = ScheduledJobStore.CreateFileForJobRunItem( outputPath, job.PSBeginTime ?? DateTime.MinValue, ScheduledJobStore.JobRunItem.Results); // Save entire job in results file stream. SaveResultsToFile(job, fsResults); } finally { if (fsStatus != null) { fsStatus.Close(); } if (fsResults != null) { fsResults.Close(); } } } /// <summary> /// Writes the job status information to the provided /// file stream. /// </summary> /// <param name="job">ScheduledJob job to save.</param> /// <param name="fs">FileStream.</param> private static void SaveStatusToFile(ScheduledJob job, FileStream fs) { StatusInfo statusInfo = new StatusInfo( job.InstanceId, job.Name, job.Location, job.Command, job.StatusMessage, job.JobStateInfo.State, job.HasMoreData, job.PSBeginTime, job.PSEndTime, job.Definition); XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); serializer.WriteObject(fs, statusInfo); fs.Flush(); } /// <summary> /// Writes the job (which implements ISerializable) to the provided /// file stream. /// </summary> /// <param name="job">ScheduledJob job to save.</param> /// <param name="fs">FileStream.</param> private static void SaveResultsToFile(ScheduledJob job, FileStream fs) { XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); serializer.WriteObject(fs, job); fs.Flush(); } /// <summary> /// Check the job store results and if maximum number of results exist /// remove the oldest results folder to make room for these new results. /// </summary> /// <param name="outputPath">Output path.</param> /// <param name="executionHistoryLength">Maximum size of stored job results.</param> private static void CheckJobStoreResults(string outputPath, int executionHistoryLength) { // Get current results for this job definition. Collection<DateTime> jobRuns = ScheduledJobStore.GetJobRunsForDefinitionPath(outputPath); if (jobRuns.Count <= executionHistoryLength) { // There is room for another job run in the store. return; } // Remove the oldest job run from the store. DateTime jobRunToRemove = DateTime.MaxValue; foreach (DateTime jobRun in jobRuns) { jobRunToRemove = (jobRun < jobRunToRemove) ? jobRun : jobRunToRemove; } try { ScheduledJobStore.RemoveJobRunFromOutputPath(outputPath, jobRunToRemove); } catch (UnauthorizedAccessException) { } } #endregion #region Retrieve Job /// <summary> /// Finds and load the Job associated with this ScheduledJobDefinition object /// having the job run date time provided. /// </summary> /// <param name="jobRun">DateTime of job run to load.</param> /// <param name="definitionName">ScheduledJobDefinition name.</param> /// <returns>Job2 job loaded from store.</returns> internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun) { FileStream fsResults = null; Exception ex = null; bool corruptedFile = false; Job2 job = null; try { // Results fsResults = ScheduledJobStore.GetFileForJobRunItem( definitionName, jobRun, ScheduledJobStore.JobRunItem.Results, FileMode.Open, FileAccess.Read, FileShare.Read); job = LoadResultsFromFile(fsResults); } catch (ArgumentException e) { ex = e; } catch (DirectoryNotFoundException e) { ex = e; } catch (FileNotFoundException e) { ex = e; corruptedFile = true; } catch (UnauthorizedAccessException e) { ex = e; } catch (IOException e) { ex = e; } catch (System.Runtime.Serialization.SerializationException) { corruptedFile = true; } catch (System.Runtime.Serialization.InvalidDataContractException) { corruptedFile = true; } catch (System.Xml.XmlException) { corruptedFile = true; } catch (System.TypeInitializationException) { corruptedFile = true; } finally { if (fsResults != null) { fsResults.Close(); } } if (corruptedFile) { // Remove the corrupted job results file. ScheduledJobStore.RemoveJobRun(definitionName, jobRun); } if (ex != null) { string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun); throw new ScheduledJobException(msg, ex); } return job; } /// <summary> /// Loads the Job2 object from provided files stream. /// </summary> /// <param name="fs">FileStream from which to read job object.</param> /// <returns>Created Job2 from file stream.</returns> private static Job2 LoadResultsFromFile(FileStream fs) { XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); return (Job2)serializer.ReadObject(fs); } #endregion #region Static Methods /// <summary> /// Adds a Job2 object to the repository. /// </summary> /// <param name="job">Job2.</param> internal static void AddToRepository(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } JobRepository.AddOrReplace(job); } /// <summary> /// Clears all items in the repository. /// </summary> internal static void ClearRepository() { JobRepository.Clear(); } /// <summary> /// Clears all items for given job definition name in the /// repository. /// </summary> /// <param name="definitionName">Scheduled job definition name.</param> internal static void ClearRepositoryForDefinition(string definitionName) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } // This returns a new list object of repository jobs. List<Job2> jobList = JobRepository.Jobs; foreach (var job in jobList) { if (string.Compare(definitionName, job.Name, StringComparison.OrdinalIgnoreCase) == 0) { JobRepository.Remove(job); } } } #endregion #region Private Methods private void RefreshRepository() { ScheduledJobStore.CreateDirectoryIfNotExists(); CreateFileSystemWatcher(); IEnumerable<string> jobDefinitions = ScheduledJobStore.GetJobDefinitions(); foreach (string definitionName in jobDefinitions) { // Create Job2 objects for each job run in store. Collection<DateTime> jobRuns = GetJobRuns(definitionName); if (jobRuns == null) { continue; } ScheduledJobDefinition definition = null; foreach (DateTime jobRun in jobRuns) { if (jobRun > JobRepository.GetLatestJobRun(definitionName)) { Job2 job; try { if (definition == null) { definition = ScheduledJobDefinition.LoadFromStore(definitionName, null); } job = LoadJobFromStore(definition.Name, jobRun); } catch (ScheduledJobException) { continue; } catch (DirectoryNotFoundException) { continue; } catch (FileNotFoundException) { continue; } catch (UnauthorizedAccessException) { continue; } catch (IOException) { continue; } JobRepository.AddOrReplace(job); JobRepository.SetLatestJobRun(definitionName, jobRun); } } } } private void CreateFileSystemWatcher() { // Lazily create the static file system watcher // on first use. if (StoreWatcher == null) { lock (SyncObject) { if (StoreWatcher == null) { StoreWatcher = new FileSystemWatcher(ScheduledJobStore.GetJobDefinitionLocation()); StoreWatcher.IncludeSubdirectories = true; StoreWatcher.NotifyFilter = NotifyFilters.LastWrite; StoreWatcher.Filter = "Results.xml"; StoreWatcher.EnableRaisingEvents = true; StoreWatcher.Changed += (object sender, FileSystemEventArgs e) => { UpdateRepositoryObjects(e); }; } } } } private static void UpdateRepositoryObjects(FileSystemEventArgs e) { // Extract job run information from change file path. string updateDefinitionName; DateTime updateJobRun; if (!GetJobRunInfo(e.Name, out updateDefinitionName, out updateJobRun)) { System.Diagnostics.Debug.Assert(false, "All job run updates should have valid directory names."); return; } // Find corresponding job in repository. ScheduledJob updateJob = JobRepository.GetJob(updateDefinitionName, updateJobRun); if (updateJob == null) { return; } // Load updated job information from store. Job2 job = null; try { job = LoadJobFromStore(updateDefinitionName, updateJobRun); } catch (ScheduledJobException) { } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } // Update job in repository based on new job store data. if (job != null) { updateJob.Update(job as ScheduledJob); } } /// <summary> /// Parses job definition name and job run DateTime from provided path string. /// Example: /// path = "ScheduledJob1\\Output\\20111219-200921-369\\Results.xml" /// 'ScheduledJob1' is the definition name. /// '20111219-200921-369' is the jobRun DateTime. /// </summary> /// <param name="path"></param> /// <param name="definitionName"></param> /// <param name="jobRunReturn"></param> /// <returns></returns> private static bool GetJobRunInfo( string path, out string definitionName, out DateTime jobRunReturn) { // Parse definition name from path. string[] pathItems = path.Split(System.IO.Path.DirectorySeparatorChar); if (pathItems.Length == 4) { definitionName = pathItems[0]; return ScheduledJobStore.ConvertJobRunNameToDateTime(pathItems[2], out jobRunReturn); } definitionName = null; jobRunReturn = DateTime.MinValue; return false; } internal static Collection<DateTime> GetJobRuns(string definitionName) { Collection<DateTime> jobRuns = null; try { jobRuns = ScheduledJobStore.GetJobRunsForDefinition(definitionName); } catch (DirectoryNotFoundException) { } catch (FileNotFoundException) { } catch (UnauthorizedAccessException) { } catch (IOException) { } return jobRuns; } private void GetJobsBefore( DateTime dateTime, ref List<Job2> jobList) { foreach (var job in JobRepository.Jobs) { if (job.PSEndTime < dateTime && !jobList.Contains(job)) { jobList.Add(job); } } } private void GetJobsAfter( DateTime dateTime, ref List<Job2> jobList) { foreach (var job in JobRepository.Jobs) { if (job.PSEndTime > dateTime && !jobList.Contains(job)) { jobList.Add(job); } } } private void GetNewestJobs( int maxNumber, ref List<Job2> jobList) { List<Job2> allJobs = JobRepository.Jobs; // Sort descending. allJobs.Sort((firstJob, secondJob) => { if (firstJob.PSEndTime > secondJob.PSEndTime) { return -1; } else if (firstJob.PSEndTime < secondJob.PSEndTime) { return 1; } else { return 0; } }); int count = 0; foreach (var job in allJobs) { if (++count > maxNumber) { break; } if (!jobList.Contains(job)) { jobList.Add(job); } } } #endregion #region Private Repository Class /// <summary> /// Collection of Job2 objects. /// </summary> internal class ScheduledJobRepository { #region Private Members private object _syncObject = new object(); private Dictionary<Guid, Job2> _jobs = new Dictionary<Guid, Job2>(); private Dictionary<string, DateTime> _latestJobRuns = new Dictionary<string, DateTime>(); #endregion #region Public Properties /// <summary> /// Returns all job objects in the repository as a List. /// </summary> public List<Job2> Jobs { get { lock (_syncObject) { return new List<Job2>(_jobs.Values); } } } /// <summary> /// Returns count of jobs in repository. /// </summary> public int Count { get { lock (_syncObject) { return _jobs.Count; } } } #endregion #region Public Methods /// <summary> /// Add Job2 to repository. /// </summary> /// <param name="job">Job2 to add.</param> public void Add(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId)) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobAlreadyExistsInLocal, job.Name, job.InstanceId); throw new ScheduledJobException(msg); } _jobs.Add(job.InstanceId, job); } } /// <summary> /// Add or replace passed in Job2 object to repository. /// </summary> /// <param name="job">Job2 to add.</param> public void AddOrReplace(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId)) { _jobs.Remove(job.InstanceId); } _jobs.Add(job.InstanceId, job); } } /// <summary> /// Remove Job2 from repository. /// </summary> /// <param name="job"></param> public void Remove(Job2 job) { if (job == null) { throw new PSArgumentNullException("job"); } lock (_syncObject) { if (_jobs.ContainsKey(job.InstanceId) == false) { string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobNotInRepository, job.Name); throw new ScheduledJobException(msg); } _jobs.Remove(job.InstanceId); } } /// <summary> /// Clears all Job2 items from the repository. /// </summary> public void Clear() { lock (_syncObject) { _jobs.Clear(); } } /// <summary> /// Gets the latest job run Date/Time for the given definition name. /// </summary> /// <param name="definitionName">ScheduledJobDefinition name.</param> /// <returns>Job Run DateTime.</returns> public DateTime GetLatestJobRun(string definitionName) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } lock (_syncObject) { if (_latestJobRuns.ContainsKey(definitionName)) { return _latestJobRuns[definitionName]; } else { DateTime startJobRun = DateTime.MinValue; _latestJobRuns.Add(definitionName, startJobRun); return startJobRun; } } } /// <summary> /// Sets the latest job run Date/Time for the given definition name. /// </summary> /// <param name="definitionName"></param> /// <param name="jobRun"></param> public void SetLatestJobRun(string definitionName, DateTime jobRun) { if (string.IsNullOrEmpty(definitionName)) { throw new PSArgumentException("definitionName"); } lock (_syncObject) { if (_latestJobRuns.ContainsKey(definitionName)) { _latestJobRuns.Remove(definitionName); _latestJobRuns.Add(definitionName, jobRun); } else { _latestJobRuns.Add(definitionName, jobRun); } } } /// <summary> /// Search repository for specific job run. /// </summary> /// <param name="definitionName">Definition name.</param> /// <param name="jobRun">Job run DateTime.</param> /// <returns>Scheduled job if found.</returns> public ScheduledJob GetJob(string definitionName, DateTime jobRun) { lock (_syncObject) { foreach (ScheduledJob job in _jobs.Values) { if (job.PSBeginTime == null) { continue; } DateTime PSBeginTime = job.PSBeginTime ?? DateTime.MinValue; if (definitionName.Equals(job.Definition.Name, StringComparison.OrdinalIgnoreCase) && jobRun.Year == PSBeginTime.Year && jobRun.Month == PSBeginTime.Month && jobRun.Day == PSBeginTime.Day && jobRun.Hour == PSBeginTime.Hour && jobRun.Minute == PSBeginTime.Minute && jobRun.Second == PSBeginTime.Second && jobRun.Millisecond == PSBeginTime.Millisecond) { return job; } } } return null; } #endregion } #endregion } }
/* ** Copyright (c) Microsoft. All rights reserved. ** Licensed under the MIT license. ** See LICENSE file in the project root for full license information. ** ** This program was translated to C# and adapted for xunit-performance. ** New variants of several tests were added to compare class versus ** struct and to compare jagged arrays vs multi-dimensional arrays. */ /* ** BYTEmark (tm) ** BYTE Magazine's Native Mode benchmarks ** Rick Grehan, BYTE Magazine ** ** Create: ** Revision: 3/95 ** ** DISCLAIMER ** The source, executable, and documentation files that comprise ** the BYTEmark benchmarks are made available on an "as is" basis. ** This means that we at BYTE Magazine have made every reasonable ** effort to verify that the there are no errors in the source and ** executable code. We cannot, however, guarantee that the programs ** are error-free. Consequently, McGraw-HIll and BYTE Magazine make ** no claims in regard to the fitness of the source code, executable ** code, and documentation of the BYTEmark. ** ** Furthermore, BYTE Magazine, McGraw-Hill, and all employees ** of McGraw-Hill cannot be held responsible for any damages resulting ** from the use of this code or the results obtained from using ** this code. */ /************* ** DoAssign ** ************** ** Perform an assignment algorithm. ** The algorithm was adapted from the step by step guide found ** in "Quantitative Decision Making for Business" (Gordon, ** Pressman, and Cohn; Prentice-Hall) ** ** ** NOTES: ** 1. Even though the algorithm distinguishes between ** ASSIGNROWS and ASSIGNCOLS, as though the two might ** be different, it does presume a square matrix. ** I.E., ASSIGNROWS and ASSIGNCOLS must be the same. ** This makes for some algorithmically-correct but ** probably non-optimal constructs. ** */ using System; public class AssignRect : AssignStruct { public override string Name() { return "ASSIGNMENT(rectangle)"; } public override double Run() { int[][,] arraybase; long accumtime; double iterations; /* ** See if we need to do self adjustment code. */ if (this.adjust == 0) { /* ** Self-adjustment code. The system begins by working on 1 ** array. If it does that in no time, then two arrays ** are built. This process continues until ** enough arrays are built to handle the tolerance. */ this.numarrays = 1; while (true) { /* ** Allocate space for arrays */ arraybase = new int[this.numarrays][,]; for (int i = 0; i < this.numarrays; i++) arraybase[i] = new int[global.ASSIGNROWS, global.ASSIGNCOLS]; /* ** Do an iteration of the assignment alg. If the ** elapsed time is less than or equal to the permitted ** minimum, then allocate for more arrays and ** try again. */ if (DoAssignIteration(arraybase, this.numarrays) > global.min_ticks) break; /* We're ok...exit */ this.numarrays++; } } else { /* ** Allocate space for arrays */ arraybase = new int[this.numarrays][,]; for (int i = 0; i < this.numarrays; i++) arraybase[i] = new int[global.ASSIGNROWS, global.ASSIGNCOLS]; } /* ** All's well if we get here. Do the tests. */ accumtime = 0; iterations = (double)0.0; do { accumtime += DoAssignIteration(arraybase, this.numarrays); iterations += (double)1.0; } while (ByteMark.TicksToSecs(accumtime) < this.request_secs); if (this.adjust == 0) this.adjust = 1; return (iterations * (double)this.numarrays / ByteMark.TicksToFracSecs(accumtime)); } /********************** ** DoAssignIteration ** *********************** ** This routine executes one iteration of the assignment test. ** It returns the number of ticks elapsed in the iteration. */ private static long DoAssignIteration(int[][,] arraybase, int numarrays) { long elapsed; /* Elapsed ticks */ int i; /* ** Load up the arrays with a random table. */ LoadAssignArrayWithRand(arraybase, numarrays); /* ** Start the stopwatch */ elapsed = ByteMark.StartStopwatch(); /* ** Execute assignment algorithms */ for (i = 0; i < numarrays; i++) { Assignment(arraybase[i]); } /* ** Get elapsed time */ return (ByteMark.StopStopwatch(elapsed)); } /**************************** ** LoadAssignArrayWithRand ** ***************************** ** Load the assignment arrays with random numbers. All positive. ** These numbers represent costs. */ private static void LoadAssignArrayWithRand(int[][,] arraybase, int numarrays) { int i; /* ** Set up the first array. Then just copy it into the ** others. */ LoadAssign(arraybase[0]); if (numarrays > 1) for (i = 1; i < numarrays; i++) { CopyToAssign(arraybase[0], arraybase[i]); } return; } /*************** ** LoadAssign ** **************** ** The array given by arraybase is loaded with positive random ** numbers. Elements in the array are capped at 5,000,000. */ private static void LoadAssign(int[,] arraybase) { short i, j; /* ** Reset random number generator so things repeat. */ ByteMark.randnum(13); for (i = 0; i < global.ASSIGNROWS; i++) for (j = 0; j < global.ASSIGNROWS; j++) arraybase[i, j] = ByteMark.abs_randwc(5000000); return; } /***************** ** CopyToAssign ** ****************** ** Copy the contents of one array to another. This is called by ** the routine that builds the initial array, and is used to copy ** the contents of the intial array into all following arrays. */ private static void CopyToAssign(int[,] arrayfrom, int[,] arrayto) { short i, j; for (i = 0; i < global.ASSIGNROWS; i++) for (j = 0; j < global.ASSIGNCOLS; j++) arrayto[i, j] = arrayfrom[i, j]; return; } /*************** ** Assignment ** ***************/ private static void Assignment(int[,] arraybase) { short[,] assignedtableau = new short[global.ASSIGNROWS, global.ASSIGNCOLS]; /* ** First, calculate minimum costs */ calc_minimum_costs(arraybase); /* ** Repeat following until the number of rows selected ** equals the number of rows in the tableau. */ while (first_assignments(arraybase, assignedtableau) != global.ASSIGNROWS) { second_assignments(arraybase, assignedtableau); } return; } /*********************** ** calc_minimum_costs ** ************************ ** Revise the tableau by calculating the minimum costs on a ** row and column basis. These minima are subtracted from ** their rows and columns, creating a new tableau. */ private static void calc_minimum_costs(int[,] tableau) { short i, j; /* Index variables */ int currentmin; /* Current minimum */ /* ** Determine minimum costs on row basis. This is done by ** subtracting -- on a row-per-row basis -- the minum value ** for that row. */ for (i = 0; i < global.ASSIGNROWS; i++) { currentmin = global.MAXPOSLONG; /* Initialize minimum */ for (j = 0; j < global.ASSIGNCOLS; j++) if (tableau[i, j] < currentmin) currentmin = tableau[i, j]; for (j = 0; j < global.ASSIGNCOLS; j++) tableau[i, j] -= currentmin; } /* ** Determine minimum cost on a column basis. This works ** just as above, only now we step through the array ** column-wise */ for (j = 0; j < global.ASSIGNCOLS; j++) { currentmin = global.MAXPOSLONG; /* Initialize minimum */ for (i = 0; i < global.ASSIGNROWS; i++) if (tableau[i, j] < currentmin) currentmin = tableau[i, j]; /* ** Here, we'll take the trouble to see if the current ** minimum is zero. This is likely worth it, since the ** preceding loop will have created at least one zero in ** each row. We can save ourselves a few iterations. */ if (currentmin != 0) for (i = 0; i < global.ASSIGNROWS; i++) tableau[i, j] -= currentmin; } return; } /********************** ** first_assignments ** *********************** ** Do first assignments. ** The assignedtableau[] array holds a set of values that ** indicate the assignment of a value, or its elimination. ** The values are: ** 0 = Item is neither assigned nor eliminated. ** 1 = Item is assigned ** 2 = Item is eliminated ** Returns the number of selections made. If this equals ** the number of rows, then an optimum has been determined. */ private static int first_assignments(int[,] tableau, short[,] assignedtableau) { short i, j, k; /* Index variables */ short numassigns; /* # of assignments */ short totnumassigns; /* Total # of assignments */ short numzeros; /* # of zeros in row */ int selected = 0; /* Flag used to indicate selection */ /* ** Clear the assignedtableau, setting all members to show that ** no one is yet assigned, eliminated, or anything. */ for (i = 0; i < global.ASSIGNROWS; i++) for (j = 0; j < global.ASSIGNCOLS; j++) assignedtableau[i, j] = 0; totnumassigns = 0; do { numassigns = 0; /* ** Step through rows. For each one that is not currently ** assigned, see if the row has only one zero in it. If so, ** mark that as an assigned row/col. Eliminate other zeros ** in the same column. */ for (i = 0; i < global.ASSIGNROWS; i++) { numzeros = 0; for (j = 0; j < global.ASSIGNCOLS; j++) if (tableau[i, j] == 0) if (assignedtableau[i, j] == 0) { numzeros++; selected = j; } if (numzeros == 1) { numassigns++; totnumassigns++; assignedtableau[i, selected] = 1; for (k = 0; k < global.ASSIGNROWS; k++) if ((k != i) && (tableau[k, selected] == 0)) assignedtableau[k, selected] = 2; } } /* ** Step through columns, doing same as above. Now, be careful ** of items in the other rows of a selected column. */ for (j = 0; j < global.ASSIGNCOLS; j++) { numzeros = 0; for (i = 0; i < global.ASSIGNROWS; i++) if (tableau[i, j] == 0) if (assignedtableau[i, j] == 0) { numzeros++; selected = i; } if (numzeros == 1) { numassigns++; totnumassigns++; assignedtableau[selected, j] = 1; for (k = 0; k < global.ASSIGNCOLS; k++) if ((k != j) && (tableau[selected, k] == 0)) assignedtableau[selected, k] = 2; } } /* ** Repeat until no more assignments to be made. */ } while (numassigns != 0); /* ** See if we can leave at this point. */ if (totnumassigns == global.ASSIGNROWS) return (totnumassigns); /* ** Now step through the array by row. If you find any unassigned ** zeros, pick the first in the row. Eliminate all zeros from ** that same row & column. This occurs if there are multiple optima... ** possibly. */ for (i = 0; i < global.ASSIGNROWS; i++) { selected = -1; for (j = 0; j < global.ASSIGNCOLS; j++) if ((tableau[i, j] == 0) && (assignedtableau[i, j] == 0)) { selected = j; break; } if (selected != -1) { assignedtableau[i, selected] = 1; totnumassigns++; for (k = 0; k < global.ASSIGNCOLS; k++) if ((k != selected) && (tableau[i, k] == 0)) assignedtableau[i, k] = 2; for (k = 0; k < global.ASSIGNROWS; k++) if ((k != i) && (tableau[k, selected] == 0)) assignedtableau[k, selected] = 2; } } return (totnumassigns); } /*********************** ** second_assignments ** ************************ ** This section of the algorithm creates the revised ** tableau, and is difficult to explain. I suggest you ** refer to the algorithm's source, mentioned in comments ** toward the beginning of the program. */ private static void second_assignments(int[,] tableau, short[,] assignedtableau) { int i, j; /* Indexes */ short[] linesrow = new short[global.ASSIGNROWS]; short[] linescol = new short[global.ASSIGNCOLS]; int smallest; /* Holds smallest value */ short numassigns; /* Number of assignments */ short newrows; /* New rows to be considered */ /* ** Clear the linesrow and linescol arrays. */ for (i = 0; i < global.ASSIGNROWS; i++) linesrow[i] = 0; for (i = 0; i < global.ASSIGNCOLS; i++) linescol[i] = 0; /* ** Scan rows, flag each row that has no assignment in it. */ for (i = 0; i < global.ASSIGNROWS; i++) { numassigns = 0; for (j = 0; j < global.ASSIGNCOLS; j++) if (assignedtableau[i, j] == 1) { numassigns++; break; } if (numassigns == 0) linesrow[i] = 1; } do { newrows = 0; /* ** For each row checked above, scan for any zeros. If found, ** check the associated column. */ for (i = 0; i < global.ASSIGNROWS; i++) { if (linesrow[i] == 1) for (j = 0; j < global.ASSIGNCOLS; j++) if (tableau[i, j] == 0) linescol[j] = 1; } /* ** Now scan checked columns. If any contain assigned zeros, check ** the associated row. */ for (j = 0; j < global.ASSIGNCOLS; j++) if (linescol[j] == 1) for (i = 0; i < global.ASSIGNROWS; i++) if ((assignedtableau[i, j] == 1) && (linesrow[i] != 1)) { linesrow[i] = 1; newrows++; } } while (newrows != 0); /* ** linesrow[n]==0 indicate rows covered by imaginary line ** linescol[n]==1 indicate cols covered by imaginary line ** For all cells not covered by imaginary lines, determine smallest ** value. */ smallest = global.MAXPOSLONG; for (i = 0; i < global.ASSIGNROWS; i++) if (linesrow[i] != 0) for (j = 0; j < global.ASSIGNCOLS; j++) if (linescol[j] != 1) if (tableau[i, j] < smallest) smallest = tableau[i, j]; /* ** Subtract smallest from all cells in the above set. */ for (i = 0; i < global.ASSIGNROWS; i++) if (linesrow[i] != 0) for (j = 0; j < global.ASSIGNCOLS; j++) if (linescol[j] != 1) tableau[i, j] -= smallest; /* ** Add smallest to all cells covered by two lines. */ for (i = 0; i < global.ASSIGNROWS; i++) if (linesrow[i] == 0) for (j = 0; j < global.ASSIGNCOLS; j++) if (linescol[j] == 1) tableau[i, j] += smallest; return; } }
/* * Deed API * * Land Registry Deed API * * OpenAPI spec version: 2.3.1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Swagger.Client; using IO.Swagger.Model; namespace IO.Swagger.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IDefaultApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> string AddDeed (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> ApiResponse<string> AddDeedWithHttpInfo (DeedApplication body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body); /// <summary> /// Deed /// </summary> /// <remarks> /// The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </remarks> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class DefaultApi : IDefaultApi { private IO.Swagger.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class. /// </summary> /// <returns></returns> public DefaultApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="DefaultApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public DefaultApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Swagger.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Swagger.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>string</returns> public string AddDeed (DeedApplication body) { ApiResponse<string> localVarResponse = AddDeedWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>ApiResponse of string</returns> public ApiResponse< string > AddDeedWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of string</returns> public async System.Threading.Tasks.Task<string> AddDeedAsync (DeedApplication body) { ApiResponse<string> localVarResponse = await AddDeedAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Deed The post Deed endpoint creates a new deed based on the JSON provided. The reponse will return a URL that can retrieve the created deed. &gt; REQUIRED: Land Registry system requests Conveyancer to confirm that the Borrowers identity has been established in accordance with Section 111 of the Network Access Agreement. /// </summary> /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body"></param> /// <returns>Task of ApiResponse (string)</returns> public async System.Threading.Tasks.Task<ApiResponse<string>> AddDeedAsyncWithHttpInfo (DeedApplication body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling DefaultApi->AddDeed"); var localVarPath = "/deed/"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddDeed", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<string>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (string) Configuration.ApiClient.Deserialize(localVarResponse, typeof(string))); } } }
// // main.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Paul Lange <palango@gmx.de> // Evan Briones <erbriones@gmail.com> // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2010 Paul Lange // Copyright (C) 2010 Evan Briones // Copyright (C) 2006-2009 Stephane Delcroix // // 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.Reflection; using System.IO; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Mono.Addins.Setup; using FSpot.Core; using FSpot.Utils; using FSpot.Imaging; using Hyena; using Hyena.CommandLine; using Hyena.Gui; namespace FSpot { public static class Driver { private static void ShowVersion () { Console.WriteLine ("F-Spot {0}", Defines.VERSION); Console.WriteLine ("http://f-spot.org"); Console.WriteLine ("\t(c)2003-2009, Novell Inc"); Console.WriteLine ("\t(c)2009 Stephane Delcroix"); Console.WriteLine("Personal photo management for the GNOME Desktop"); } private static void ShowAssemblyVersions () { ShowVersion (); Console.WriteLine (); Console.WriteLine ("Mono/.NET Version: " + Environment.Version.ToString ()); Console.WriteLine (String.Format ("{0}Assembly Version Information:", Environment.NewLine)); foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) { AssemblyName name = asm.GetName (); Console.WriteLine ("\t" + name.Name + " (" + name.Version.ToString () + ")"); } } private static void ShowHelp () { Console.WriteLine ("Usage: f-spot [options...] [files|URIs...]"); Console.WriteLine (); Hyena.CommandLine.Layout commands = new Hyena.CommandLine.Layout ( new LayoutGroup ("help", "Help Options", new LayoutOption ("help", "Show this help"), new LayoutOption ("help-options", "Show command line options"), new LayoutOption ("help-all", "Show all options"), new LayoutOption ("version", "Show version information"), new LayoutOption ("versions", "Show detailed version information")), new LayoutGroup ("options", "General options", new LayoutOption ("basedir=DIR", "Path to the photo database folder"), new LayoutOption ("import=URI", "Import from the given uri"), new LayoutOption ("photodir=DIR", "Default import folder"), new LayoutOption ("view ITEM", "View file(s) or directories"), new LayoutOption ("shutdown", "Shut down a running instance of F-Spot"), new LayoutOption ("slideshow", "Display a slideshow"), new LayoutOption ("debug", "Run in debug mode"))); if (ApplicationContext.CommandLine.Contains ("help-all")) { Console.WriteLine (commands); return; } List<string> errors = null; foreach (KeyValuePair<string, string> argument in ApplicationContext.CommandLine.Arguments) { switch (argument.Key) { case "help": Console.WriteLine (commands.ToString ("help")); break; case "help-options": Console.WriteLine (commands.ToString ("options")); break; default: if (argument.Key.StartsWith ("help")) { (errors ?? (errors = new List<string> ())).Add (argument.Key); } break; } } if (errors != null) { Console.WriteLine (commands.LayoutLine (String.Format ( "The following help arguments are invalid: {0}", Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", ")))); } } static string [] FixArgs (string [] args) { // Makes sure command line arguments are parsed backwards compatible. var outargs = new List<string> (); for (int i = 0; i < args.Length; i++) { switch (args [i]) { case "-h": case "-help": case "-usage": outargs.Add ("--help"); break; case "-V": case "-version": outargs.Add ("--version"); break; case "-versions": outargs.Add ("--versions"); break; case "-shutdown": outargs.Add ("--shutdown"); break; case "-b": case "-basedir": case "--basedir": outargs.Add ("--basedir=" + (i + 1 == args.Length ? String.Empty : args [++i])); break; case "-p": case "-photodir": case "--photodir": outargs.Add ("--photodir=" + (i + 1 == args.Length ? String.Empty : args [++i])); break; case "-i": case "-import": case "--import": outargs.Add ("--import=" + (i + 1 == args.Length ? String.Empty : args [++i])); break; case "-v": case "-view": outargs.Add ("--view"); break; case "-slideshow": outargs.Add ("--slideshow"); break; default: outargs.Add (args [i]); break; } } return outargs.ToArray (); } static int Main (string [] args) { args = FixArgs (args); ApplicationContext.ApplicationName = "F-Spot"; ApplicationContext.TrySetProcessName (Defines.PACKAGE); Paths.ApplicationName = "f-spot"; ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = RunIdle; XdgThumbnailSpec.DefaultLoader = (uri) => { using (var file = ImageFile.Create (uri)) return file.Load (); }; // Options and Option parsing bool shutdown = false; bool view = false; bool slideshow = false; bool import = false; GLib.GType.Init (); Catalog.Init ("f-spot", Defines.LOCALE_DIR); FSpot.Core.Global.PhotoUri = new SafeUri (Preferences.Get<string> (Preferences.STORAGE_PATH)); ApplicationContext.CommandLine = new CommandLineParser (args, 0); if (ApplicationContext.CommandLine.ContainsStart ("help")) { ShowHelp (); return 0; } if (ApplicationContext.CommandLine.Contains ("version")) { ShowVersion (); return 0; } if (ApplicationContext.CommandLine.Contains ("versions")) { ShowAssemblyVersions (); return 0; } if (ApplicationContext.CommandLine.Contains ("shutdown")) { Log.Information ("Shutting down existing F-Spot server..."); shutdown = true; } if (ApplicationContext.CommandLine.Contains ("slideshow")) { Log.Information ("Running F-Spot in slideshow mode."); slideshow = true; } if (ApplicationContext.CommandLine.Contains ("basedir")) { string dir = ApplicationContext.CommandLine ["basedir"]; if (!string.IsNullOrEmpty (dir)) { FSpot.Core.Global.BaseDirectory = dir; Log.InformationFormat ("BaseDirectory is now {0}", dir); } else { Log.Error ("f-spot: -basedir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("photodir")) { string dir = ApplicationContext.CommandLine ["photodir"]; if (!string.IsNullOrEmpty (dir)) { FSpot.Core.Global.PhotoUri = new SafeUri (dir); Log.InformationFormat ("PhotoDirectory is now {0}", dir); } else { Log.Error ("f-spot: -photodir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("import")) import = true; if (ApplicationContext.CommandLine.Contains ("view")) view = true; if (ApplicationContext.CommandLine.Contains ("debug")) { Log.Debugging = true; // Debug GdkPixbuf critical warnings GLib.LogFunc logFunc = new GLib.LogFunc (GLib.Log.PrintTraceLogFunction); GLib.Log.SetLogHandler ("GdkPixbuf", GLib.LogLevelFlags.Critical, logFunc); // Debug Gtk critical warnings GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, logFunc); // Debug GLib critical warnings GLib.Log.SetLogHandler ("GLib", GLib.LogLevelFlags.Critical, logFunc); //Debug GLib-GObject critical warnings GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Critical, logFunc); GLib.Log.SetLogHandler ("GLib-GIO", GLib.LogLevelFlags.Critical, logFunc); } // Validate command line options if ((import && (view || shutdown || slideshow)) || (view && (shutdown || slideshow)) || (shutdown && slideshow)) { Log.Error ("Can't mix -import, -view, -shutdown or -slideshow"); return 1; } InitializeAddins (); // Gtk initialization Gtk.Application.Init (Defines.PACKAGE, ref args); // Maybe we'll add this at a future date //Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk); // init web proxy globally Platform.WebProxy.Init (); if (File.Exists (Preferences.Get<string> (Preferences.GTK_RC))) { if (File.Exists (Path.Combine (FSpot.Core.Global.BaseDirectory, "gtkrc"))) Gtk.Rc.AddDefaultFile (Path.Combine (FSpot.Core.Global.BaseDirectory, "gtkrc")); FSpot.Core.Global.DefaultRcFiles = Gtk.Rc.DefaultFiles; Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GTK_RC)); Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true); } try { Gtk.Window.DefaultIconList = new Gdk.Pixbuf [] { GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot", 16, (Gtk.IconLookupFlags)0), GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot", 22, (Gtk.IconLookupFlags)0), GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot", 32, (Gtk.IconLookupFlags)0), GtkUtil.TryLoadIcon (FSpot.Core.Global.IconTheme, "f-spot", 48, (Gtk.IconLookupFlags)0) }; } catch {} CleanRoomStartup.Startup (Startup); return 0; } static void InitializeAddins () { uint timer = Log.InformationTimerStart ("Initializing Mono.Addins"); try { UpdatePlugins (); } catch (Exception) { Log.Debug ("Failed to initialize plugins, will remove addin-db and try again."); ResetPluginDb (); } SetupService setupService = new SetupService (AddinManager.Registry); foreach (AddinRepository repo in setupService.Repositories.GetRepositories ()) { if (repo.Url.StartsWith ("http://addins.f-spot.org/")) { Log.InformationFormat ("Unregistering {0}", repo.Url); setupService.Repositories.RemoveRepository (repo.Url); } } Log.DebugTimerPrint (timer, "Mono.Addins Initialization took {0}"); } static void UpdatePlugins () { AddinManager.Initialize (FSpot.Core.Global.BaseDirectory); AddinManager.Registry.Update (null); } static void ResetPluginDb () { // Nuke addin-db var directory = GLib.FileFactory.NewForUri (new SafeUri (FSpot.Core.Global.BaseDirectory)); var list = directory.EnumerateChildren ("standard::name", GLib.FileQueryInfoFlags.None, null); foreach (GLib.FileInfo info in list) { if (info.Name.StartsWith ("addin-db-")) { var file = GLib.FileFactory.NewForPath (Path.Combine (directory.Path, info.Name)); file.DeleteRecursive (); } } // Try again UpdatePlugins (); } static void Startup () { if (ApplicationContext.CommandLine.Contains ("slideshow")) App.Instance.Slideshow (null); else if (ApplicationContext.CommandLine.Contains ("shutdown")) App.Instance.Shutdown (); else if (ApplicationContext.CommandLine.Contains ("view")) { if (ApplicationContext.CommandLine.Files.Count == 0) { Log.Error ("f-spot: -view option takes at least one argument"); System.Environment.Exit (1); } var list = new UriList (); foreach (var f in ApplicationContext.CommandLine.Files) list.AddUnknown (f); if (list.Count == 0) { ShowHelp (); System.Environment.Exit (1); } App.Instance.View (list); } else if (ApplicationContext.CommandLine.Contains ("import")) { string dir = ApplicationContext.CommandLine ["import"]; if (string.IsNullOrEmpty (dir)) { Log.Error ("f-spot: -import option takes one argument"); System.Environment.Exit (1); } App.Instance.Import (dir); } else App.Instance.Organize (); if (!App.Instance.IsRunning) Gtk.Application.Run (); } public static void RunIdle (InvokeHandler handler) { GLib.Idle.Add (delegate { handler (); return false; }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting; using Xunit; namespace System.Tests { public class ActivatorNetcoreTests : RemoteExecutorTestBase { [Fact] public static void CreateInstance_Invalid() { foreach (Type nonRuntimeType in Helpers.NonRuntimeTypes) { // Type is not a valid RuntimeType AssertExtensions.Throws<ArgumentException>("type", () => Activator.CreateInstance(nonRuntimeType)); } } [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleData))] public static void TestingCreateInstanceFromObjectHandle(string physicalFileName, string assemblyFile, string type, string returnedFullNameType, Type exceptionType) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type); CheckValidity(oh, returnedFullNameType); } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null)); } else { oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, null); CheckValidity(oh, returnedFullNameType); } Assert.True(File.Exists(physicalFileName)); } public static TheoryData<string, string, string, string, Type> TestingCreateInstanceFromObjectHandleData => new TheoryData<string, string, string, string, Type>() { // string physicalFileName, string assemblyFile, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", "PublicClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", "PublicClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", "PrivateClassSample", null }, { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException) }, { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException) }, { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException) } }; [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleData))] public static void TestingCreateInstanceObjectHandle(string assemblyName, string type, string returnedFullNameType, Type exceptionType, bool returnNull) { ObjectHandle oh = null; if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } if (exceptionType != null) { Assert.Throws(exceptionType, () => Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null)); } else { oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, null); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } } public static TheoryData<string, string, string, Type, bool> TestingCreateInstanceObjectHandleData => new TheoryData<string, string, string, Type, bool>() { // string assemblyName, string typeName, returnedFullNameType, expectedException { "TestLoadAssembly", "PublicClassSample", "PublicClassSample", null, false }, { "testloadassembly", "publicclasssample", "PublicClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PrivateClassSample", "PrivateClassSample", null, false }, { "testloadassembly", "privateclasssample", "PrivateClassSample", typeof(TypeLoadException), false }, { "TestLoadAssembly", "PublicClassNoDefaultConstructorSample", "PublicClassNoDefaultConstructorSample", typeof(MissingMethodException), false }, { "testloadassembly", "publicclassnodefaultconstructorsample", "PublicClassNoDefaultConstructorSample", typeof(TypeLoadException), false }, { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", "", null, true } }; [Theory] [MemberData(nameof(TestingCreateInstanceFromObjectHandleFullSignatureData))] public static void TestingCreateInstanceFromObjectHandleFullSignature(string physicalFileName, string assemblyFile, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstanceFrom(assemblyFile: assemblyFile, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); Assert.True(File.Exists(physicalFileName)); } public static IEnumerable<object[]> TestingCreateInstanceFromObjectHandleFullSignatureData() { // string physicalFileName, string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "TestLoadAssembly.dll", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; yield return new object[] { "TestLoadAssembly.dll", "testloadassembly.dll", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample" }; } [Theory] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureData))] public static void TestingCreateInstanceObjectHandleFullSignature(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType, bool returnNull) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); if (returnNull) { Assert.Null(oh); } else { CheckValidity(oh, returnedFullNameType); } } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PublicClassSample", false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "testloadassembly", "publicclasssample", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PublicClassSample" , false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "TestLoadAssembly", "PrivateClassSample", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { "testloadassembly", "privateclasssample", true, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[1] { 1 }, CultureInfo.InvariantCulture, null, "PrivateClassSample", false }; yield return new object[] { null, typeof(PublicType).FullName, false, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PublicType).FullName, false }; yield return new object[] { null, typeof(PrivateType).FullName, false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, typeof(PrivateType).FullName, false }; yield return new object[] { "mscorlib", "System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", true, BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "", true }; } [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWinRTSupported), nameof(PlatformDetection.IsNotWindows8x), nameof(PlatformDetection.IsNotWindowsServerCore), nameof(PlatformDetection.IsNotWindowsNanoServer), nameof(PlatformDetection.IsNotWindowsIoTCore))] [PlatformSpecific(TestPlatforms.Windows)] [MemberData(nameof(TestingCreateInstanceObjectHandleFullSignatureWinRTData))] public static void TestingCreateInstanceObjectHandleFullSignatureWinRT(string assemblyName, string type, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, string returnedFullNameType) { ObjectHandle oh = Activator.CreateInstance(assemblyName: assemblyName, typeName: type, ignoreCase: ignoreCase, bindingAttr: bindingAttr, binder: binder, args: args, culture: culture, activationAttributes: activationAttributes); CheckValidity(oh, returnedFullNameType); } public static IEnumerable<object[]> TestingCreateInstanceObjectHandleFullSignatureWinRTData() { // string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, returnedFullNameType yield return new object[] { "Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime", "Windows.Foundation.Collections.StringMap", false, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance, Type.DefaultBinder, new object[0], CultureInfo.InvariantCulture, null, "Windows.Foundation.Collections.StringMap" }; } private static void CheckValidity(ObjectHandle instance, string expected) { Assert.NotNull(instance); Assert.Equal(expected, instance.Unwrap().GetType().FullName); } public class PublicType { public PublicType() { } } private class PrivateType { public PrivateType() { } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Assembly.LoadFile is not supported in AppX.")] public static void CreateInstanceAssemblyResolve() { RemoteInvoke(() => { AppDomain.CurrentDomain.AssemblyResolve += (object sender, ResolveEventArgs args) => Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), "TestLoadAssembly.dll")); ObjectHandle oh = Activator.CreateInstance(",,,,", "PublicClassSample"); Assert.NotNull(oh.Unwrap()); }).Dispose(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; namespace OpenSim.Groups { public class HGGroupsServiceRobustConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HGGroupsService m_GroupsService; private string m_ConfigName = "Groups"; // Called by Robust shell public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName) : this(config, server, configName, null, null) { } // Called by the sim-bound module public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName, IOfflineIMService im, IUserAccountService users) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; m_log.DebugFormat("[Groups.RobustHGConnector]: Starting with config name {0}", m_ConfigName); string homeURI = Util.GetConfigVarFromSections<string>(config, "HomeURI", new string[] { "Startup", "Hypergrid", m_ConfigName}, string.Empty); if (homeURI == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide the HomeURI [Startup] or in section {0}", m_ConfigName)); IConfig cnf = config.Configs[m_ConfigName]; if (cnf == null) throw new Exception(String.Format("[Groups.RobustHGConnector]: {0} section does not exist", m_ConfigName)); if (im == null) { string imDll = cnf.GetString("OfflineIMService", string.Empty); if (imDll == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide OfflineIMService in section {0}", m_ConfigName)); Object[] args = new Object[] { config }; im = ServerUtils.LoadPlugin<IOfflineIMService>(imDll, args); } if (users == null) { string usersDll = cnf.GetString("UserAccountService", string.Empty); if (usersDll == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide UserAccountService in section {0}", m_ConfigName)); Object[] args = new Object[] { config }; users = ServerUtils.LoadPlugin<IUserAccountService>(usersDll, args); } m_GroupsService = new HGGroupsService(config, im, users, homeURI); server.AddStreamHandler(new HGGroupsServicePostHandler(m_GroupsService)); } } public class HGGroupsServicePostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HGGroupsService m_GroupsService; public HGGroupsServicePostHandler(HGGroupsService service) : base("POST", "/hg-groups") { m_GroupsService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { string body; using(StreamReader sr = new StreamReader(requestData)) body = sr.ReadToEnd(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); m_log.DebugFormat("[Groups.RobustHGConnector]: {0}", method); switch (method) { case "POSTGROUP": return HandleAddGroupProxy(request); case "REMOVEAGENTFROMGROUP": return HandleRemoveAgentFromGroup(request); case "GETGROUP": return HandleGetGroup(request); case "ADDNOTICE": return HandleAddNotice(request); case "VERIFYNOTICE": return HandleVerifyNotice(request); case "GETGROUPMEMBERS": return HandleGetGroupMembers(request); case "GETGROUPROLES": return HandleGetGroupRoles(request); case "GETROLEMEMBERS": return HandleGetRoleMembers(request); } m_log.DebugFormat("[Groups.RobustHGConnector]: unknown method request: {0}", method); } catch (Exception e) { m_log.Error(string.Format("[Groups.RobustHGConnector]: Exception {0} ", e.Message), e); } return FailureResult(); } byte[] HandleAddGroupProxy(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AgentID") || !request.ContainsKey("AccessToken") || !request.ContainsKey("Location")) NullResult(result, "Bad network data"); else { string RequestingAgentID = request["RequestingAgentID"].ToString(); string agentID = request["AgentID"].ToString(); UUID groupID = new UUID(request["GroupID"].ToString()); string accessToken = request["AccessToken"].ToString(); string location = request["Location"].ToString(); string name = string.Empty; if (request.ContainsKey("Name")) name = request["Name"].ToString(); string reason = string.Empty; bool success = m_GroupsService.CreateGroupProxy(RequestingAgentID, agentID, accessToken, groupID, location, name, out reason); result["REASON"] = reason; result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleRemoveAgentFromGroup(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("AccessToken") || !request.ContainsKey("AgentID") || !request.ContainsKey("GroupID")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string agentID = request["AgentID"].ToString(); string token = request["AccessToken"].ToString(); if (!m_GroupsService.RemoveAgentFromGroup(agentID, agentID, groupID, token)) NullResult(result, "Internal error"); else result["RESULT"] = "true"; } //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result)); } byte[] HandleGetGroup(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { string RequestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); UUID groupID = UUID.Zero; string groupName = string.Empty; if (request.ContainsKey("GroupID")) groupID = new UUID(request["GroupID"].ToString()); if (request.ContainsKey("Name")) groupName = request["Name"].ToString(); ExtendedGroupRecord grec = m_GroupsService.GetGroupRecord(RequestingAgentID, groupID, groupName, token); if (grec == null) NullResult(result, "Group not found"); else result["RESULT"] = GroupsDataUtils.GroupRecord(grec); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetGroupMembers(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<ExtendedGroupMembersData> members = m_GroupsService.GetGroupMembers(requestingAgentID, groupID, token); if (members == null || (members != null && members.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (ExtendedGroupMembersData m in members) { dict["m-" + i++] = GroupsDataUtils.GroupMembersData(m); } result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetGroupRoles(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<GroupRolesData> roles = m_GroupsService.GetGroupRoles(requestingAgentID, groupID, token); if (roles == null || (roles != null && roles.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (GroupRolesData r in roles) dict["r-" + i++] = GroupsDataUtils.GroupRolesData(r); result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetRoleMembers(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<ExtendedGroupRoleMembersData> rmembers = m_GroupsService.GetGroupRoleMembers(requestingAgentID, groupID, token); if (rmembers == null || (rmembers != null && rmembers.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (ExtendedGroupRoleMembersData rm in rmembers) dict["rm-" + i++] = GroupsDataUtils.GroupRoleMembersData(rm); result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleAddNotice(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("NoticeID") || !request.ContainsKey("FromName") || !request.ContainsKey("Subject") || !request.ContainsKey("Message") || !request.ContainsKey("HasAttachment")) NullResult(result, "Bad network data"); else { bool hasAtt = bool.Parse(request["HasAttachment"].ToString()); byte attType = 0; string attName = string.Empty; string attOwner = string.Empty; UUID attItem = UUID.Zero; if (request.ContainsKey("AttachmentType")) attType = byte.Parse(request["AttachmentType"].ToString()); if (request.ContainsKey("AttachmentName")) attName = request["AttachmentType"].ToString(); if (request.ContainsKey("AttachmentItemID")) attItem = new UUID(request["AttachmentItemID"].ToString()); if (request.ContainsKey("AttachmentOwnerID")) attOwner = request["AttachmentOwnerID"].ToString(); bool success = m_GroupsService.AddNotice(request["RequestingAgentID"].ToString(), new UUID(request["GroupID"].ToString()), new UUID(request["NoticeID"].ToString()), request["FromName"].ToString(), request["Subject"].ToString(), request["Message"].ToString(), hasAtt, attType, attName, attItem, attOwner); result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleVerifyNotice(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("NoticeID") || !request.ContainsKey("GroupID")) NullResult(result, "Bad network data"); else { UUID noticeID = new UUID(request["NoticeID"].ToString()); UUID groupID = new UUID(request["GroupID"].ToString()); bool success = m_GroupsService.VerifyNotice(noticeID, groupID); //m_log.DebugFormat("[XXX]: VerifyNotice returned {0}", success); result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } // // // // // #region Helpers private void NullResult(Dictionary<string, object> result, string reason) { result["RESULT"] = "NULL"; result["REASON"] = reason; } private byte[] FailureResult() { Dictionary<string, object> result = new Dictionary<string, object>(); NullResult(result, "Unknown method"); string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CustomerEditorValues /// </summary> [DataContract] public partial class CustomerEditorValues : IEquatable<CustomerEditorValues>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CustomerEditorValues" /> class. /// </summary> /// <param name="affiliates">affiliates.</param> /// <param name="cardExpMonths">card_exp_months.</param> /// <param name="cardExpYears">card_exp_years.</param> /// <param name="cardTypes">card_types.</param> /// <param name="countries">countries.</param> /// <param name="qbClasses">qb_classes.</param> /// <param name="salesRepCodes">sales_rep_codes.</param> /// <param name="stateOptionalCountries">state_optional_countries.</param> /// <param name="terms">terms.</param> public CustomerEditorValues(List<CustomerAffiliate> affiliates = default(List<CustomerAffiliate>), List<string> cardExpMonths = default(List<string>), List<string> cardExpYears = default(List<string>), List<string> cardTypes = default(List<string>), List<Country> countries = default(List<Country>), List<string> qbClasses = default(List<string>), List<string> salesRepCodes = default(List<string>), List<Country> stateOptionalCountries = default(List<Country>), List<string> terms = default(List<string>)) { this.Affiliates = affiliates; this.CardExpMonths = cardExpMonths; this.CardExpYears = cardExpYears; this.CardTypes = cardTypes; this.Countries = countries; this.QbClasses = qbClasses; this.SalesRepCodes = salesRepCodes; this.StateOptionalCountries = stateOptionalCountries; this.Terms = terms; } /// <summary> /// affiliates /// </summary> /// <value>affiliates</value> [DataMember(Name="affiliates", EmitDefaultValue=false)] public List<CustomerAffiliate> Affiliates { get; set; } /// <summary> /// card_exp_months /// </summary> /// <value>card_exp_months</value> [DataMember(Name="card_exp_months", EmitDefaultValue=false)] public List<string> CardExpMonths { get; set; } /// <summary> /// card_exp_years /// </summary> /// <value>card_exp_years</value> [DataMember(Name="card_exp_years", EmitDefaultValue=false)] public List<string> CardExpYears { get; set; } /// <summary> /// card_types /// </summary> /// <value>card_types</value> [DataMember(Name="card_types", EmitDefaultValue=false)] public List<string> CardTypes { get; set; } /// <summary> /// countries /// </summary> /// <value>countries</value> [DataMember(Name="countries", EmitDefaultValue=false)] public List<Country> Countries { get; set; } /// <summary> /// qb_classes /// </summary> /// <value>qb_classes</value> [DataMember(Name="qb_classes", EmitDefaultValue=false)] public List<string> QbClasses { get; set; } /// <summary> /// sales_rep_codes /// </summary> /// <value>sales_rep_codes</value> [DataMember(Name="sales_rep_codes", EmitDefaultValue=false)] public List<string> SalesRepCodes { get; set; } /// <summary> /// state_optional_countries /// </summary> /// <value>state_optional_countries</value> [DataMember(Name="state_optional_countries", EmitDefaultValue=false)] public List<Country> StateOptionalCountries { get; set; } /// <summary> /// terms /// </summary> /// <value>terms</value> [DataMember(Name="terms", EmitDefaultValue=false)] public List<string> Terms { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CustomerEditorValues {\n"); sb.Append(" Affiliates: ").Append(Affiliates).Append("\n"); sb.Append(" CardExpMonths: ").Append(CardExpMonths).Append("\n"); sb.Append(" CardExpYears: ").Append(CardExpYears).Append("\n"); sb.Append(" CardTypes: ").Append(CardTypes).Append("\n"); sb.Append(" Countries: ").Append(Countries).Append("\n"); sb.Append(" QbClasses: ").Append(QbClasses).Append("\n"); sb.Append(" SalesRepCodes: ").Append(SalesRepCodes).Append("\n"); sb.Append(" StateOptionalCountries: ").Append(StateOptionalCountries).Append("\n"); sb.Append(" Terms: ").Append(Terms).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CustomerEditorValues); } /// <summary> /// Returns true if CustomerEditorValues instances are equal /// </summary> /// <param name="input">Instance of CustomerEditorValues to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomerEditorValues input) { if (input == null) return false; return ( this.Affiliates == input.Affiliates || this.Affiliates != null && this.Affiliates.SequenceEqual(input.Affiliates) ) && ( this.CardExpMonths == input.CardExpMonths || this.CardExpMonths != null && this.CardExpMonths.SequenceEqual(input.CardExpMonths) ) && ( this.CardExpYears == input.CardExpYears || this.CardExpYears != null && this.CardExpYears.SequenceEqual(input.CardExpYears) ) && ( this.CardTypes == input.CardTypes || this.CardTypes != null && this.CardTypes.SequenceEqual(input.CardTypes) ) && ( this.Countries == input.Countries || this.Countries != null && this.Countries.SequenceEqual(input.Countries) ) && ( this.QbClasses == input.QbClasses || this.QbClasses != null && this.QbClasses.SequenceEqual(input.QbClasses) ) && ( this.SalesRepCodes == input.SalesRepCodes || this.SalesRepCodes != null && this.SalesRepCodes.SequenceEqual(input.SalesRepCodes) ) && ( this.StateOptionalCountries == input.StateOptionalCountries || this.StateOptionalCountries != null && this.StateOptionalCountries.SequenceEqual(input.StateOptionalCountries) ) && ( this.Terms == input.Terms || this.Terms != null && this.Terms.SequenceEqual(input.Terms) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Affiliates != null) hashCode = hashCode * 59 + this.Affiliates.GetHashCode(); if (this.CardExpMonths != null) hashCode = hashCode * 59 + this.CardExpMonths.GetHashCode(); if (this.CardExpYears != null) hashCode = hashCode * 59 + this.CardExpYears.GetHashCode(); if (this.CardTypes != null) hashCode = hashCode * 59 + this.CardTypes.GetHashCode(); if (this.Countries != null) hashCode = hashCode * 59 + this.Countries.GetHashCode(); if (this.QbClasses != null) hashCode = hashCode * 59 + this.QbClasses.GetHashCode(); if (this.SalesRepCodes != null) hashCode = hashCode * 59 + this.SalesRepCodes.GetHashCode(); if (this.StateOptionalCountries != null) hashCode = hashCode * 59 + this.StateOptionalCountries.GetHashCode(); if (this.Terms != null) hashCode = hashCode * 59 + this.Terms.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class ScrollViewUnitTests : BaseTestFixture { [SetUp] public override void Setup() { base.Setup (); Device.PlatformServices = new MockPlatformServices (); } [TearDown] public override void TearDown() { base.TearDown (); Device.PlatformServices = null; } [Test] public void TestConstructor () { ScrollView scrollView = new ScrollView (); Assert.Null (scrollView.Content); View view = new View (); scrollView = new ScrollView {Content = view}; Assert.AreEqual (view, scrollView.Content); } [Test] [TestCase (ScrollOrientation.Horizontal)] [TestCase (ScrollOrientation.Both)] public void GetsCorrectSizeRequestWithWrappingContent (ScrollOrientation orientation) { var scrollView = new ScrollView { IsPlatformEnabled = true, Orientation = orientation, Platform = new UnitPlatform (null, true) }; var hLayout = new StackLayout { IsPlatformEnabled = true, Orientation = StackOrientation.Horizontal, Children = { new Label {Text = "THIS IS A REALLY LONG STRING", IsPlatformEnabled = true}, new Label {Text = "THIS IS A REALLY LONG STRING", IsPlatformEnabled = true}, new Label {Text = "THIS IS A REALLY LONG STRING", IsPlatformEnabled = true}, new Label {Text = "THIS IS A REALLY LONG STRING", IsPlatformEnabled = true}, new Label {Text = "THIS IS A REALLY LONG STRING", IsPlatformEnabled = true}, } }; scrollView.Content = hLayout; var r = scrollView.GetSizeRequest (100, 100); Assert.AreEqual (10, r.Request.Height); } [Test] public void TestContentSizeChangedVertical () { View view = new View {IsPlatformEnabled = true, WidthRequest = 100, HeightRequest = 100}; ScrollView scroll = new ScrollView {Content = view}; scroll.Platform = new UnitPlatform (); scroll.Layout (new Rectangle (0, 0, 50, 50)); Assert.AreEqual (new Size (50, 100), scroll.ContentSize); bool changed = false; scroll.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "ContentSize": changed = true; break; } }; view.HeightRequest = 200; Assert.True (changed); Assert.AreEqual (new Size (50, 200), scroll.ContentSize); } [Test] public void TestContentSizeChangedVerticalBidirectional () { View view = new View { IsPlatformEnabled = true, WidthRequest = 100, HeightRequest = 100 }; ScrollView scroll = new ScrollView { Content = view, Orientation = ScrollOrientation.Both }; scroll.Platform = new UnitPlatform (); scroll.Layout (new Rectangle (0, 0, 50, 50)); Assert.AreEqual (new Size (100, 100), scroll.ContentSize); bool changed = false; scroll.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "ContentSize": changed = true; break; } }; view.HeightRequest = 200; Assert.True (changed); Assert.AreEqual (new Size (100, 200), scroll.ContentSize); } [Test] public void TestContentSizeChangedHorizontal () { View view = new View {IsPlatformEnabled = true, WidthRequest = 100, HeightRequest = 100}; var scroll = new ScrollView { Orientation = ScrollOrientation.Horizontal, Content = view }; scroll.Platform = new UnitPlatform (); scroll.Layout (new Rectangle (0, 0, 50, 50)); Assert.AreEqual (new Size (100, 50), scroll.ContentSize); bool changed = false; scroll.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "ContentSize": changed = true; break; } }; view.WidthRequest = 200; Assert.True (changed); Assert.AreEqual (new Size (200, 50), scroll.ContentSize); } [Test] public void TestContentSizeChangedHorizontalBidirectional () { View view = new View { IsPlatformEnabled = true, WidthRequest = 100, HeightRequest = 100 }; var scroll = new ScrollView { Orientation = ScrollOrientation.Both, Content = view }; scroll.Platform = new UnitPlatform (); scroll.Layout (new Rectangle (0, 0, 50, 50)); Assert.AreEqual (new Size (100, 100), scroll.ContentSize); bool changed = false; scroll.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "ContentSize": changed = true; break; } }; view.WidthRequest = 200; Assert.True (changed); Assert.AreEqual (new Size (200, 100), scroll.ContentSize); } [Test] public void TestContentSizeClamping () { View view = new View {IsPlatformEnabled = true, WidthRequest = 100, HeightRequest = 100}; var scroll = new ScrollView { Orientation = ScrollOrientation.Horizontal, Content = view, Platform = new UnitPlatform () }; scroll.Layout (new Rectangle (0, 0, 50, 50)); bool changed = false; scroll.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "ContentSize": changed = true; break; } }; view.HeightRequest = 200; Assert.False (changed); Assert.AreEqual (new Size (100, 50), scroll.ContentSize); } [Test] public void TestChildChanged () { ScrollView scrollView = new ScrollView (); bool changed = false; scrollView.PropertyChanged += (sender, e) => { switch (e.PropertyName) { case "Content": changed = true; break; } }; View view = new View (); scrollView.Content = view; Assert.True (changed); } [Test] public void TestChildDoubleSet () { var scrollView = new ScrollView (); bool changed = false; scrollView.PropertyChanged += (sender, args) => { if (args.PropertyName == "Content") changed = true; }; var child = new View (); scrollView.Content = child; Assert.True (changed); Assert.AreEqual (child, scrollView.Content); changed = false; scrollView.Content = child; Assert.False (changed); scrollView.Content = null; Assert.True (changed); Assert.Null (scrollView.Content); } [Test] public void TestOrientation () { var scrollView = new ScrollView (); Assert.AreEqual (ScrollOrientation.Vertical, scrollView.Orientation); bool signaled = false; scrollView.PropertyChanged += (sender, args) => { if (args.PropertyName == "Orientation") signaled = true; }; scrollView.Orientation = ScrollOrientation.Horizontal; Assert.AreEqual (ScrollOrientation.Horizontal, scrollView.Orientation); Assert.True (signaled); scrollView.Orientation = ScrollOrientation.Both; Assert.AreEqual (ScrollOrientation.Both, scrollView.Orientation); Assert.True (signaled); } [Test] public void TestOrientationDoubleSet () { var scrollView = new ScrollView (); bool signaled = false; scrollView.PropertyChanged += (sender, args) => { if (args.PropertyName == "Orientation") signaled = true; }; scrollView.Orientation = scrollView.Orientation; Assert.False (signaled); } [Test] public void TestScrollTo() { var scrollView = new ScrollView (); scrollView.Platform = new UnitPlatform (); var item = new View { }; scrollView.Content = new StackLayout { Children = { item } }; bool requested = false; ((IScrollViewController) scrollView).ScrollToRequested += (sender, args) => { requested = true; Assert.AreEqual(args.ScrollY,100); Assert.AreEqual(args.ScrollX,0); Assert.Null (args.Item); Assert.That (args.ShouldAnimate, Is.EqualTo (true)); }; scrollView.ScrollToAsync (0,100, true); Assert.That (requested, Is.True); } [Test] public void TestScrollToNotAnimated() { var scrollView = new ScrollView (); scrollView.Platform = new UnitPlatform (); var item = new View { }; scrollView.Content = new StackLayout { Children = { item } }; bool requested = false; ((IScrollViewController) scrollView).ScrollToRequested += (sender, args) => { requested = true; Assert.AreEqual(args.ScrollY,100); Assert.AreEqual(args.ScrollX,0); Assert.Null (args.Item); Assert.That (args.ShouldAnimate, Is.EqualTo (false)); }; scrollView.ScrollToAsync (0,100, false); Assert.That (requested, Is.True); } [Test] public void TestScrollToElement () { var scrollView = new ScrollView (); scrollView.Platform = new UnitPlatform (); var item = new Label { Text = "Test" }; scrollView.Content = new StackLayout { Children = { item } }; bool requested = false; ((IScrollViewController) scrollView).ScrollToRequested += (sender, args) => { requested = true; Assert.That (args.Element, Is.SameAs (item)); Assert.That (args.Position, Is.EqualTo (ScrollToPosition.Center)); Assert.That (args.ShouldAnimate, Is.EqualTo (true)); }; scrollView.ScrollToAsync (item, ScrollToPosition.Center, true); Assert.That (requested, Is.True); } [Test] public void TestScrollToElementNotAnimated () { var scrollView = new ScrollView (); scrollView.Platform = new UnitPlatform (); var item = new Label { Text = "Test" }; scrollView.Content = new StackLayout { Children = { item } }; bool requested = false; ((IScrollViewController) scrollView).ScrollToRequested += (sender, args) => { requested = true; Assert.That (args.Element, Is.SameAs (item)); Assert.That (args.Position, Is.EqualTo (ScrollToPosition.Center)); Assert.That (args.ShouldAnimate, Is.EqualTo (false)); }; scrollView.ScrollToAsync (item, ScrollToPosition.Center, false); Assert.That (requested, Is.True); } [Test] public void TestScrollToInvalid () { var scrollView = new ScrollView (); scrollView.Platform = new UnitPlatform (); Assert.That (() => scrollView.ScrollToAsync (new VisualElement(), ScrollToPosition.Center, true), Throws.ArgumentException); Assert.That (() => scrollView.ScrollToAsync (null, (ScrollToPosition) 500, true), Throws.ArgumentException); } [Test] public void SetScrollPosition () { var scroll = new ScrollView(); IScrollViewController controller = scroll; controller.SetScrolledPosition (100, 100); Assert.That (scroll.ScrollX, Is.EqualTo (100)); Assert.That (scroll.ScrollY, Is.EqualTo (100)); } [Test] public void TestScrollContentMarginHorizontal() { View view = new View { IsPlatformEnabled = true, Margin = 100, WidthRequest = 100, HeightRequest = 100 }; var scroll = new ScrollView { Content = view, Orientation = ScrollOrientation.Horizontal, Platform = new UnitPlatform() }; scroll.Layout(new Rectangle(0, 0, 100, 100)); Assert.AreEqual(new Size(300, 100), scroll.ContentSize); Assert.AreEqual(100, scroll.Height); Assert.AreEqual(100, scroll.Width); } [Test] public void TestScrollContentMarginVertical() { View view = new View { IsPlatformEnabled = true, Margin = 100, WidthRequest = 100, HeightRequest = 100 }; var scroll = new ScrollView { Content = view, Orientation = ScrollOrientation.Vertical, Platform = new UnitPlatform() }; scroll.Layout(new Rectangle(0, 0, 100, 100)); Assert.AreEqual(new Size(100, 300), scroll.ContentSize); Assert.AreEqual(100, scroll.Height); Assert.AreEqual(100, scroll.Width); } [Test] public void TestScrollContentMarginBiDirectional() { View view = new View { IsPlatformEnabled = true, Margin = 100, WidthRequest = 100, HeightRequest = 100 }; var scroll = new ScrollView { Content = view, Orientation = ScrollOrientation.Both, Platform = new UnitPlatform() }; scroll.Layout(new Rectangle(0, 0, 100, 100)); Assert.AreEqual(new Size(300, 300), scroll.ContentSize); Assert.AreEqual(100, scroll.Height); Assert.AreEqual(100, scroll.Width); } [Test] public void TestBackToBackBiDirectionalScroll() { var scrollView = new ScrollView { Orientation = ScrollOrientation.Both, Platform = new UnitPlatform(), Content = new Grid { WidthRequest = 1000, HeightRequest = 1000 } }; var y100Count = 0; ((IScrollViewController)scrollView).ScrollToRequested += (sender, args) => { if (args.ScrollY == 100) { ++y100Count; } }; scrollView.ScrollToAsync(100, 100, true); Assert.AreEqual(y100Count, 1); scrollView.ScrollToAsync(0, 100, true); Assert.AreEqual(y100Count, 2); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.TypeLoader; using System.Collections.Generic; using System.Threading; using Internal.Metadata.NativeFormat; using Internal.TypeSystem; namespace Internal.Runtime.TypeLoader { internal static class RuntimeTypeHandleEETypeExtensions { public static unsafe EEType* ToEETypePtr(this RuntimeTypeHandle rtth) { return (EEType*)(*(IntPtr*)&rtth); } public static unsafe IntPtr ToIntPtr(this RuntimeTypeHandle rtth) { return *(IntPtr*)&rtth; } public static unsafe bool IsDynamicType(this RuntimeTypeHandle rtth) { return rtth.ToEETypePtr()->IsDynamicType; } public static unsafe int GetNumVtableSlots(this RuntimeTypeHandle rtth) { return rtth.ToEETypePtr()->NumVtableSlots; } public static unsafe IntPtr GetDictionary(this RuntimeTypeHandle rtth) { return EETypeCreator.GetDictionary(rtth.ToEETypePtr()); } public static unsafe void SetDictionary(this RuntimeTypeHandle rtth, int dictionarySlot, IntPtr dictionary) { Debug.Assert(rtth.ToEETypePtr()->IsDynamicType && dictionarySlot < rtth.GetNumVtableSlots()); *(IntPtr*)((byte*)rtth.ToEETypePtr() + sizeof(EEType) + dictionarySlot * IntPtr.Size) = dictionary; } public static unsafe void SetInterface(this RuntimeTypeHandle rtth, int interfaceIndex, RuntimeTypeHandle interfaceType) { rtth.ToEETypePtr()->InterfaceMap[interfaceIndex].InterfaceType = interfaceType.ToEETypePtr(); } public static unsafe void SetGenericDefinition(this RuntimeTypeHandle rtth, RuntimeTypeHandle genericDefinitionHandle) { rtth.ToEETypePtr()->GenericDefinition = genericDefinitionHandle.ToEETypePtr(); } public static unsafe void SetGenericArgument(this RuntimeTypeHandle rtth, int argumentIndex, RuntimeTypeHandle argumentType) { rtth.ToEETypePtr()->GenericArguments[argumentIndex].Value = argumentType.ToEETypePtr(); } public static unsafe void SetNullableType(this RuntimeTypeHandle rtth, RuntimeTypeHandle T_typeHandle) { rtth.ToEETypePtr()->NullableType = T_typeHandle.ToEETypePtr(); } public static unsafe void SetRelatedParameterType(this RuntimeTypeHandle rtth, RuntimeTypeHandle relatedTypeHandle) { rtth.ToEETypePtr()->RelatedParameterType = relatedTypeHandle.ToEETypePtr(); } public static unsafe void SetParameterizedTypeShape(this RuntimeTypeHandle rtth, uint value) { rtth.ToEETypePtr()->ParameterizedTypeShape = value; } public static unsafe void SetBaseType(this RuntimeTypeHandle rtth, RuntimeTypeHandle baseTypeHandle) { rtth.ToEETypePtr()->BaseType = baseTypeHandle.ToEETypePtr(); } public static unsafe void SetComponentSize(this RuntimeTypeHandle rtth, UInt16 componentSize) { rtth.ToEETypePtr()->ComponentSize = componentSize; } } internal class MemoryHelpers { public static int AlignUp(int val, int alignment) { Debug.Assert(val >= 0 && alignment >= 0); // alignment must be a power of 2 for this implementation to work (need modulo otherwise) Debug.Assert(0 == (alignment & (alignment - 1))); int result = (val + (alignment - 1)) & ~(alignment - 1); Debug.Assert(result >= val); // check for overflow return result; } public static unsafe void Memset(IntPtr destination, int length, byte value) { byte* pbDest = (byte*)destination.ToPointer(); while (length > 0) { *pbDest = value; pbDest++; length--; } } public static IntPtr AllocateMemory(int cbBytes) { return PInvokeMarshal.MemAlloc(new IntPtr(cbBytes)); } public static void FreeMemory(IntPtr memoryPtrToFree) { PInvokeMarshal.MemFree(memoryPtrToFree); } } internal unsafe class EETypeCreator { private static IntPtr s_emptyGCDesc; private static void CreateEETypeWorker(EEType* pTemplateEEType, UInt32 hashCodeOfNewType, int arity, bool requireVtableSlotMapping, TypeBuilderState state) { bool successful = false; IntPtr eeTypePtrPlusGCDesc = IntPtr.Zero; IntPtr dynamicDispatchMapPtr = IntPtr.Zero; DynamicModule* dynamicModulePtr = null; IntPtr gcStaticData = IntPtr.Zero; IntPtr gcStaticsIndirection = IntPtr.Zero; try { Debug.Assert((pTemplateEEType != null) || (state.TypeBeingBuilt as MetadataType != null)); // In some situations involving arrays we can find as a template a dynamically generated type. // In that case, the correct template would be the template used to create the dynamic type in the first // place. if (pTemplateEEType != null && pTemplateEEType->IsDynamicType) { pTemplateEEType = pTemplateEEType->DynamicTemplateType; } ModuleInfo moduleInfo = TypeLoaderEnvironment.GetModuleInfoForType(state.TypeBeingBuilt); dynamicModulePtr = moduleInfo.DynamicModulePtr; Debug.Assert(dynamicModulePtr != null); bool requiresDynamicDispatchMap = requireVtableSlotMapping && (pTemplateEEType != null) && pTemplateEEType->HasDispatchMap; uint valueTypeFieldPaddingEncoded = 0; int baseSize = 0; bool isValueType; bool hasFinalizer; bool isNullable; bool isArray; bool isGeneric; ushort componentSize = 0; ushort flags; ushort runtimeInterfacesLength = 0; bool isGenericEETypeDef = false; bool isAbstractClass; bool isByRefLike; #if EETYPE_TYPE_MANAGER IntPtr typeManager = IntPtr.Zero; #endif if (state.RuntimeInterfaces != null) { runtimeInterfacesLength = checked((ushort)state.RuntimeInterfaces.Length); } if (pTemplateEEType != null) { valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue( pTemplateEEType->ValueTypeFieldPadding, (uint)pTemplateEEType->FieldAlignmentRequirement, IntPtr.Size); baseSize = (int)pTemplateEEType->BaseSize; isValueType = pTemplateEEType->IsValueType; hasFinalizer = pTemplateEEType->IsFinalizable; isNullable = pTemplateEEType->IsNullable; componentSize = pTemplateEEType->ComponentSize; flags = pTemplateEEType->Flags; isArray = pTemplateEEType->IsArray; isGeneric = pTemplateEEType->IsGeneric; isAbstractClass = pTemplateEEType->IsAbstract && !pTemplateEEType->IsInterface; isByRefLike = pTemplateEEType->IsByRefLike; #if EETYPE_TYPE_MANAGER typeManager = pTemplateEEType->PointerToTypeManager; #endif Debug.Assert(pTemplateEEType->NumInterfaces == runtimeInterfacesLength); } else if (state.TypeBeingBuilt.IsGenericDefinition) { flags = (ushort)EETypeKind.GenericTypeDefEEType; isValueType = state.TypeBeingBuilt.IsValueType; if (isValueType) flags |= (ushort)EETypeFlags.ValueTypeFlag; if (state.TypeBeingBuilt.IsInterface) flags |= (ushort)EETypeFlags.IsInterfaceFlag; hasFinalizer = false; isArray = false; isNullable = false; isGeneric = false; isGenericEETypeDef = true; isAbstractClass = false; isByRefLike = false; componentSize = checked((ushort)state.TypeBeingBuilt.Instantiation.Length); baseSize = 0; } else { isValueType = state.TypeBeingBuilt.IsValueType; hasFinalizer = state.TypeBeingBuilt.HasFinalizer; isNullable = state.TypeBeingBuilt.GetTypeDefinition().IsNullable; flags = EETypeBuilderHelpers.ComputeFlags(state.TypeBeingBuilt); isArray = false; isGeneric = state.TypeBeingBuilt.HasInstantiation; isAbstractClass = (state.TypeBeingBuilt is MetadataType) && ((MetadataType)state.TypeBeingBuilt).IsAbstract && !state.TypeBeingBuilt.IsInterface; isByRefLike = (state.TypeBeingBuilt is DefType) && ((DefType)state.TypeBeingBuilt).IsByRefLike; if (state.TypeBeingBuilt.HasVariance) { state.GenericVarianceFlags = new int[state.TypeBeingBuilt.Instantiation.Length]; int i = 0; foreach (GenericParameterDesc gpd in state.TypeBeingBuilt.GetTypeDefinition().Instantiation) { state.GenericVarianceFlags[i] = (int)gpd.Variance; i++; } Debug.Assert(i == state.GenericVarianceFlags.Length); } } // TODO! Change to if template is Universal or non-Existent if (state.TypeSize.HasValue) { baseSize = state.TypeSize.Value; int baseSizeBeforeAlignment = baseSize; baseSize = MemoryHelpers.AlignUp(baseSize, IntPtr.Size); if (isValueType) { // Compute the valuetype padding size based on size before adding the object type pointer field to the size uint cbValueTypeFieldPadding = (uint)(baseSize - baseSizeBeforeAlignment); // Add Object type pointer field to base size baseSize += IntPtr.Size; valueTypeFieldPaddingEncoded = (uint)EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(cbValueTypeFieldPadding, (uint)state.FieldAlignment.Value, IntPtr.Size); } // Minimum base size is 3 pointers, and requires us to bump the size of an empty class type if (baseSize <= IntPtr.Size) { // ValueTypes should already have had their size bumped up by the normal type layout process Debug.Assert(!isValueType); baseSize += IntPtr.Size; } // Add sync block skew baseSize += IntPtr.Size; // Minimum basesize is 3 pointers Debug.Assert(baseSize >= (IntPtr.Size * 3)); } // Optional fields encoding int cbOptionalFieldsSize; OptionalFieldsRuntimeBuilder optionalFields; { optionalFields = new OptionalFieldsRuntimeBuilder(pTemplateEEType != null ? pTemplateEEType->OptionalFieldsPtr : null); UInt32 rareFlags = optionalFields.GetFieldValue(EETypeOptionalFieldTag.RareFlags, 0); rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeFlag; // Set the IsDynamicTypeFlag rareFlags &= ~(uint)EETypeRareFlags.NullableTypeViaIATFlag; // Remove the NullableTypeViaIATFlag flag if (state.NumSealedVTableEntries > 0) rareFlags |= (uint)EETypeRareFlags.HasSealedVTableEntriesFlag; if (requiresDynamicDispatchMap) rareFlags |= (uint)EETypeRareFlags.HasDynamicallyAllocatedDispatchMapFlag; if (state.NonGcDataSize != 0) rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithNonGcStatics; if (state.GcDataSize != 0) rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithGcStatics; if (state.ThreadDataSize != 0) rareFlags |= (uint)EETypeRareFlags.IsDynamicTypeWithThreadStatics; #if ARM if (state.FieldAlignment == 8) rareFlags |= (uint)EETypeRareFlags.RequiresAlign8Flag; else rareFlags &= ~(uint)EETypeRareFlags.RequiresAlign8Flag; #endif #if ARM || ARM64 if (state.IsHFA) rareFlags |= (uint)EETypeRareFlags.IsHFAFlag; else rareFlags &= ~(uint)EETypeRareFlags.IsHFAFlag; #endif if (state.HasStaticConstructor) rareFlags |= (uint)EETypeRareFlags.HasCctorFlag; else rareFlags &= ~(uint)EETypeRareFlags.HasCctorFlag; if (isAbstractClass) rareFlags |= (uint)EETypeRareFlags.IsAbstractClassFlag; else rareFlags &= ~(uint)EETypeRareFlags.IsAbstractClassFlag; if (isByRefLike) rareFlags |= (uint)EETypeRareFlags.IsByRefLikeFlag; else rareFlags &= ~(uint)EETypeRareFlags.IsByRefLikeFlag; if (isNullable) { rareFlags |= (uint)EETypeRareFlags.IsNullableFlag; uint nullableValueOffset = state.NullableValueOffset; // The stored offset is never zero (Nullable has a boolean there indicating whether the value is valid). // If the real offset is one, then the field isn't set. Otherwise the offset is encoded - 1 to save space. if (nullableValueOffset == 1) optionalFields.ClearField(EETypeOptionalFieldTag.NullableValueOffset); else optionalFields.SetFieldValue(EETypeOptionalFieldTag.NullableValueOffset, checked(nullableValueOffset - 1)); } else { rareFlags &= ~(uint)EETypeRareFlags.IsNullableFlag; optionalFields.ClearField(EETypeOptionalFieldTag.NullableValueOffset); } rareFlags |= (uint)EETypeRareFlags.HasDynamicModuleFlag; optionalFields.SetFieldValue(EETypeOptionalFieldTag.RareFlags, rareFlags); // Dispatch map is fetched either from template type, or from the dynamically allocated DispatchMap field optionalFields.ClearField(EETypeOptionalFieldTag.DispatchMap); optionalFields.ClearField(EETypeOptionalFieldTag.ValueTypeFieldPadding); if (valueTypeFieldPaddingEncoded != 0) optionalFields.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded); // Compute size of optional fields encoding cbOptionalFieldsSize = optionalFields.Encode(); Debug.Assert(cbOptionalFieldsSize > 0); } // Note: The number of vtable slots on the EEType to create is not necessary equal to the number of // vtable slots on the template type for universal generics (see ComputeVTableLayout) ushort numVtableSlots = state.NumVTableSlots; // Compute the EEType size and allocate it EEType* pEEType; { // In order to get the size of the EEType to allocate we need the following information // 1) The number of VTable slots (from the TypeBuilderState) // 2) The number of Interfaces (from the template) // 3) Whether or not there is a finalizer (from the template) // 4) Optional fields size // 5) Whether or not the type is nullable (from the template) // 6) Whether or not the type has sealed virtuals (from the TypeBuilderState) int cbEEType = (int)EEType.GetSizeofEEType( numVtableSlots, runtimeInterfacesLength, hasFinalizer, true, isNullable, state.NumSealedVTableEntries > 0, isGeneric, state.NonGcDataSize != 0, state.GcDataSize != 0, state.ThreadDataSize != 0); // Dynamic types have an extra pointer-sized field that contains a pointer to their template type cbEEType += IntPtr.Size; // Check if we need another pointer sized field for a dynamic DispatchMap cbEEType += (requiresDynamicDispatchMap ? IntPtr.Size : 0); // Add another pointer sized field for a DynamicModule cbEEType += IntPtr.Size; int cbGCDesc = GetInstanceGCDescSize(state, pTemplateEEType, isValueType, isArray); int cbGCDescAligned = MemoryHelpers.AlignUp(cbGCDesc, IntPtr.Size); // Allocate enough space for the EEType + gcDescSize eeTypePtrPlusGCDesc = MemoryHelpers.AllocateMemory(cbGCDescAligned + cbEEType + cbOptionalFieldsSize); // Get the EEType pointer, and the template EEType pointer pEEType = (EEType*)(eeTypePtrPlusGCDesc + cbGCDescAligned); state.HalfBakedRuntimeTypeHandle = pEEType->ToRuntimeTypeHandle(); // Set basic EEType fields pEEType->ComponentSize = componentSize; pEEType->Flags = flags; pEEType->BaseSize = (uint)baseSize; pEEType->NumVtableSlots = numVtableSlots; pEEType->NumInterfaces = runtimeInterfacesLength; pEEType->HashCode = hashCodeOfNewType; #if EETYPE_TYPE_MANAGER pEEType->PointerToTypeManager = typeManager; #endif // Write the GCDesc bool isSzArray = isArray ? state.ArrayRank < 1 : false; int arrayRank = isArray ? state.ArrayRank.Value : 0; CreateInstanceGCDesc(state, pTemplateEEType, pEEType, baseSize, cbGCDesc, isValueType, isArray, isSzArray, arrayRank); Debug.Assert(pEEType->HasGCPointers == (cbGCDesc != 0)); #if GENERICS_FORCE_USG if (state.NonUniversalTemplateType != null) { Debug.Assert(state.NonUniversalInstanceGCDescSize == cbGCDesc, "Non-universal instance GCDesc size not matching with universal GCDesc size!"); Debug.Assert(cbGCDesc == 0 || pEEType->HasGCPointers); // The TestGCDescsForEquality helper will compare 2 GCDescs for equality, 4 bytes at a time (GCDesc contents treated as integers), and will read the // GCDesc data in *reverse* order for instance GCDescs (subtracts 4 from the pointer values at each iteration). // - For the first GCDesc, we use (pEEType - 4) to point to the first 4-byte integer directly preceeding the EEType // - For the second GCDesc, given that the state.NonUniversalInstanceGCDesc already points to the first byte preceeding the template EEType, we // subtract 3 to point to the first 4-byte integer directly preceeding the template EEType TestGCDescsForEquality(new IntPtr((byte*)pEEType - 4), state.NonUniversalInstanceGCDesc - 3, cbGCDesc, true); } #endif // Copy the encoded optional fields buffer to the newly allocated memory, and update the OptionalFields field on the EEType // It is important to set the optional fields first on the newly created EEType, because all other 'setters' // will assert that the type is dynamic, just to make sure we are not making any changes to statically compiled types pEEType->OptionalFieldsPtr = (byte*)pEEType + cbEEType; optionalFields.WriteToEEType(pEEType, cbOptionalFieldsSize); #if !PROJECTN pEEType->PointerToTypeManager = PermanentAllocatedMemoryBlobs.GetPointerToIntPtr(moduleInfo.Handle.GetIntPtrUNSAFE()); #endif pEEType->DynamicModule = dynamicModulePtr; // Copy VTable entries from template type int numSlotsFilled = 0; IntPtr* pVtable = (IntPtr*)((byte*)pEEType + sizeof(EEType)); if (pTemplateEEType != null) { IntPtr* pTemplateVtable = (IntPtr*)((byte*)pTemplateEEType + sizeof(EEType)); for (int i = 0; i < pTemplateEEType->NumVtableSlots; i++) { int vtableSlotInDynamicType = requireVtableSlotMapping ? state.VTableSlotsMapping.GetVTableSlotInTargetType(i) : i; if (vtableSlotInDynamicType != -1) { Debug.Assert(vtableSlotInDynamicType < numVtableSlots); IntPtr dictionaryPtrValue; if (requireVtableSlotMapping && state.VTableSlotsMapping.IsDictionarySlot(i, out dictionaryPtrValue)) { // This must be the dictionary pointer value of one of the base types of the // current universal generic type being constructed. pVtable[vtableSlotInDynamicType] = dictionaryPtrValue; // Assert that the current template vtable slot is also a NULL value since all // universal generic template types have NULL dictionary slot values in their vtables Debug.Assert(pTemplateVtable[i] == IntPtr.Zero); } else { pVtable[vtableSlotInDynamicType] = pTemplateVtable[i]; } numSlotsFilled++; } } } else if (isGenericEETypeDef) { // If creating a Generic Type Definition Debug.Assert(pEEType->NumVtableSlots == 0); } else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING // Dynamically loaded type // Fill the vtable with vtable resolution thunks in all slots except for // the dictionary slots, which should be filled with dictionary pointers if those // dictionaries are already published. TypeDesc nextTypeToExamineForDictionarySlot = state.TypeBeingBuilt; TypeDesc typeWithDictionary; int nextDictionarySlot = GetMostDerivedDictionarySlot(ref nextTypeToExamineForDictionarySlot, out typeWithDictionary); for (int iSlot = pEEType->NumVtableSlots - 1; iSlot >= 0; iSlot--) { bool isDictionary = iSlot == nextDictionarySlot; if (!isDictionary) { pVtable[iSlot] = LazyVTableResolver.GetThunkForSlot(iSlot); } else { if (typeWithDictionary.RetrieveRuntimeTypeHandleIfPossible()) { pVtable[iSlot] = typeWithDictionary.RuntimeTypeHandle.GetDictionary(); } nextDictionarySlot = GetMostDerivedDictionarySlot(ref nextTypeToExamineForDictionarySlot, out typeWithDictionary); } numSlotsFilled++; } #else Environment.FailFast("Template type loader is null, but metadata based type loader is not in use"); #endif } Debug.Assert(numSlotsFilled == numVtableSlots); // Copy Pointer to finalizer method from the template type if (hasFinalizer) { if (pTemplateEEType != null) { pEEType->FinalizerCode = pTemplateEEType->FinalizerCode; } else { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING pEEType->FinalizerCode = LazyVTableResolver.GetFinalizerThunk(); #else Environment.FailFast("Template type loader is null, but metadata based type loader is not in use"); #endif } } } // Copy the sealed vtable entries if they exist on the template type if (state.NumSealedVTableEntries > 0) { state.HalfBakedSealedVTable = MemoryHelpers.AllocateMemory((int)state.NumSealedVTableEntries * IntPtr.Size); UInt32 cbSealedVirtualSlotsTypeOffset = pEEType->GetFieldOffset(EETypeField.ETF_SealedVirtualSlots); *((IntPtr*)((byte*)pEEType + cbSealedVirtualSlotsTypeOffset)) = state.HalfBakedSealedVTable; for (UInt16 i = 0; i < state.NumSealedVTableEntries; i++) { IntPtr value = pTemplateEEType->GetSealedVirtualSlot(i); pEEType->SetSealedVirtualSlot(value, i); } } // Create a new DispatchMap for the type if (requiresDynamicDispatchMap) { DispatchMap* pTemplateDispatchMap = (DispatchMap*)RuntimeAugments.GetDispatchMapForType(pTemplateEEType->ToRuntimeTypeHandle()); dynamicDispatchMapPtr = MemoryHelpers.AllocateMemory(pTemplateDispatchMap->Size); UInt32 cbDynamicDispatchMapOffset = pEEType->GetFieldOffset(EETypeField.ETF_DynamicDispatchMap); *((IntPtr*)((byte*)pEEType + cbDynamicDispatchMapOffset)) = dynamicDispatchMapPtr; DispatchMap* pDynamicDispatchMap = (DispatchMap*)dynamicDispatchMapPtr; pDynamicDispatchMap->NumEntries = pTemplateDispatchMap->NumEntries; for (int i = 0; i < pTemplateDispatchMap->NumEntries; i++) { DispatchMap.DispatchMapEntry* pTemplateEntry = (*pTemplateDispatchMap)[i]; DispatchMap.DispatchMapEntry* pDynamicEntry = (*pDynamicDispatchMap)[i]; pDynamicEntry->_usInterfaceIndex = pTemplateEntry->_usInterfaceIndex; pDynamicEntry->_usInterfaceMethodSlot = pTemplateEntry->_usInterfaceMethodSlot; if (pTemplateEntry->_usImplMethodSlot < pTemplateEEType->NumVtableSlots) { pDynamicEntry->_usImplMethodSlot = (ushort)state.VTableSlotsMapping.GetVTableSlotInTargetType(pTemplateEntry->_usImplMethodSlot); Debug.Assert(pDynamicEntry->_usImplMethodSlot < numVtableSlots); } else { // This is an entry in the sealed vtable. We need to adjust the slot number based on the number of vtable slots // in the dynamic EEType pDynamicEntry->_usImplMethodSlot = (ushort)(pTemplateEntry->_usImplMethodSlot - pTemplateEEType->NumVtableSlots + numVtableSlots); Debug.Assert(state.NumSealedVTableEntries > 0 && pDynamicEntry->_usImplMethodSlot >= numVtableSlots && (pDynamicEntry->_usImplMethodSlot - numVtableSlots) < state.NumSealedVTableEntries); } } } if (pTemplateEEType != null) { pEEType->DynamicTemplateType = pTemplateEEType; } else { // Use object as the template type for non-template based EETypes. This will // allow correct Module identification for types. if (state.TypeBeingBuilt.HasVariance) { // TODO! We need to have a variant EEType here if the type has variance, as the // CreateGenericInstanceDescForType requires it. However, this is a ridiculous api surface // When we remove GenericInstanceDescs from the product, get rid of this weird special // case pEEType->DynamicTemplateType = typeof(IEnumerable<int>).TypeHandle.ToEETypePtr(); } else { pEEType->DynamicTemplateType = typeof(object).TypeHandle.ToEETypePtr(); } } int nonGCStaticDataOffset = 0; if (!isArray && !isGenericEETypeDef) { nonGCStaticDataOffset = state.HasStaticConstructor ? -TypeBuilder.ClassConstructorOffset : 0; // create GC desc if (state.GcDataSize != 0 && state.GcStaticDesc == IntPtr.Zero) { if (state.GcStaticEEType != IntPtr.Zero) { // CoreRT Abi uses managed heap-allocated GC statics object obj = RuntimeAugments.NewObject(((EEType*)state.GcStaticEEType)->ToRuntimeTypeHandle()); gcStaticData = RuntimeAugments.RhHandleAlloc(obj, GCHandleType.Normal); // CoreRT references statics through an extra level of indirection (a table in the image). gcStaticsIndirection = MemoryHelpers.AllocateMemory(IntPtr.Size); *((IntPtr*)gcStaticsIndirection) = gcStaticData; pEEType->DynamicGcStaticsData = gcStaticsIndirection; } else { int cbStaticGCDesc; state.GcStaticDesc = CreateStaticGCDesc(state.StaticGCLayout, out state.AllocatedStaticGCDesc, out cbStaticGCDesc); #if GENERICS_FORCE_USG TestGCDescsForEquality(state.GcStaticDesc, state.NonUniversalStaticGCDesc, cbStaticGCDesc, false); #endif } } if (state.ThreadDataSize != 0 && state.ThreadStaticDesc == IntPtr.Zero) { int cbThreadStaticGCDesc; state.ThreadStaticDesc = CreateStaticGCDesc(state.ThreadStaticGCLayout, out state.AllocatedThreadStaticGCDesc, out cbThreadStaticGCDesc); #if GENERICS_FORCE_USG TestGCDescsForEquality(state.ThreadStaticDesc, state.NonUniversalThreadStaticGCDesc, cbThreadStaticGCDesc, false); #endif } // If we have a class constructor, our NonGcDataSize MUST be non-zero Debug.Assert(!state.HasStaticConstructor || (state.NonGcDataSize != 0)); } if (isGeneric) { if (!RuntimeAugments.CreateGenericInstanceDescForType(*(RuntimeTypeHandle*)&pEEType, arity, state.NonGcDataSize, nonGCStaticDataOffset, state.GcDataSize, (int)state.ThreadStaticOffset, state.GcStaticDesc, state.ThreadStaticDesc, state.GenericVarianceFlags)) { throw new OutOfMemoryException(); } } else { Debug.Assert(arity == 0 || isGenericEETypeDef); // We don't need to report the non-gc and gc static data regions and allocate them for non-generics, // as we currently place these fields directly into the image if (!isGenericEETypeDef && state.ThreadDataSize != 0) { // Types with thread static fields ALWAYS get a GID. The GID is used to perform GC // and lifetime management of the thread static data. However, these GIDs are only used for that // so the specified GcDataSize, etc are 0 if (!RuntimeAugments.CreateGenericInstanceDescForType(*(RuntimeTypeHandle*)&pEEType, 0, 0, 0, 0, (int)state.ThreadStaticOffset, IntPtr.Zero, state.ThreadStaticDesc, null)) { throw new OutOfMemoryException(); } } } if (state.Dictionary != null) state.HalfBakedDictionary = state.Dictionary.Allocate(); Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull()); Debug.Assert((state.NumSealedVTableEntries == 0 && state.HalfBakedSealedVTable == IntPtr.Zero) || (state.NumSealedVTableEntries > 0 && state.HalfBakedSealedVTable != IntPtr.Zero)); Debug.Assert((state.Dictionary == null && state.HalfBakedDictionary == IntPtr.Zero) || (state.Dictionary != null && state.HalfBakedDictionary != IntPtr.Zero)); successful = true; } finally { if (!successful) { if (eeTypePtrPlusGCDesc != IntPtr.Zero) MemoryHelpers.FreeMemory(eeTypePtrPlusGCDesc); if (dynamicDispatchMapPtr != IntPtr.Zero) MemoryHelpers.FreeMemory(dynamicDispatchMapPtr); if (state.HalfBakedSealedVTable != IntPtr.Zero) MemoryHelpers.FreeMemory(state.HalfBakedSealedVTable); if (state.HalfBakedDictionary != IntPtr.Zero) MemoryHelpers.FreeMemory(state.HalfBakedDictionary); if (state.AllocatedStaticGCDesc) MemoryHelpers.FreeMemory(state.GcStaticDesc); if (state.AllocatedThreadStaticGCDesc) MemoryHelpers.FreeMemory(state.ThreadStaticDesc); if (gcStaticData != IntPtr.Zero) RuntimeAugments.RhHandleFree(gcStaticData); if (gcStaticsIndirection != IntPtr.Zero) MemoryHelpers.FreeMemory(gcStaticsIndirection); } } } private static IntPtr CreateStaticGCDesc(LowLevelList<bool> gcBitfield, out bool allocated, out int cbGCDesc) { if (gcBitfield != null) { int series = CreateGCDesc(gcBitfield, 0, false, true, null); if (series > 0) { cbGCDesc = sizeof(int) + series * sizeof(int) * 2; IntPtr result = MemoryHelpers.AllocateMemory(cbGCDesc); CreateGCDesc(gcBitfield, 0, false, true, (void**)result.ToPointer()); allocated = true; return result; } } allocated = false; if (s_emptyGCDesc == IntPtr.Zero) { IntPtr ptr = MemoryHelpers.AllocateMemory(8); long* gcdesc = (long*)ptr.ToPointer(); *gcdesc = 0; if (Interlocked.CompareExchange(ref s_emptyGCDesc, ptr, IntPtr.Zero) != IntPtr.Zero) MemoryHelpers.FreeMemory(ptr); } cbGCDesc = IntPtr.Size; return s_emptyGCDesc; } private static void CreateInstanceGCDesc(TypeBuilderState state, EEType* pTemplateEEType, EEType* pEEType, int baseSize, int cbGCDesc, bool isValueType, bool isArray, bool isSzArray, int arrayRank) { var gcBitfield = state.InstanceGCLayout; if (isArray) { if (cbGCDesc != 0) { pEEType->HasGCPointers = true; if (state.IsArrayOfReferenceTypes) { IntPtr* gcDescStart = (IntPtr*)((byte*)pEEType - cbGCDesc); gcDescStart[0] = new IntPtr(-baseSize); gcDescStart[1] = new IntPtr(baseSize - sizeof(IntPtr)); gcDescStart[2] = new IntPtr(1); } else { CreateArrayGCDesc(gcBitfield, arrayRank, isSzArray, ((void**)pEEType) - 1); } } else { pEEType->HasGCPointers = false; } } else if (gcBitfield != null) { if (cbGCDesc != 0) { pEEType->HasGCPointers = true; CreateGCDesc(gcBitfield, baseSize, isValueType, false, ((void**)pEEType) - 1); } else { pEEType->HasGCPointers = false; } } else if (pTemplateEEType != null) { Buffer.MemoryCopy((byte*)pTemplateEEType - cbGCDesc, (byte*)pEEType - cbGCDesc, cbGCDesc, cbGCDesc); pEEType->HasGCPointers = pTemplateEEType->HasGCPointers; } else { pEEType->HasGCPointers = false; } } private static unsafe int GetInstanceGCDescSize(TypeBuilderState state, EEType* pTemplateEEType, bool isValueType, bool isArray) { var gcBitfield = state.InstanceGCLayout; if (isArray) { if (state.IsArrayOfReferenceTypes) { // Reference type arrays have a GC desc the size of 3 pointers return 3 * sizeof(IntPtr); } else { int series = 0; if (gcBitfield != null) series = CreateArrayGCDesc(gcBitfield, 1, true, null); return series > 0 ? (series + 2) * IntPtr.Size : 0; } } else if (gcBitfield != null) { int series = CreateGCDesc(gcBitfield, 0, isValueType, false, null); return series > 0 ? (series * 2 + 1) * IntPtr.Size : 0; } else if (pTemplateEEType != null) { return RuntimeAugments.GetGCDescSize(pTemplateEEType->ToRuntimeTypeHandle()); } else { return 0; } } private static unsafe int CreateArrayGCDesc(LowLevelList<bool> bitfield, int rank, bool isSzArray, void* gcdesc) { if (bitfield == null) return 0; void** baseOffsetPtr = (void**)gcdesc - 1; #if WIN64 int* ptr = (int*)baseOffsetPtr - 1; #else short* ptr = (short*)baseOffsetPtr - 1; #endif int baseOffset = 2; if (!isSzArray) { baseOffset += 2 * rank / (sizeof(IntPtr) / sizeof(int)); } int numSeries = 0; int i = 0; bool first = true; int last = 0; short numPtrs = 0; while (i < bitfield.Count) { if (bitfield[i]) { if (first) { baseOffset += i; first = false; } else if (gcdesc != null) { *ptr-- = (short)((i - last) * IntPtr.Size); *ptr-- = numPtrs; } numSeries++; numPtrs = 0; while ((i < bitfield.Count) && (bitfield[i])) { numPtrs++; i++; } last = i; } else { i++; } } if (gcdesc != null) { if (numSeries > 0) { *ptr-- = (short)((bitfield.Count - last + baseOffset - 2) * IntPtr.Size); *ptr-- = numPtrs; *(void**)gcdesc = (void*)-numSeries; *baseOffsetPtr = (void*)(baseOffset * IntPtr.Size); } } return numSeries; } private static unsafe int CreateGCDesc(LowLevelList<bool> bitfield, int size, bool isValueType, bool isStatic, void* gcdesc) { int offs = 0; // if this type is a class we have to account for the gcdesc. if (isValueType) offs = IntPtr.Size; if (bitfield == null) return 0; void** ptr = (void**)gcdesc - 1; int* staticPtr = isStatic ? ((int*)gcdesc + 1) : null; int numSeries = 0; int i = 0; while (i < bitfield.Count) { if (bitfield[i]) { numSeries++; int seriesOffset = i * IntPtr.Size + offs; int seriesSize = 0; while ((i < bitfield.Count) && (bitfield[i])) { seriesSize += IntPtr.Size; i++; } if (gcdesc != null) { if (staticPtr != null) { *staticPtr++ = seriesSize; *staticPtr++ = seriesOffset; } else { seriesSize = seriesSize - size; *ptr-- = (void*)seriesOffset; *ptr-- = (void*)seriesSize; } } } else { i++; } } if (gcdesc != null) { if (staticPtr != null) *(int*)gcdesc = numSeries; else *(void**)gcdesc = (void*)numSeries; } return numSeries; } [Conditional("GENERICS_FORCE_USG")] unsafe private static void TestGCDescsForEquality(IntPtr dynamicGCDesc, IntPtr templateGCDesc, int cbGCDesc, bool isInstanceGCDesc) { if (templateGCDesc == IntPtr.Zero) return; Debug.Assert(dynamicGCDesc != IntPtr.Zero); Debug.Assert(cbGCDesc == MemoryHelpers.AlignUp(cbGCDesc, 4)); uint* pMem1 = (uint*)dynamicGCDesc.ToPointer(); uint* pMem2 = (uint*)templateGCDesc.ToPointer(); bool foundDifferences = false; for (int i = 0; i < cbGCDesc; i += 4) { if (*pMem1 != *pMem2) { // Log all the differences before the assert Debug.WriteLine("ERROR: GCDesc comparison failed at byte #" + i.LowLevelToString() + " while comparing " + dynamicGCDesc.LowLevelToString() + " with " + templateGCDesc.LowLevelToString() + ": [" + (*pMem1).LowLevelToString() + "]/[" + (*pMem2).LowLevelToString() + "]"); foundDifferences = true; } if (isInstanceGCDesc) { pMem1--; pMem2--; } else { pMem1++; pMem2++; } } Debug.Assert(!foundDifferences); } public static RuntimeTypeHandle CreatePointerEEType(UInt32 hashCodeOfNewType, RuntimeTypeHandle pointeeTypeHandle, TypeDesc pointerType) { TypeBuilderState state = new TypeBuilderState(pointerType); CreateEETypeWorker(typeof(void*).TypeHandle.ToEETypePtr(), hashCodeOfNewType, 0, false, state); Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull()); TypeLoaderLogger.WriteLine("Allocated new POINTER type " + pointerType.ToString() + " with hashcode value = 0x" + hashCodeOfNewType.LowLevelToString() + " with eetype = " + state.HalfBakedRuntimeTypeHandle.ToIntPtr().LowLevelToString()); state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->RelatedParameterType = pointeeTypeHandle.ToEETypePtr(); return state.HalfBakedRuntimeTypeHandle; } public static RuntimeTypeHandle CreateByRefEEType(UInt32 hashCodeOfNewType, RuntimeTypeHandle pointeeTypeHandle, TypeDesc byRefType) { TypeBuilderState state = new TypeBuilderState(byRefType); // ByRef and pointer types look similar enough that we can use void* as a template. // Ideally this should be typeof(void&) but C# doesn't support that syntax. We adjust for this below. CreateEETypeWorker(typeof(void*).TypeHandle.ToEETypePtr(), hashCodeOfNewType, 0, false, state); Debug.Assert(!state.HalfBakedRuntimeTypeHandle.IsNull()); TypeLoaderLogger.WriteLine("Allocated new BYREF type " + byRefType.ToString() + " with hashcode value = 0x" + hashCodeOfNewType.LowLevelToString() + " with eetype = " + state.HalfBakedRuntimeTypeHandle.ToIntPtr().LowLevelToString()); state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->RelatedParameterType = pointeeTypeHandle.ToEETypePtr(); // We used a pointer as a template. We need to make this a byref. Debug.Assert(state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape == ParameterizedTypeShapeConstants.Pointer); state.HalfBakedRuntimeTypeHandle.ToEETypePtr()->ParameterizedTypeShape = ParameterizedTypeShapeConstants.ByRef; return state.HalfBakedRuntimeTypeHandle; } public static RuntimeTypeHandle CreateEEType(TypeDesc type, TypeBuilderState state) { Debug.Assert(type != null && state != null); EEType* pTemplateEEType = null; bool requireVtableSlotMapping = false; if (type is PointerType || type is ByRefType) { Debug.Assert(0 == state.NonGcDataSize); Debug.Assert(false == state.HasStaticConstructor); Debug.Assert(0 == state.GcDataSize); Debug.Assert(0 == state.ThreadStaticOffset); Debug.Assert(0 == state.NumSealedVTableEntries); Debug.Assert(IntPtr.Zero == state.GcStaticDesc); Debug.Assert(IntPtr.Zero == state.ThreadStaticDesc); // Pointers and ByRefs only differ by the ParameterizedTypeShape value. RuntimeTypeHandle templateTypeHandle = typeof(void*).TypeHandle; pTemplateEEType = templateTypeHandle.ToEETypePtr(); } else if ((type is MetadataType) && (state.TemplateType == null || !state.TemplateType.RetrieveRuntimeTypeHandleIfPossible())) { requireVtableSlotMapping = true; pTemplateEEType = null; } else if (type.IsMdArray || (type.IsSzArray && ((ArrayType)type).ElementType.IsPointer)) { // Multidimensional arrays and szarrays of pointers don't implement generic interfaces and // we don't need to do much for them in terms of type building. We can pretty much just take // the EEType for any of those, massage the bits that matter (GCDesc, element type, // component size,...) to be of the right shape and we're done. pTemplateEEType = typeof(object[,]).TypeHandle.ToEETypePtr(); requireVtableSlotMapping = false; } else { Debug.Assert(state.TemplateType != null && !state.TemplateType.RuntimeTypeHandle.IsNull()); requireVtableSlotMapping = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.Universal); RuntimeTypeHandle templateTypeHandle = state.TemplateType.RuntimeTypeHandle; pTemplateEEType = templateTypeHandle.ToEETypePtr(); } DefType typeAsDefType = type as DefType; // Use a checked typecast to 'ushort' for the arity to ensure its value never exceeds 65535 and cause integer // overflows later when computing size of memory blocks to allocate for the type and its GenericInstanceDescriptor structures int arity = checked((ushort)((typeAsDefType != null && typeAsDefType.HasInstantiation ? typeAsDefType.Instantiation.Length : 0))); CreateEETypeWorker(pTemplateEEType, (uint)type.GetHashCode(), arity, requireVtableSlotMapping, state); return state.HalfBakedRuntimeTypeHandle; } public static int GetDictionaryOffsetInEEtype(EEType* pEEType) { // Dictionary slot is the first vtable slot EEType* pBaseType = pEEType->BaseType; int dictionarySlot = (pBaseType == null ? 0 : pBaseType->NumVtableSlots); return sizeof(EEType) + dictionarySlot * IntPtr.Size; } public static IntPtr GetDictionaryAtOffset(EEType* pEEType, int offset) { return *(IntPtr*)((byte*)pEEType + offset); } public static IntPtr GetDictionary(EEType* pEEType) { return GetDictionaryAtOffset(pEEType, GetDictionaryOffsetInEEtype(pEEType)); } public static int GetDictionarySlotInVTable(TypeDesc type) { if (!type.CanShareNormalGenericCode()) return -1; // Dictionary slot is the first slot in the vtable after the base type's vtable entries return type.BaseType != null ? type.BaseType.GetOrCreateTypeBuilderState().NumVTableSlots : 0; } private static int GetMostDerivedDictionarySlot(ref TypeDesc nextTypeToExamineForDictionarySlot, out TypeDesc typeWithDictionary) { while (nextTypeToExamineForDictionarySlot != null) { if (nextTypeToExamineForDictionarySlot.GetOrCreateTypeBuilderState().HasDictionarySlotInVTable) { typeWithDictionary = nextTypeToExamineForDictionarySlot; nextTypeToExamineForDictionarySlot = nextTypeToExamineForDictionarySlot.BaseType; return GetDictionarySlotInVTable(typeWithDictionary); } nextTypeToExamineForDictionarySlot = nextTypeToExamineForDictionarySlot.BaseType; } typeWithDictionary = null; return -1; } public static EEType* GetBaseEETypeForDictionaryPtr(EEType* pEEType, IntPtr dictionaryPtr) { // Look for the exact base type that owns the dictionary IntPtr curDictPtr = GetDictionary(pEEType); EEType* pBaseEEType = pEEType; while (curDictPtr != dictionaryPtr) { pBaseEEType = pBaseEEType->BaseType; Debug.Assert(pBaseEEType != null); // Since in multifile scenario, the base type's dictionary may end up having // a copy in each module, therefore the lookup of the right base type should be // based on the dictionary pointer in the current EEtype, instead of the base EEtype. curDictPtr = GetDictionaryAtOffset(pEEType, EETypeCreator.GetDictionaryOffsetInEEtype(pBaseEEType)); } return pBaseEEType; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>CampaignAsset</c> resource.</summary> public sealed partial class CampaignAssetName : gax::IResourceName, sys::IEquatable<CampaignAssetName> { /// <summary>The possible contents of <see cref="CampaignAssetName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </summary> CustomerCampaignAssetFieldType = 1, } private static gax::PathTemplate s_customerCampaignAssetFieldType = new gax::PathTemplate("customers/{customer_id}/campaignAssets/{campaign_id_asset_id_field_type}"); /// <summary>Creates a <see cref="CampaignAssetName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="CampaignAssetName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CampaignAssetName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CampaignAssetName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CampaignAssetName"/> with the pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CampaignAssetName"/> constructed from the provided ids.</returns> public static CampaignAssetName FromCustomerCampaignAssetFieldType(string customerId, string campaignId, string assetId, string fieldTypeId) => new CampaignAssetName(ResourceNameType.CustomerCampaignAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignAssetName"/> with pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignAssetName"/> with pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </returns> public static string Format(string customerId, string campaignId, string assetId, string fieldTypeId) => FormatCustomerCampaignAssetFieldType(customerId, campaignId, assetId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignAssetName"/> with pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignAssetName"/> with pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c>. /// </returns> public static string FormatCustomerCampaignAssetFieldType(string customerId, string campaignId, string assetId, string fieldTypeId) => s_customerCampaignAssetFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignAssetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="campaignAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CampaignAssetName"/> if successful.</returns> public static CampaignAssetName Parse(string campaignAssetName) => Parse(campaignAssetName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignAssetName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="CampaignAssetName"/> if successful.</returns> public static CampaignAssetName Parse(string campaignAssetName, bool allowUnparsed) => TryParse(campaignAssetName, allowUnparsed, out CampaignAssetName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignAssetName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="campaignAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignAssetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string campaignAssetName, out CampaignAssetName result) => TryParse(campaignAssetName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignAssetName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignAssetName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignAssetName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string campaignAssetName, bool allowUnparsed, out CampaignAssetName result) { gax::GaxPreconditions.CheckNotNull(campaignAssetName, nameof(campaignAssetName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignAssetFieldType.TryParseName(campaignAssetName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignAssetFieldType(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(campaignAssetName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CampaignAssetName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string campaignId = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; AssetId = assetId; CampaignId = campaignId; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="CampaignAssetName"/> class from the component parts of pattern /// <c>customers/{customer_id}/campaignAssets/{campaign_id}~{asset_id}~{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public CampaignAssetName(string customerId, string campaignId, string assetId, string fieldTypeId) : this(ResourceNameType.CustomerCampaignAssetFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Asset</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AssetId { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaignAssetFieldType: return s_customerCampaignAssetFieldType.Expand(CustomerId, $"{CampaignId}~{AssetId}~{FieldTypeId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as CampaignAssetName); /// <inheritdoc/> public bool Equals(CampaignAssetName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CampaignAssetName a, CampaignAssetName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CampaignAssetName a, CampaignAssetName b) => !(a == b); } public partial class CampaignAsset { /// <summary> /// <see cref="CampaignAssetName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CampaignAssetName ResourceNameAsCampaignAssetName { get => string.IsNullOrEmpty(ResourceName) ? null : CampaignAssetName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } /// <summary><see cref="AssetName"/>-typed view over the <see cref="Asset"/> resource name property.</summary> internal AssetName AssetAsAssetName { get => string.IsNullOrEmpty(Asset) ? null : AssetName.Parse(Asset, allowUnparsed: true); set => Asset = value?.ToString() ?? ""; } } }
using System; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using bv.common; using bv.common.Configuration; using bv.common.Core; using bv.common.win; using DevExpress.XtraEditors; using DevExpress.XtraPrinting; using eidss.model.Resources; using EIDSS.RAM.Presenters.Base; using EIDSS.RAM_DB.Common.CommandProcessing.Commands; using EIDSS.RAM_DB.Common.CommandProcessing.Commands.Layout; using EIDSS.RAM_DB.Common.EventHandlers; using EIDSS.RAM_DB.DBService; using EIDSS.RAM_DB.DBService.Models; using EIDSS.RAM_DB.Views; using Convert = BLToolkit.Common.Convert; namespace EIDSS.RAM.Presenters { public class MapPresenter : RelatedObjectPresenter { private readonly IMapView m_MapView; private Image m_PrintImage; private readonly BaseRamDbService m_MapFormService; private readonly LayoutMediator m_LayoutMediator; public MapPresenter(SharedPresenter sharedPresenter, IMapView view) : base(sharedPresenter, view) { m_MapFormService = new BaseRamDbService(); m_LayoutMediator = new LayoutMediator(this); m_MapView = view; m_MapView.DBService = MapFormService; m_MapView.InitAdmUnit += View_InitAdmUnit; m_MapView.RefreshMap += View_RefreshMap; m_SharedPresenter.SharedModel.PropertyChanged += SharedModel_PropertyChanged; } private void SharedModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { var property = (SharedProperty) (Enum.Parse(typeof (SharedProperty), e.PropertyName)); switch (property) { case SharedProperty.FilterText: m_MapView.FilterText = m_SharedPresenter.SharedModel.FilterText; break; case SharedProperty.MapName: m_MapView.MapName = m_SharedPresenter.SharedModel.MapName; break; } } public BaseRamDbService MapFormService { get { return m_MapFormService; } } public bool MapHasChanges { get { return m_SharedPresenter.SharedModel.MapHasChanges; } set { m_SharedPresenter.SharedModel.MapHasChanges = value; } } private void View_InitAdmUnit(object sender, ComboBoxEventArgs e) { m_SharedPresenter.BindAdmUnitComboBox(e); } private void View_RefreshMap(object sender, EventArgs e) { if (Utils.IsEmpty(m_MapView.AdmUnitValue)) { throw new RamException("Map field name is empty"); } string fieldAlias = Utils.Str(m_MapView.AdmUnitValue); bool isSingle; DataTable dataSource = m_SharedPresenter.SharedModel.GetMapDataTable(fieldAlias, out isSingle); var mapSettings = new EventLayerSettings(); if (!m_LayoutMediator.LayoutRow.IsintGisLayerPositionNull()) { mapSettings.Position = m_LayoutMediator.LayoutRow.intGisLayerPosition; } if (!m_LayoutMediator.LayoutRow.IsstrGisLayerSettingsNull()) { mapSettings.LayerSettings = Convert.ToXmlDocument(m_LayoutMediator.LayoutRow.strGisLayerSettings); } if (!m_LayoutMediator.LayoutRow.IsstrGisMapSettingsNull()) { mapSettings.MapSettings = Convert.ToXmlDocument(m_LayoutMediator.LayoutRow.strGisMapSettings); } m_MapView.UpdateMap(dataSource, mapSettings, isSingle); } #region Binding public void BindMapName(TextEdit edit) { BindingHelper.BindEditor(edit, m_LayoutMediator.LayoutDataSet, m_LayoutMediator.LayoutTable.TableName, m_LayoutMediator.LayoutTable.strMapNameColumn.ColumnName); } #endregion #region Command handlers public override void Process(Command cmd) { try { ProcessMapSettings(cmd); ProcessPrintExport(cmd); } catch (Exception ex) { if (BaseSettings.ThrowExceptionOnError) { throw; } ErrorForm.ShowError(ex); } } private void ProcessMapSettings(Command cmd) { if (!((cmd is RefreshCommand) && ((RefreshCommand) cmd).RefreshType == RefreshType.MapSettings)) { return; } cmd.State = CommandState.Pending; EventLayerSettings mapSettings = m_MapView.MapSettings; if (mapSettings != null) { m_LayoutMediator.LayoutRow.intGisLayerPosition = mapSettings.Position; m_LayoutMediator.LayoutRow.strGisLayerSettings = Utils.IsEmpty(mapSettings.LayerSettings) ? string.Empty : Convert.ToString(mapSettings.LayerSettings); m_LayoutMediator.LayoutRow.strGisMapSettings = Utils.IsEmpty(mapSettings.MapSettings) ? string.Empty : Convert.ToString(mapSettings.MapSettings); } cmd.State = CommandState.Processed; } public void ProcessPrintExport(Command cmd) { if ((!(cmd is PrintCommand)) && (!(cmd is ExportCommand))) { return; } if (cmd is PrintCommand && ((PrintCommand) cmd).PrintType != PrintType.Map) { return; } if (cmd is ExportCommand && (((ExportCommand) cmd).ExportType != ExportType.Image || ((ExportCommand) cmd).ExportObject != ExportObject.Map)) { return; } Trace.WriteLine(Trace.Kind.Info, "MapForm.Process(): executing map print command"); cmd.State = CommandState.Pending; if (m_MapView.AdmUnitValue == null) { m_MapView.RaiseInitAdmUnitComboBox(); } View_RefreshMap(this, EventArgs.Empty); m_PrintImage = GetPrintBitmap(); if (cmd is PrintCommand) { ShowPreview(m_MapView.PrintingSystem, CreateDetailArea); } if (cmd is ExportCommand) { ExportTo("jpg", EidssMessages.Get("msgFilterJpg", "Jpeg images|*.jpg"), fileName => m_PrintImage.Save(fileName, ImageFormat.Jpeg)); } cmd.State = CommandState.Processed; } private Bitmap GetPrintBitmap() { const float mmWidth = 297; const float mmHeight = 210; const int dpi = 300; const float inch = 25.4f; const int pixelWidth = (int) ((mmWidth * dpi) / inch); const int pixelHeight = (int) ((mmHeight * dpi) / inch); var fontBitmap = new Bitmap(pixelWidth, 1); Graphics fontGraphics = Graphics.FromImage(fontBitmap); var font = new Font(BaseSettings.SystemFontName, 40); SizeF headerSize = fontGraphics.MeasureString(m_MapView.MapName, font, pixelWidth); SizeF filterSize = fontGraphics.MeasureString(m_MapView.FilterText, font, pixelWidth); var printBitmap = new Bitmap(pixelWidth, pixelHeight); Graphics printGraphics = Graphics.FromImage(printBitmap); // printBitmap.HorizontalResolution = printGraphics. printGraphics.FillRectangle(new SolidBrush(Color.White), 0, 0, printBitmap.Width, printBitmap.Height); var strFormat = new StringFormat {Alignment = StringAlignment.Center}; var mmTextHeight = (int) ((inch * (filterSize.Height + headerSize.Height)) / dpi); if (mmTextHeight < mmHeight) { printGraphics.DrawString(m_MapView.MapName, font, Brushes.Black, new RectangleF(0, 0, pixelWidth, pixelHeight), strFormat); printGraphics.DrawString(m_MapView.FilterText, font, Brushes.Black, new RectangleF(0, headerSize.Height, pixelWidth, pixelHeight), strFormat); Bitmap mapImage = m_MapView.GetMapImage(mmWidth, mmHeight - mmTextHeight, dpi); mapImage.SetResolution(printBitmap.HorizontalResolution, printBitmap.VerticalResolution); printGraphics.DrawImage(mapImage, 0, filterSize.Height + headerSize.Height); } else { string error = EidssMessages.Get("msgRamMapHeaderTooBig", @"Header and filter are too big. Please change them and try again."); printGraphics.DrawString(error, font, Brushes.Black, new RectangleF(0, 0, pixelWidth, pixelHeight), strFormat); } return printBitmap; } private void CreateDetailArea(object sender, CreateAreaEventArgs e) { var imageBrick = new ImageBrick { Rect = new RectangleF(0, 0, m_PrintImage.Width, m_PrintImage.Height), Image = m_PrintImage }; e.Graph.DrawBrick(imageBrick); } #endregion } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Text; using System.Threading; using System.Web.Services.Protocols; using System.Windows.Forms; using MLifter.BusinessLayer; using MLifter.Components.Properties; using MLifter.Generics; using MRG.Controls.UI; using System.Runtime.Serialization.Formatters.Binary; using System.Xml; using System.ServiceModel.Syndication; using System.Xml.Serialization; using System.Net; using System.Collections.ObjectModel; using System.Collections.Specialized; namespace MLifter.Components { public partial class FolderTreeView : TreeView { /// <summary> /// Occurs when content loading throws an exception. /// </summary> /// <remarks>Documented by Dev02, 2009-05-14</remarks> public event MLifter.BusinessLayer.FolderIndexEntry.ContentLoadExceptionEventHandler ContentLoadException; /// <summary> /// Gets or sets the folders. /// </summary> /// <value>The folders.</value> /// <remarks>Documented by Dev05, 2009-03-12</remarks> public ObservableList<FolderIndexEntry> Folders { get; private set; } /// <summary> /// Gets the connections. /// </summary> /// <value>The connections.</value> /// <remarks>Documented by Dev05, 2009-03-12</remarks> public ObservableList<IConnectionString> Connections { get; private set; } /// <summary> /// Gets the feeds. /// </summary> /// <remarks>CFI, 2012-03-03</remarks> public ObservableCollection<ModuleFeedConnection> Feeds { get; private set; } /// <summary> /// Gets the collection of tree nodes that are assigned to the tree view control. /// </summary> /// <value></value> /// <returns> /// A <see cref="T:System.Windows.Forms.TreeNodeCollection"/> that represents the tree nodes assigned to the tree view control. /// </returns> /// <remarks>Documented by Dev05, 2009-03-12</remarks> public new List<FolderTreeNode> Nodes { get; private set; } /// <summary> /// Gets or sets the tree node that is currently selected in the tree view control. /// </summary> /// <value></value> /// <returns> /// The <see cref="T:System.Windows.Forms.TreeNode"/> that is currently selected in the tree view control. /// </returns> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/> /// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// </PermissionSet> /// <remarks>Documented by Dev05, 2009-03-12</remarks> [Browsable(false)] public FolderIndexEntry SelectedFolder { get { try { if (SelectedNode is FolderTreeNode) return (SelectedNode as FolderTreeNode).Folder; else return null; } catch { return null; } } set { try { SelectedNode = Nodes.Find(n => n.Folder == value); } catch { } } } /// <summary> /// Gets or sets the tree node that is currently selected in the tree view control. /// </summary> /// <value></value> /// <returns> /// The <see cref="T:System.Windows.Forms.TreeNode"/> that is currently selected in the tree view control. /// </returns> /// <PermissionSet> /// <IPermission class="System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// <IPermission class="System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Flags="UnmanagedCode, ControlEvidence"/> /// <IPermission class="System.Diagnostics.PerformanceCounterPermission, System, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" version="1" Unrestricted="true"/> /// </PermissionSet> /// <remarks>Documented by Dev05, 2009-03-12</remarks> public new TreeNode SelectedNode { get { return base.SelectedNode; } set { base.SelectedNode = value; } } /// <summary> /// Initializes a new instance of the <see cref="FolderTreeView"/> class. /// </summary> /// <remarks>Documented by Dev05, 2009-03-12</remarks> public FolderTreeView() : base() { this.DoubleBuffered = true; InitializeComponent(); updateTimer.Interval = 1000; updateTimer.Tick += new EventHandler(updateTimer_Tick); this.ImageList = new ImageList(); this.ImageList.Images.Add(Resources.learning_16_gif); this.ImageList.Images.Add(Resources.folder_gif); this.ImageList.Images.Add(Resources.folder_saved_search_gif); this.ImageList.Images.Add(Resources.network_gif); this.ImageList.Images.Add(Resources.network_offline_gif); this.ImageList.Images.Add(Resources.system_search_gif); this.ImageList.Images.Add(Resources.usbDrive); this.ImageList.Images.Add(Resources.ML); InitTreeView(); } private FolderTreeNode mainNode = new FolderTreeNode(); private void InitTreeView() { base.Nodes.Add(mainNode); mainNode.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(mainNode_ContentLoadException); mainNode.Expand(); mainNode.UpdateDetails(); Nodes = new List<FolderTreeNode>(); Nodes.Add(mainNode); Folders = new ObservableList<FolderIndexEntry>(); Folders.ListChanged += new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged); Connections = new ObservableList<IConnectionString>(); Connections.ListChanged += new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged); } /// <summary> /// Sets the feeds. /// </summary> /// <param name="feeds">The feeds.</param> /// <remarks>CFI, 2012-03-03</remarks> public void SetFeeds(ObservableCollection<ModuleFeedConnection> feeds) { List<TreeNode> nodesToRemove = new List<TreeNode>(); foreach (TreeNode node in base.Nodes) if (node is FeedTreeNode) nodesToRemove.Add(node); nodesToRemove.ForEach(n => base.Nodes.Remove(n)); if(Feeds != null) Feeds.CollectionChanged -= feeds_CollectionChanged; Feeds = feeds; Feeds.CollectionChanged += new NotifyCollectionChangedEventHandler(feeds_CollectionChanged); foreach (ModuleFeedConnection feed in Feeds) base.Nodes.Add(new FeedTreeNode(feed)); } /// <summary> /// Handles the CollectionChanged event of the feeds control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Collections.Specialized.NotifyCollectionChangedEventArgs"/> instance containing the event data.</param> /// <remarks>CFI, 2012-03-03</remarks> protected void feeds_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (ModuleFeedConnection item in e.NewItems) base.Nodes.Add(new FeedTreeNode(item)); break; case NotifyCollectionChangedAction.Remove: break; case NotifyCollectionChangedAction.Replace: case NotifyCollectionChangedAction.Reset: SetFeeds(sender as ObservableCollection<ModuleFeedConnection>); break; case NotifyCollectionChangedAction.Move: default: break; } } /// <summary> /// Mains the node_ content load exception. /// </summary> /// <param name="sender">The sender.</param> /// <param name="exp">The exp.</param> /// <remarks>Documented by Dev02, 2009-05-14</remarks> private void mainNode_ContentLoadException(object sender, Exception exp) { if (ContentLoadException != null) ContentLoadException(sender, exp); } /// <summary> /// Replaces the connections and rebuilds the tree. /// </summary> /// <param name="connections">The connections.</param> /// <remarks>Documented by Dev03, 2009-03-20</remarks> public void ReplaceConnections(List<IConnectionString> connections) { if (Connections.Count == 0) Connections.AddRange(connections); else { Folders.ListChanged -= new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged); Connections.ListChanged -= new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged); mainNode.Nodes.Clear(); Folders.Clear(); Connections.Clear(); Folders.ListChanged += new EventHandler<ObservableListChangedEventArgs<FolderIndexEntry>>(Folders_ListChanged); Connections.ListChanged += new EventHandler<ObservableListChangedEventArgs<IConnectionString>>(Connections_ListChanged); Connections.AddRange(connections); } } /// <summary> /// Handles the Tick event of the updateTimer control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-16</remarks> private void updateTimer_Tick(object sender, EventArgs e) { BeginUpdate(); try { lock (Nodes) { if (!Nodes.Exists(n => n.IsLoading)) updateTimer.Enabled = false; Nodes.ForEach(n => n.UpdateDetails()); } } catch (Exception exp) { Trace.WriteLine(exp.ToString()); } EndUpdate(); } /// <summary> /// Handles the ListChanged event of the Connections control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MLifter.Components.ObservableListChangedEventArgs&lt;MLifter.BusinessLayer.IConnectionString&gt;"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-12</remarks> private void Connections_ListChanged(object sender, ObservableListChangedEventArgs<IConnectionString> e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: if (Folders.Find(f => f.Connection == e.Item) == null) { FolderTreeNode entry = new FolderTreeNode(e.Item); entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException); lock (Nodes) { Nodes.Add(entry); } if (InvokeRequired) Invoke((MethodInvoker)delegate { AddFolderToMainNode(entry); }); else AddFolderToMainNode(entry); entry.UpdateDetails(); } break; case ListChangedType.ItemDeleted: if (InvokeRequired) Invoke((MethodInvoker)delegate { lock (Nodes) { Nodes.FindAll(f => f.Connection == e.Item).ForEach(f => base.Nodes.Remove(f)); Nodes.RemoveAll(f => f.Connection == e.Item); } }); else { lock (Nodes) { Nodes.FindAll(f => f.Connection == e.Item).ForEach(f => base.Nodes.Remove(f)); Nodes.RemoveAll(f => f.Connection == e.Item); } } break; case ListChangedType.ItemChanged: break; case ListChangedType.Reset: foreach (IConnectionString item in Connections) { if (Folders.Find(f => f.Connection == item) == null) { FolderTreeNode entry = new FolderTreeNode(item); entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException); lock (Nodes) { Nodes.Add(entry); } if (InvokeRequired) Invoke((MethodInvoker)delegate { AddFolderToMainNode(entry); }); else AddFolderToMainNode(entry); entry.UpdateDetails(); } } break; case ListChangedType.ItemMoved: default: throw new NotSupportedException(); } updateTimer.Enabled = true; } private void AddFolderToMainNode(FolderTreeNode entry) { BeginUpdate(); lock (Nodes) { Nodes.Find(n => n.IsMainNode).Nodes.Add(entry); } EndUpdate(); } /// <summary> /// Handles the ListChanged event of the Folders list. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="MLifter.Components.ObservableListChangedEventArgs&lt;MLifter.BusinessLayer.FolderIndexEntry&gt;"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-12</remarks> private void Folders_ListChanged(object sender, ObservableListChangedEventArgs<FolderIndexEntry> e) { switch (e.ListChangedType) { case ListChangedType.ItemAdded: if (!Connections.Contains(e.Item.Connection)) Connections.Add(e.Item.Connection); if (e.Item.Parent != null) { try { FolderTreeNode entry = new FolderTreeNode(e.Item); entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException); lock (Nodes) { Nodes.Add(entry); } while (Nodes.Find(n => n.Folder == e.Item.Parent) == null) Thread.Sleep(10); if (InvokeRequired) Invoke((MethodInvoker)delegate { AddFolderToParent(e.Item.Parent, entry); }); else entry.UpdateDetails(); } catch (Exception exp) { Trace.WriteLine("Folder-Added: " + exp.ToString()); } } else { FolderTreeNode node = Nodes.Find(n => n.Connection == e.Item.Connection); if (node != null) node.SetFolder(e.Item); else { FolderTreeNode entry = new FolderTreeNode(e.Item); entry.ContentLoadException += new FolderIndexEntry.ContentLoadExceptionEventHandler(Folder_ContentLoadException); lock (Nodes) { Nodes.Add(entry); } Delegate add = (MethodInvoker)delegate { BeginUpdate(); lock (Nodes) { Nodes.Find(n => n.IsMainNode).Nodes.Add(entry); } EndUpdate(); }; if (InvokeRequired) Invoke((MethodInvoker)add); else add.DynamicInvoke(); entry.UpdateDetails(); } } e.Item.ContentLoading += new EventHandler(Folder_ContentLoading); break; case ListChangedType.ItemDeleted: throw new NotImplementedException(); case ListChangedType.ItemChanged: break; case ListChangedType.Reset: case ListChangedType.ItemMoved: default: throw new NotSupportedException(); } updateTimer.Enabled = true; } /// <summary> /// Folder_s the content load exception. /// </summary> /// <param name="sender">The sender.</param> /// <param name="exp">The exp.</param> /// <remarks>Documented by Dev05, 2009-05-15</remarks> private void Folder_ContentLoadException(object sender, Exception exp) { if (ContentLoadException != null) ContentLoadException(sender, exp); } private void Folder_ContentLoading(object sender, EventArgs e) { updateTimer.Enabled = true; } private void AddFolderToParent(FolderIndexEntry parent, FolderTreeNode entry) { BeginUpdate(); lock (Nodes) { Nodes.Find(n => n.Folder == parent).Nodes.Add(entry); } EndUpdate(); } } }
// Artificial Intelligence for Humans // Volume 2: Nature-Inspired Algorithms // C# Version // http://www.aifh.org // http://www.jeffheaton.com // // Code repository: // https://github.com/jeffheaton/aifh // // Copyright 2014 by Jeff Heaton // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Globalization; using System.Text; using AIFH_Vol2.Core; using AIFH_Vol2.Core.Genetic.Trees; using AIFH_Vol2.Core.Randomize; namespace AIFH_Vol2.Examples.GP { /// <summary> /// Evaluate expression. This class shows how to construct a tree evaluator that will evaluate the following /// operators: /// /// add, sub, div, mul, negative, power, sqrt, as well as variables. /// /// This class could easily be modified to support additional operators. /// </summary> public class EvaluateExpression : EvaluateTree { /// <summary> /// The opcode for add. /// </summary> public const int OPCODE_ADD = 0; /// <summary> /// The opcode for subtract. /// </summary> public const int OPCODE_SUB = 1; /// <summary> /// The opcode for divide. /// </summary> public const int OPCODE_DIV = 2; /// <summary> /// The opcode for multiply. /// </summary> public const int OPCODE_MUL = 3; /// <summary> /// The opcode for negative. /// </summary> public const int OPCODE_NEG = 4; /// <summary> /// The opcode for raise to the power. /// </summary> public const int OPCODE_POWER = 5; /// <summary> /// The opcode for square root. /// </summary> public const int OPCODE_SQRT = 6; /// <summary> /// The start of the constant and variable opcodes. /// </summary> public const int OPCODE_VAR_CONST = 7; /// <summary> /// The constant values. /// </summary> private readonly double[] constValues; /// <summary> /// The number of variables. /// </summary> private readonly int varCount; /// <summary> /// The constructor. /// </summary> /// <param name="rnd">A random number generator.</param> /// <param name="numConst">The number of constants.</param> /// <param name="numVar">The number of variables.</param> /// <param name="minConstValue">The minimum amount for a constant.</param> /// <param name="maxConstValue">The maximum amount for a constant.</param> public EvaluateExpression(IGenerateRandom rnd, int numConst, int numVar, double minConstValue, double maxConstValue) { constValues = new double[numConst]; varCount = numVar; for (int i = 0; i < constValues.Length; i++) { constValues[i] = rnd.NextDouble(minConstValue, maxConstValue); } } /** * Construct an evaluator with 1 variable, and 100 constants ranging between (-5,5) * * @param rnd A random number generator. */ public EvaluateExpression(IGenerateRandom rnd) : this(rnd, 100, 1, -5, 5) { } /// <inheritdoc /> public override int VarConstOpcode { get { return OPCODE_VAR_CONST; } } /// <inheritdoc /> public override int NumConst { get { return constValues.Length; } } /// <inheritdoc /> public override int NumVar { get { return varCount; } } /// <inheritdoc /> public override int DetermineChildCount(int opcode) { switch (opcode) { case OPCODE_ADD: return 2; case OPCODE_SUB: return 2; case OPCODE_DIV: return 2; case OPCODE_MUL: return 2; case OPCODE_NEG: return 1; case OPCODE_POWER: return 2; case OPCODE_SQRT: return 1; default: return 0; } } /// <summary> /// Get the text for an opcode. /// </summary> /// <param name="opcode">The opcode.</param> /// <returns>The text for the opcode.</returns> public String GetOpcodeText(int opcode) { switch (opcode) { case OPCODE_NEG: return "-"; case OPCODE_ADD: return "+"; case OPCODE_SUB: return "-"; case OPCODE_DIV: return "/"; case OPCODE_MUL: return "*"; case OPCODE_POWER: return "^"; case OPCODE_SQRT: return "sqrt"; default: int index = opcode - OPCODE_VAR_CONST; if (index >= (constValues.Length + varCount)) { throw new AIFHError("Invalid opcode: " + opcode); } if (index < varCount) { return "" + ((char)('a' + index)); } return constValues[index - varCount].ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Display an expression as LISP (the programming language) /// </summary> /// <param name="node">The root node.</param> /// <returns>The LISP for the expression.</returns> public String DisplayExpressionLISP(TreeGenomeNode node) { var result = new StringBuilder(); if (DetermineChildCount(node.Opcode) == 0) { result.Append(GetOpcodeText(node.Opcode)); } else { result.Append("("); result.Append(GetOpcodeText(node.Opcode)); foreach (TreeGenomeNode child in node.Children) { result.Append(" "); result.Append(DisplayExpressionLISP(child)); } result.Append(")"); } return result.ToString(); } /// <summary> /// Display an expression as normal infix. /// </summary> /// <param name="node">The root node.</param> /// <returns>The infix string.</returns> public String DisplayExpressionNormal(TreeGenomeNode node) { var result = new StringBuilder(); if (DetermineChildCount(node.Opcode) == 0) { result.Append(GetOpcodeText(node.Opcode)); } else { int childCount = DetermineChildCount(node.Opcode); if (childCount == 0) { result.Append(GetOpcodeText(node.Opcode)); } else { String name = GetOpcodeText(node.Opcode); if (name.Length > 1) { result.Append(name); result.Append("("); bool first = true; foreach (TreeGenomeNode child in node.Children) { if (!first) { result.Append(","); } result.Append(DisplayExpressionNormal(child)); first = false; } result.Append(")"); } else { result.Append("("); if (childCount == 2) { result.Append(DisplayExpressionNormal(node.Children[0])); result.Append(name); result.Append(DisplayExpressionNormal(node.Children[1])); result.Append(")"); } else { result.Append(name); result.Append(DisplayExpressionNormal(node.Children[0])); result.Append(")"); } } } } return result.ToString(); } /// <inheritdoc /> public override double Evaluate(TreeGenomeNode node, double[] varValues) { switch (node.Opcode) { case OPCODE_NEG: return -(Evaluate(node.Children[0], varValues)); case OPCODE_ADD: return Evaluate(node.Children[0], varValues) + Evaluate(node.Children[1], varValues); case OPCODE_SUB: return Evaluate(node.Children[0], varValues) - Evaluate(node.Children[1], varValues); case OPCODE_DIV: return Evaluate(node.Children[0], varValues) / Evaluate(node.Children[1], varValues); case OPCODE_MUL: return Evaluate(node.Children[0], varValues) * Evaluate(node.Children[1], varValues); case OPCODE_POWER: return Math.Pow(Evaluate(node.Children[0], varValues), Evaluate(node.Children[1], varValues)); case OPCODE_SQRT: return Math.Sqrt(Evaluate(node.Children[0], varValues)); default: int index = node.Opcode - OPCODE_VAR_CONST; if (index >= (constValues.Length + varCount)) { throw new AIFHError("Invalid opcode: " + node.Opcode); } if (index < varCount) { return varValues[index]; } return constValues[index - varCount]; } } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // File implements Slicing-by-8 CRC Generation, as described in // "Novel Table Lookup-Based Algorithms for High-Performance CRC Generation" // IEEE TRANSACTIONS ON COMPUTERS, VOL. 57, NO. 11, NOVEMBER 2008 /* * Copyright (c) 2004-2006 Intel Corporation - All Rights Reserved * * * This software program is licensed subject to the BSD License, * available at http://www.opensource.org/licenses/bsd-license.html. */ using System.Diagnostics; namespace System.IO.Compression { /// <summary> /// This class contains a managed Crc32 function as well as an indirection to the Interop.Zlib.Crc32 call. /// Since Desktop compression uses this file alongside the Open ZipArchive, we cannot remove it /// without breaking the Desktop build. /// /// Note that in CoreFX the ZlibCrc32 function is always called. /// </summary> internal static class Crc32Helper { // Calculate CRC based on the old CRC and the new bytes // See RFC1952 for details. public static uint UpdateCrc32(uint crc32, byte[] buffer, int offset, int length) { Debug.Assert((buffer != null) && (offset >= 0) && (length >= 0) && (offset <= buffer.Length - length), "check the caller"); #if FEATURE_ZLIB return Interop.zlib.crc32(crc32, buffer, offset, length); #else return ManagedCrc32(crc32, buffer, offset, length); #endif } #if !FEATURE_ZLIB // Generated tables for managed crc calculation. // Each table n (starting at 0) contains remainders from the long division of // all possible byte values, shifted by an offset of (n * 4 bits). // The divisor used is the crc32 standard polynomial 0xEDB88320 // Please see cited paper for more details. private static readonly uint[] s_crcTable_0 = new uint[256] { 0x00000000u, 0x77073096u, 0xee0e612cu, 0x990951bau, 0x076dc419u, 0x706af48fu, 0xe963a535u, 0x9e6495a3u, 0x0edb8832u, 0x79dcb8a4u, 0xe0d5e91eu, 0x97d2d988u, 0x09b64c2bu, 0x7eb17cbdu, 0xe7b82d07u, 0x90bf1d91u, 0x1db71064u, 0x6ab020f2u, 0xf3b97148u, 0x84be41deu, 0x1adad47du, 0x6ddde4ebu, 0xf4d4b551u, 0x83d385c7u, 0x136c9856u, 0x646ba8c0u, 0xfd62f97au, 0x8a65c9ecu, 0x14015c4fu, 0x63066cd9u, 0xfa0f3d63u, 0x8d080df5u, 0x3b6e20c8u, 0x4c69105eu, 0xd56041e4u, 0xa2677172u, 0x3c03e4d1u, 0x4b04d447u, 0xd20d85fdu, 0xa50ab56bu, 0x35b5a8fau, 0x42b2986cu, 0xdbbbc9d6u, 0xacbcf940u, 0x32d86ce3u, 0x45df5c75u, 0xdcd60dcfu, 0xabd13d59u, 0x26d930acu, 0x51de003au, 0xc8d75180u, 0xbfd06116u, 0x21b4f4b5u, 0x56b3c423u, 0xcfba9599u, 0xb8bda50fu, 0x2802b89eu, 0x5f058808u, 0xc60cd9b2u, 0xb10be924u, 0x2f6f7c87u, 0x58684c11u, 0xc1611dabu, 0xb6662d3du, 0x76dc4190u, 0x01db7106u, 0x98d220bcu, 0xefd5102au, 0x71b18589u, 0x06b6b51fu, 0x9fbfe4a5u, 0xe8b8d433u, 0x7807c9a2u, 0x0f00f934u, 0x9609a88eu, 0xe10e9818u, 0x7f6a0dbbu, 0x086d3d2du, 0x91646c97u, 0xe6635c01u, 0x6b6b51f4u, 0x1c6c6162u, 0x856530d8u, 0xf262004eu, 0x6c0695edu, 0x1b01a57bu, 0x8208f4c1u, 0xf50fc457u, 0x65b0d9c6u, 0x12b7e950u, 0x8bbeb8eau, 0xfcb9887cu, 0x62dd1ddfu, 0x15da2d49u, 0x8cd37cf3u, 0xfbd44c65u, 0x4db26158u, 0x3ab551ceu, 0xa3bc0074u, 0xd4bb30e2u, 0x4adfa541u, 0x3dd895d7u, 0xa4d1c46du, 0xd3d6f4fbu, 0x4369e96au, 0x346ed9fcu, 0xad678846u, 0xda60b8d0u, 0x44042d73u, 0x33031de5u, 0xaa0a4c5fu, 0xdd0d7cc9u, 0x5005713cu, 0x270241aau, 0xbe0b1010u, 0xc90c2086u, 0x5768b525u, 0x206f85b3u, 0xb966d409u, 0xce61e49fu, 0x5edef90eu, 0x29d9c998u, 0xb0d09822u, 0xc7d7a8b4u, 0x59b33d17u, 0x2eb40d81u, 0xb7bd5c3bu, 0xc0ba6cadu, 0xedb88320u, 0x9abfb3b6u, 0x03b6e20cu, 0x74b1d29au, 0xead54739u, 0x9dd277afu, 0x04db2615u, 0x73dc1683u, 0xe3630b12u, 0x94643b84u, 0x0d6d6a3eu, 0x7a6a5aa8u, 0xe40ecf0bu, 0x9309ff9du, 0x0a00ae27u, 0x7d079eb1u, 0xf00f9344u, 0x8708a3d2u, 0x1e01f268u, 0x6906c2feu, 0xf762575du, 0x806567cbu, 0x196c3671u, 0x6e6b06e7u, 0xfed41b76u, 0x89d32be0u, 0x10da7a5au, 0x67dd4accu, 0xf9b9df6fu, 0x8ebeeff9u, 0x17b7be43u, 0x60b08ed5u, 0xd6d6a3e8u, 0xa1d1937eu, 0x38d8c2c4u, 0x4fdff252u, 0xd1bb67f1u, 0xa6bc5767u, 0x3fb506ddu, 0x48b2364bu, 0xd80d2bdau, 0xaf0a1b4cu, 0x36034af6u, 0x41047a60u, 0xdf60efc3u, 0xa867df55u, 0x316e8eefu, 0x4669be79u, 0xcb61b38cu, 0xbc66831au, 0x256fd2a0u, 0x5268e236u, 0xcc0c7795u, 0xbb0b4703u, 0x220216b9u, 0x5505262fu, 0xc5ba3bbeu, 0xb2bd0b28u, 0x2bb45a92u, 0x5cb36a04u, 0xc2d7ffa7u, 0xb5d0cf31u, 0x2cd99e8bu, 0x5bdeae1du, 0x9b64c2b0u, 0xec63f226u, 0x756aa39cu, 0x026d930au, 0x9c0906a9u, 0xeb0e363fu, 0x72076785u, 0x05005713u, 0x95bf4a82u, 0xe2b87a14u, 0x7bb12baeu, 0x0cb61b38u, 0x92d28e9bu, 0xe5d5be0du, 0x7cdcefb7u, 0x0bdbdf21u, 0x86d3d2d4u, 0xf1d4e242u, 0x68ddb3f8u, 0x1fda836eu, 0x81be16cdu, 0xf6b9265bu, 0x6fb077e1u, 0x18b74777u, 0x88085ae6u, 0xff0f6a70u, 0x66063bcau, 0x11010b5cu, 0x8f659effu, 0xf862ae69u, 0x616bffd3u, 0x166ccf45u, 0xa00ae278u, 0xd70dd2eeu, 0x4e048354u, 0x3903b3c2u, 0xa7672661u, 0xd06016f7u, 0x4969474du, 0x3e6e77dbu, 0xaed16a4au, 0xd9d65adcu, 0x40df0b66u, 0x37d83bf0u, 0xa9bcae53u, 0xdebb9ec5u, 0x47b2cf7fu, 0x30b5ffe9u, 0xbdbdf21cu, 0xcabac28au, 0x53b39330u, 0x24b4a3a6u, 0xbad03605u, 0xcdd70693u, 0x54de5729u, 0x23d967bfu, 0xb3667a2eu, 0xc4614ab8u, 0x5d681b02u, 0x2a6f2b94u, 0xb40bbe37u, 0xc30c8ea1u, 0x5a05df1bu, 0x2d02ef8du }; private static readonly uint[] s_crcTable_1 = new uint[256] { 0x00000000u, 0x191B3141u, 0x32366282u, 0x2B2D53C3u, 0x646CC504u, 0x7D77F445u, 0x565AA786u, 0x4F4196C7u, 0xC8D98A08u, 0xD1C2BB49u, 0xFAEFE88Au, 0xE3F4D9CBu, 0xACB54F0Cu, 0xB5AE7E4Du, 0x9E832D8Eu, 0x87981CCFu, 0x4AC21251u, 0x53D92310u, 0x78F470D3u, 0x61EF4192u, 0x2EAED755u, 0x37B5E614u, 0x1C98B5D7u, 0x05838496u, 0x821B9859u, 0x9B00A918u, 0xB02DFADBu, 0xA936CB9Au, 0xE6775D5Du, 0xFF6C6C1Cu, 0xD4413FDFu, 0xCD5A0E9Eu, 0x958424A2u, 0x8C9F15E3u, 0xA7B24620u, 0xBEA97761u, 0xF1E8E1A6u, 0xE8F3D0E7u, 0xC3DE8324u, 0xDAC5B265u, 0x5D5DAEAAu, 0x44469FEBu, 0x6F6BCC28u, 0x7670FD69u, 0x39316BAEu, 0x202A5AEFu, 0x0B07092Cu, 0x121C386Du, 0xDF4636F3u, 0xC65D07B2u, 0xED705471u, 0xF46B6530u, 0xBB2AF3F7u, 0xA231C2B6u, 0x891C9175u, 0x9007A034u, 0x179FBCFBu, 0x0E848DBAu, 0x25A9DE79u, 0x3CB2EF38u, 0x73F379FFu, 0x6AE848BEu, 0x41C51B7Du, 0x58DE2A3Cu, 0xF0794F05u, 0xE9627E44u, 0xC24F2D87u, 0xDB541CC6u, 0x94158A01u, 0x8D0EBB40u, 0xA623E883u, 0xBF38D9C2u, 0x38A0C50Du, 0x21BBF44Cu, 0x0A96A78Fu, 0x138D96CEu, 0x5CCC0009u, 0x45D73148u, 0x6EFA628Bu, 0x77E153CAu, 0xBABB5D54u, 0xA3A06C15u, 0x888D3FD6u, 0x91960E97u, 0xDED79850u, 0xC7CCA911u, 0xECE1FAD2u, 0xF5FACB93u, 0x7262D75Cu, 0x6B79E61Du, 0x4054B5DEu, 0x594F849Fu, 0x160E1258u, 0x0F152319u, 0x243870DAu, 0x3D23419Bu, 0x65FD6BA7u, 0x7CE65AE6u, 0x57CB0925u, 0x4ED03864u, 0x0191AEA3u, 0x188A9FE2u, 0x33A7CC21u, 0x2ABCFD60u, 0xAD24E1AFu, 0xB43FD0EEu, 0x9F12832Du, 0x8609B26Cu, 0xC94824ABu, 0xD05315EAu, 0xFB7E4629u, 0xE2657768u, 0x2F3F79F6u, 0x362448B7u, 0x1D091B74u, 0x04122A35u, 0x4B53BCF2u, 0x52488DB3u, 0x7965DE70u, 0x607EEF31u, 0xE7E6F3FEu, 0xFEFDC2BFu, 0xD5D0917Cu, 0xCCCBA03Du, 0x838A36FAu, 0x9A9107BBu, 0xB1BC5478u, 0xA8A76539u, 0x3B83984Bu, 0x2298A90Au, 0x09B5FAC9u, 0x10AECB88u, 0x5FEF5D4Fu, 0x46F46C0Eu, 0x6DD93FCDu, 0x74C20E8Cu, 0xF35A1243u, 0xEA412302u, 0xC16C70C1u, 0xD8774180u, 0x9736D747u, 0x8E2DE606u, 0xA500B5C5u, 0xBC1B8484u, 0x71418A1Au, 0x685ABB5Bu, 0x4377E898u, 0x5A6CD9D9u, 0x152D4F1Eu, 0x0C367E5Fu, 0x271B2D9Cu, 0x3E001CDDu, 0xB9980012u, 0xA0833153u, 0x8BAE6290u, 0x92B553D1u, 0xDDF4C516u, 0xC4EFF457u, 0xEFC2A794u, 0xF6D996D5u, 0xAE07BCE9u, 0xB71C8DA8u, 0x9C31DE6Bu, 0x852AEF2Au, 0xCA6B79EDu, 0xD37048ACu, 0xF85D1B6Fu, 0xE1462A2Eu, 0x66DE36E1u, 0x7FC507A0u, 0x54E85463u, 0x4DF36522u, 0x02B2F3E5u, 0x1BA9C2A4u, 0x30849167u, 0x299FA026u, 0xE4C5AEB8u, 0xFDDE9FF9u, 0xD6F3CC3Au, 0xCFE8FD7Bu, 0x80A96BBCu, 0x99B25AFDu, 0xB29F093Eu, 0xAB84387Fu, 0x2C1C24B0u, 0x350715F1u, 0x1E2A4632u, 0x07317773u, 0x4870E1B4u, 0x516BD0F5u, 0x7A468336u, 0x635DB277u, 0xCBFAD74Eu, 0xD2E1E60Fu, 0xF9CCB5CCu, 0xE0D7848Du, 0xAF96124Au, 0xB68D230Bu, 0x9DA070C8u, 0x84BB4189u, 0x03235D46u, 0x1A386C07u, 0x31153FC4u, 0x280E0E85u, 0x674F9842u, 0x7E54A903u, 0x5579FAC0u, 0x4C62CB81u, 0x8138C51Fu, 0x9823F45Eu, 0xB30EA79Du, 0xAA1596DCu, 0xE554001Bu, 0xFC4F315Au, 0xD7626299u, 0xCE7953D8u, 0x49E14F17u, 0x50FA7E56u, 0x7BD72D95u, 0x62CC1CD4u, 0x2D8D8A13u, 0x3496BB52u, 0x1FBBE891u, 0x06A0D9D0u, 0x5E7EF3ECu, 0x4765C2ADu, 0x6C48916Eu, 0x7553A02Fu, 0x3A1236E8u, 0x230907A9u, 0x0824546Au, 0x113F652Bu, 0x96A779E4u, 0x8FBC48A5u, 0xA4911B66u, 0xBD8A2A27u, 0xF2CBBCE0u, 0xEBD08DA1u, 0xC0FDDE62u, 0xD9E6EF23u, 0x14BCE1BDu, 0x0DA7D0FCu, 0x268A833Fu, 0x3F91B27Eu, 0x70D024B9u, 0x69CB15F8u, 0x42E6463Bu, 0x5BFD777Au, 0xDC656BB5u, 0xC57E5AF4u, 0xEE530937u, 0xF7483876u, 0xB809AEB1u, 0xA1129FF0u, 0x8A3FCC33u, 0x9324FD72u }; private static readonly uint[] s_crcTable_2 = new uint[256] { 0x00000000u, 0x01C26A37u, 0x0384D46Eu, 0x0246BE59u, 0x0709A8DCu, 0x06CBC2EBu, 0x048D7CB2u, 0x054F1685u, 0x0E1351B8u, 0x0FD13B8Fu, 0x0D9785D6u, 0x0C55EFE1u, 0x091AF964u, 0x08D89353u, 0x0A9E2D0Au, 0x0B5C473Du, 0x1C26A370u, 0x1DE4C947u, 0x1FA2771Eu, 0x1E601D29u, 0x1B2F0BACu, 0x1AED619Bu, 0x18ABDFC2u, 0x1969B5F5u, 0x1235F2C8u, 0x13F798FFu, 0x11B126A6u, 0x10734C91u, 0x153C5A14u, 0x14FE3023u, 0x16B88E7Au, 0x177AE44Du, 0x384D46E0u, 0x398F2CD7u, 0x3BC9928Eu, 0x3A0BF8B9u, 0x3F44EE3Cu, 0x3E86840Bu, 0x3CC03A52u, 0x3D025065u, 0x365E1758u, 0x379C7D6Fu, 0x35DAC336u, 0x3418A901u, 0x3157BF84u, 0x3095D5B3u, 0x32D36BEAu, 0x331101DDu, 0x246BE590u, 0x25A98FA7u, 0x27EF31FEu, 0x262D5BC9u, 0x23624D4Cu, 0x22A0277Bu, 0x20E69922u, 0x2124F315u, 0x2A78B428u, 0x2BBADE1Fu, 0x29FC6046u, 0x283E0A71u, 0x2D711CF4u, 0x2CB376C3u, 0x2EF5C89Au, 0x2F37A2ADu, 0x709A8DC0u, 0x7158E7F7u, 0x731E59AEu, 0x72DC3399u, 0x7793251Cu, 0x76514F2Bu, 0x7417F172u, 0x75D59B45u, 0x7E89DC78u, 0x7F4BB64Fu, 0x7D0D0816u, 0x7CCF6221u, 0x798074A4u, 0x78421E93u, 0x7A04A0CAu, 0x7BC6CAFDu, 0x6CBC2EB0u, 0x6D7E4487u, 0x6F38FADEu, 0x6EFA90E9u, 0x6BB5866Cu, 0x6A77EC5Bu, 0x68315202u, 0x69F33835u, 0x62AF7F08u, 0x636D153Fu, 0x612BAB66u, 0x60E9C151u, 0x65A6D7D4u, 0x6464BDE3u, 0x662203BAu, 0x67E0698Du, 0x48D7CB20u, 0x4915A117u, 0x4B531F4Eu, 0x4A917579u, 0x4FDE63FCu, 0x4E1C09CBu, 0x4C5AB792u, 0x4D98DDA5u, 0x46C49A98u, 0x4706F0AFu, 0x45404EF6u, 0x448224C1u, 0x41CD3244u, 0x400F5873u, 0x4249E62Au, 0x438B8C1Du, 0x54F16850u, 0x55330267u, 0x5775BC3Eu, 0x56B7D609u, 0x53F8C08Cu, 0x523AAABBu, 0x507C14E2u, 0x51BE7ED5u, 0x5AE239E8u, 0x5B2053DFu, 0x5966ED86u, 0x58A487B1u, 0x5DEB9134u, 0x5C29FB03u, 0x5E6F455Au, 0x5FAD2F6Du, 0xE1351B80u, 0xE0F771B7u, 0xE2B1CFEEu, 0xE373A5D9u, 0xE63CB35Cu, 0xE7FED96Bu, 0xE5B86732u, 0xE47A0D05u, 0xEF264A38u, 0xEEE4200Fu, 0xECA29E56u, 0xED60F461u, 0xE82FE2E4u, 0xE9ED88D3u, 0xEBAB368Au, 0xEA695CBDu, 0xFD13B8F0u, 0xFCD1D2C7u, 0xFE976C9Eu, 0xFF5506A9u, 0xFA1A102Cu, 0xFBD87A1Bu, 0xF99EC442u, 0xF85CAE75u, 0xF300E948u, 0xF2C2837Fu, 0xF0843D26u, 0xF1465711u, 0xF4094194u, 0xF5CB2BA3u, 0xF78D95FAu, 0xF64FFFCDu, 0xD9785D60u, 0xD8BA3757u, 0xDAFC890Eu, 0xDB3EE339u, 0xDE71F5BCu, 0xDFB39F8Bu, 0xDDF521D2u, 0xDC374BE5u, 0xD76B0CD8u, 0xD6A966EFu, 0xD4EFD8B6u, 0xD52DB281u, 0xD062A404u, 0xD1A0CE33u, 0xD3E6706Au, 0xD2241A5Du, 0xC55EFE10u, 0xC49C9427u, 0xC6DA2A7Eu, 0xC7184049u, 0xC25756CCu, 0xC3953CFBu, 0xC1D382A2u, 0xC011E895u, 0xCB4DAFA8u, 0xCA8FC59Fu, 0xC8C97BC6u, 0xC90B11F1u, 0xCC440774u, 0xCD866D43u, 0xCFC0D31Au, 0xCE02B92Du, 0x91AF9640u, 0x906DFC77u, 0x922B422Eu, 0x93E92819u, 0x96A63E9Cu, 0x976454ABu, 0x9522EAF2u, 0x94E080C5u, 0x9FBCC7F8u, 0x9E7EADCFu, 0x9C381396u, 0x9DFA79A1u, 0x98B56F24u, 0x99770513u, 0x9B31BB4Au, 0x9AF3D17Du, 0x8D893530u, 0x8C4B5F07u, 0x8E0DE15Eu, 0x8FCF8B69u, 0x8A809DECu, 0x8B42F7DBu, 0x89044982u, 0x88C623B5u, 0x839A6488u, 0x82580EBFu, 0x801EB0E6u, 0x81DCDAD1u, 0x8493CC54u, 0x8551A663u, 0x8717183Au, 0x86D5720Du, 0xA9E2D0A0u, 0xA820BA97u, 0xAA6604CEu, 0xABA46EF9u, 0xAEEB787Cu, 0xAF29124Bu, 0xAD6FAC12u, 0xACADC625u, 0xA7F18118u, 0xA633EB2Fu, 0xA4755576u, 0xA5B73F41u, 0xA0F829C4u, 0xA13A43F3u, 0xA37CFDAAu, 0xA2BE979Du, 0xB5C473D0u, 0xB40619E7u, 0xB640A7BEu, 0xB782CD89u, 0xB2CDDB0Cu, 0xB30FB13Bu, 0xB1490F62u, 0xB08B6555u, 0xBBD72268u, 0xBA15485Fu, 0xB853F606u, 0xB9919C31u, 0xBCDE8AB4u, 0xBD1CE083u, 0xBF5A5EDAu, 0xBE9834EDu }; private static readonly uint[] s_crcTable_3 = new uint[256] { 0x00000000u, 0xB8BC6765u, 0xAA09C88Bu, 0x12B5AFEEu, 0x8F629757u, 0x37DEF032u, 0x256B5FDCu, 0x9DD738B9u, 0xC5B428EFu, 0x7D084F8Au, 0x6FBDE064u, 0xD7018701u, 0x4AD6BFB8u, 0xF26AD8DDu, 0xE0DF7733u, 0x58631056u, 0x5019579Fu, 0xE8A530FAu, 0xFA109F14u, 0x42ACF871u, 0xDF7BC0C8u, 0x67C7A7ADu, 0x75720843u, 0xCDCE6F26u, 0x95AD7F70u, 0x2D111815u, 0x3FA4B7FBu, 0x8718D09Eu, 0x1ACFE827u, 0xA2738F42u, 0xB0C620ACu, 0x087A47C9u, 0xA032AF3Eu, 0x188EC85Bu, 0x0A3B67B5u, 0xB28700D0u, 0x2F503869u, 0x97EC5F0Cu, 0x8559F0E2u, 0x3DE59787u, 0x658687D1u, 0xDD3AE0B4u, 0xCF8F4F5Au, 0x7733283Fu, 0xEAE41086u, 0x525877E3u, 0x40EDD80Du, 0xF851BF68u, 0xF02BF8A1u, 0x48979FC4u, 0x5A22302Au, 0xE29E574Fu, 0x7F496FF6u, 0xC7F50893u, 0xD540A77Du, 0x6DFCC018u, 0x359FD04Eu, 0x8D23B72Bu, 0x9F9618C5u, 0x272A7FA0u, 0xBAFD4719u, 0x0241207Cu, 0x10F48F92u, 0xA848E8F7u, 0x9B14583Du, 0x23A83F58u, 0x311D90B6u, 0x89A1F7D3u, 0x1476CF6Au, 0xACCAA80Fu, 0xBE7F07E1u, 0x06C36084u, 0x5EA070D2u, 0xE61C17B7u, 0xF4A9B859u, 0x4C15DF3Cu, 0xD1C2E785u, 0x697E80E0u, 0x7BCB2F0Eu, 0xC377486Bu, 0xCB0D0FA2u, 0x73B168C7u, 0x6104C729u, 0xD9B8A04Cu, 0x446F98F5u, 0xFCD3FF90u, 0xEE66507Eu, 0x56DA371Bu, 0x0EB9274Du, 0xB6054028u, 0xA4B0EFC6u, 0x1C0C88A3u, 0x81DBB01Au, 0x3967D77Fu, 0x2BD27891u, 0x936E1FF4u, 0x3B26F703u, 0x839A9066u, 0x912F3F88u, 0x299358EDu, 0xB4446054u, 0x0CF80731u, 0x1E4DA8DFu, 0xA6F1CFBAu, 0xFE92DFECu, 0x462EB889u, 0x549B1767u, 0xEC277002u, 0x71F048BBu, 0xC94C2FDEu, 0xDBF98030u, 0x6345E755u, 0x6B3FA09Cu, 0xD383C7F9u, 0xC1366817u, 0x798A0F72u, 0xE45D37CBu, 0x5CE150AEu, 0x4E54FF40u, 0xF6E89825u, 0xAE8B8873u, 0x1637EF16u, 0x048240F8u, 0xBC3E279Du, 0x21E91F24u, 0x99557841u, 0x8BE0D7AFu, 0x335CB0CAu, 0xED59B63Bu, 0x55E5D15Eu, 0x47507EB0u, 0xFFEC19D5u, 0x623B216Cu, 0xDA874609u, 0xC832E9E7u, 0x708E8E82u, 0x28ED9ED4u, 0x9051F9B1u, 0x82E4565Fu, 0x3A58313Au, 0xA78F0983u, 0x1F336EE6u, 0x0D86C108u, 0xB53AA66Du, 0xBD40E1A4u, 0x05FC86C1u, 0x1749292Fu, 0xAFF54E4Au, 0x322276F3u, 0x8A9E1196u, 0x982BBE78u, 0x2097D91Du, 0x78F4C94Bu, 0xC048AE2Eu, 0xD2FD01C0u, 0x6A4166A5u, 0xF7965E1Cu, 0x4F2A3979u, 0x5D9F9697u, 0xE523F1F2u, 0x4D6B1905u, 0xF5D77E60u, 0xE762D18Eu, 0x5FDEB6EBu, 0xC2098E52u, 0x7AB5E937u, 0x680046D9u, 0xD0BC21BCu, 0x88DF31EAu, 0x3063568Fu, 0x22D6F961u, 0x9A6A9E04u, 0x07BDA6BDu, 0xBF01C1D8u, 0xADB46E36u, 0x15080953u, 0x1D724E9Au, 0xA5CE29FFu, 0xB77B8611u, 0x0FC7E174u, 0x9210D9CDu, 0x2AACBEA8u, 0x38191146u, 0x80A57623u, 0xD8C66675u, 0x607A0110u, 0x72CFAEFEu, 0xCA73C99Bu, 0x57A4F122u, 0xEF189647u, 0xFDAD39A9u, 0x45115ECCu, 0x764DEE06u, 0xCEF18963u, 0xDC44268Du, 0x64F841E8u, 0xF92F7951u, 0x41931E34u, 0x5326B1DAu, 0xEB9AD6BFu, 0xB3F9C6E9u, 0x0B45A18Cu, 0x19F00E62u, 0xA14C6907u, 0x3C9B51BEu, 0x842736DBu, 0x96929935u, 0x2E2EFE50u, 0x2654B999u, 0x9EE8DEFCu, 0x8C5D7112u, 0x34E11677u, 0xA9362ECEu, 0x118A49ABu, 0x033FE645u, 0xBB838120u, 0xE3E09176u, 0x5B5CF613u, 0x49E959FDu, 0xF1553E98u, 0x6C820621u, 0xD43E6144u, 0xC68BCEAAu, 0x7E37A9CFu, 0xD67F4138u, 0x6EC3265Du, 0x7C7689B3u, 0xC4CAEED6u, 0x591DD66Fu, 0xE1A1B10Au, 0xF3141EE4u, 0x4BA87981u, 0x13CB69D7u, 0xAB770EB2u, 0xB9C2A15Cu, 0x017EC639u, 0x9CA9FE80u, 0x241599E5u, 0x36A0360Bu, 0x8E1C516Eu, 0x866616A7u, 0x3EDA71C2u, 0x2C6FDE2Cu, 0x94D3B949u, 0x090481F0u, 0xB1B8E695u, 0xA30D497Bu, 0x1BB12E1Eu, 0x43D23E48u, 0xFB6E592Du, 0xE9DBF6C3u, 0x516791A6u, 0xCCB0A91Fu, 0x740CCE7Au, 0x66B96194u, 0xDE0506F1u }; private static readonly uint[] s_crcTable_4 = new uint[256] { 0x00000000u, 0x3D6029B0u, 0x7AC05360u, 0x47A07AD0u, 0xF580A6C0u, 0xC8E08F70u, 0x8F40F5A0u, 0xB220DC10u, 0x30704BC1u, 0x0D106271u, 0x4AB018A1u, 0x77D03111u, 0xC5F0ED01u, 0xF890C4B1u, 0xBF30BE61u, 0x825097D1u, 0x60E09782u, 0x5D80BE32u, 0x1A20C4E2u, 0x2740ED52u, 0x95603142u, 0xA80018F2u, 0xEFA06222u, 0xD2C04B92u, 0x5090DC43u, 0x6DF0F5F3u, 0x2A508F23u, 0x1730A693u, 0xA5107A83u, 0x98705333u, 0xDFD029E3u, 0xE2B00053u, 0xC1C12F04u, 0xFCA106B4u, 0xBB017C64u, 0x866155D4u, 0x344189C4u, 0x0921A074u, 0x4E81DAA4u, 0x73E1F314u, 0xF1B164C5u, 0xCCD14D75u, 0x8B7137A5u, 0xB6111E15u, 0x0431C205u, 0x3951EBB5u, 0x7EF19165u, 0x4391B8D5u, 0xA121B886u, 0x9C419136u, 0xDBE1EBE6u, 0xE681C256u, 0x54A11E46u, 0x69C137F6u, 0x2E614D26u, 0x13016496u, 0x9151F347u, 0xAC31DAF7u, 0xEB91A027u, 0xD6F18997u, 0x64D15587u, 0x59B17C37u, 0x1E1106E7u, 0x23712F57u, 0x58F35849u, 0x659371F9u, 0x22330B29u, 0x1F532299u, 0xAD73FE89u, 0x9013D739u, 0xD7B3ADE9u, 0xEAD38459u, 0x68831388u, 0x55E33A38u, 0x124340E8u, 0x2F236958u, 0x9D03B548u, 0xA0639CF8u, 0xE7C3E628u, 0xDAA3CF98u, 0x3813CFCBu, 0x0573E67Bu, 0x42D39CABu, 0x7FB3B51Bu, 0xCD93690Bu, 0xF0F340BBu, 0xB7533A6Bu, 0x8A3313DBu, 0x0863840Au, 0x3503ADBAu, 0x72A3D76Au, 0x4FC3FEDAu, 0xFDE322CAu, 0xC0830B7Au, 0x872371AAu, 0xBA43581Au, 0x9932774Du, 0xA4525EFDu, 0xE3F2242Du, 0xDE920D9Du, 0x6CB2D18Du, 0x51D2F83Du, 0x167282EDu, 0x2B12AB5Du, 0xA9423C8Cu, 0x9422153Cu, 0xD3826FECu, 0xEEE2465Cu, 0x5CC29A4Cu, 0x61A2B3FCu, 0x2602C92Cu, 0x1B62E09Cu, 0xF9D2E0CFu, 0xC4B2C97Fu, 0x8312B3AFu, 0xBE729A1Fu, 0x0C52460Fu, 0x31326FBFu, 0x7692156Fu, 0x4BF23CDFu, 0xC9A2AB0Eu, 0xF4C282BEu, 0xB362F86Eu, 0x8E02D1DEu, 0x3C220DCEu, 0x0142247Eu, 0x46E25EAEu, 0x7B82771Eu, 0xB1E6B092u, 0x8C869922u, 0xCB26E3F2u, 0xF646CA42u, 0x44661652u, 0x79063FE2u, 0x3EA64532u, 0x03C66C82u, 0x8196FB53u, 0xBCF6D2E3u, 0xFB56A833u, 0xC6368183u, 0x74165D93u, 0x49767423u, 0x0ED60EF3u, 0x33B62743u, 0xD1062710u, 0xEC660EA0u, 0xABC67470u, 0x96A65DC0u, 0x248681D0u, 0x19E6A860u, 0x5E46D2B0u, 0x6326FB00u, 0xE1766CD1u, 0xDC164561u, 0x9BB63FB1u, 0xA6D61601u, 0x14F6CA11u, 0x2996E3A1u, 0x6E369971u, 0x5356B0C1u, 0x70279F96u, 0x4D47B626u, 0x0AE7CCF6u, 0x3787E546u, 0x85A73956u, 0xB8C710E6u, 0xFF676A36u, 0xC2074386u, 0x4057D457u, 0x7D37FDE7u, 0x3A978737u, 0x07F7AE87u, 0xB5D77297u, 0x88B75B27u, 0xCF1721F7u, 0xF2770847u, 0x10C70814u, 0x2DA721A4u, 0x6A075B74u, 0x576772C4u, 0xE547AED4u, 0xD8278764u, 0x9F87FDB4u, 0xA2E7D404u, 0x20B743D5u, 0x1DD76A65u, 0x5A7710B5u, 0x67173905u, 0xD537E515u, 0xE857CCA5u, 0xAFF7B675u, 0x92979FC5u, 0xE915E8DBu, 0xD475C16Bu, 0x93D5BBBBu, 0xAEB5920Bu, 0x1C954E1Bu, 0x21F567ABu, 0x66551D7Bu, 0x5B3534CBu, 0xD965A31Au, 0xE4058AAAu, 0xA3A5F07Au, 0x9EC5D9CAu, 0x2CE505DAu, 0x11852C6Au, 0x562556BAu, 0x6B457F0Au, 0x89F57F59u, 0xB49556E9u, 0xF3352C39u, 0xCE550589u, 0x7C75D999u, 0x4115F029u, 0x06B58AF9u, 0x3BD5A349u, 0xB9853498u, 0x84E51D28u, 0xC34567F8u, 0xFE254E48u, 0x4C059258u, 0x7165BBE8u, 0x36C5C138u, 0x0BA5E888u, 0x28D4C7DFu, 0x15B4EE6Fu, 0x521494BFu, 0x6F74BD0Fu, 0xDD54611Fu, 0xE03448AFu, 0xA794327Fu, 0x9AF41BCFu, 0x18A48C1Eu, 0x25C4A5AEu, 0x6264DF7Eu, 0x5F04F6CEu, 0xED242ADEu, 0xD044036Eu, 0x97E479BEu, 0xAA84500Eu, 0x4834505Du, 0x755479EDu, 0x32F4033Du, 0x0F942A8Du, 0xBDB4F69Du, 0x80D4DF2Du, 0xC774A5FDu, 0xFA148C4Du, 0x78441B9Cu, 0x4524322Cu, 0x028448FCu, 0x3FE4614Cu, 0x8DC4BD5Cu, 0xB0A494ECu, 0xF704EE3Cu, 0xCA64C78Cu }; private static readonly uint[] s_crcTable_5 = new uint[256] { 0x00000000u, 0xCB5CD3A5u, 0x4DC8A10Bu, 0x869472AEu, 0x9B914216u, 0x50CD91B3u, 0xD659E31Du, 0x1D0530B8u, 0xEC53826Du, 0x270F51C8u, 0xA19B2366u, 0x6AC7F0C3u, 0x77C2C07Bu, 0xBC9E13DEu, 0x3A0A6170u, 0xF156B2D5u, 0x03D6029Bu, 0xC88AD13Eu, 0x4E1EA390u, 0x85427035u, 0x9847408Du, 0x531B9328u, 0xD58FE186u, 0x1ED33223u, 0xEF8580F6u, 0x24D95353u, 0xA24D21FDu, 0x6911F258u, 0x7414C2E0u, 0xBF481145u, 0x39DC63EBu, 0xF280B04Eu, 0x07AC0536u, 0xCCF0D693u, 0x4A64A43Du, 0x81387798u, 0x9C3D4720u, 0x57619485u, 0xD1F5E62Bu, 0x1AA9358Eu, 0xEBFF875Bu, 0x20A354FEu, 0xA6372650u, 0x6D6BF5F5u, 0x706EC54Du, 0xBB3216E8u, 0x3DA66446u, 0xF6FAB7E3u, 0x047A07ADu, 0xCF26D408u, 0x49B2A6A6u, 0x82EE7503u, 0x9FEB45BBu, 0x54B7961Eu, 0xD223E4B0u, 0x197F3715u, 0xE82985C0u, 0x23755665u, 0xA5E124CBu, 0x6EBDF76Eu, 0x73B8C7D6u, 0xB8E41473u, 0x3E7066DDu, 0xF52CB578u, 0x0F580A6Cu, 0xC404D9C9u, 0x4290AB67u, 0x89CC78C2u, 0x94C9487Au, 0x5F959BDFu, 0xD901E971u, 0x125D3AD4u, 0xE30B8801u, 0x28575BA4u, 0xAEC3290Au, 0x659FFAAFu, 0x789ACA17u, 0xB3C619B2u, 0x35526B1Cu, 0xFE0EB8B9u, 0x0C8E08F7u, 0xC7D2DB52u, 0x4146A9FCu, 0x8A1A7A59u, 0x971F4AE1u, 0x5C439944u, 0xDAD7EBEAu, 0x118B384Fu, 0xE0DD8A9Au, 0x2B81593Fu, 0xAD152B91u, 0x6649F834u, 0x7B4CC88Cu, 0xB0101B29u, 0x36846987u, 0xFDD8BA22u, 0x08F40F5Au, 0xC3A8DCFFu, 0x453CAE51u, 0x8E607DF4u, 0x93654D4Cu, 0x58399EE9u, 0xDEADEC47u, 0x15F13FE2u, 0xE4A78D37u, 0x2FFB5E92u, 0xA96F2C3Cu, 0x6233FF99u, 0x7F36CF21u, 0xB46A1C84u, 0x32FE6E2Au, 0xF9A2BD8Fu, 0x0B220DC1u, 0xC07EDE64u, 0x46EAACCAu, 0x8DB67F6Fu, 0x90B34FD7u, 0x5BEF9C72u, 0xDD7BEEDCu, 0x16273D79u, 0xE7718FACu, 0x2C2D5C09u, 0xAAB92EA7u, 0x61E5FD02u, 0x7CE0CDBAu, 0xB7BC1E1Fu, 0x31286CB1u, 0xFA74BF14u, 0x1EB014D8u, 0xD5ECC77Du, 0x5378B5D3u, 0x98246676u, 0x852156CEu, 0x4E7D856Bu, 0xC8E9F7C5u, 0x03B52460u, 0xF2E396B5u, 0x39BF4510u, 0xBF2B37BEu, 0x7477E41Bu, 0x6972D4A3u, 0xA22E0706u, 0x24BA75A8u, 0xEFE6A60Du, 0x1D661643u, 0xD63AC5E6u, 0x50AEB748u, 0x9BF264EDu, 0x86F75455u, 0x4DAB87F0u, 0xCB3FF55Eu, 0x006326FBu, 0xF135942Eu, 0x3A69478Bu, 0xBCFD3525u, 0x77A1E680u, 0x6AA4D638u, 0xA1F8059Du, 0x276C7733u, 0xEC30A496u, 0x191C11EEu, 0xD240C24Bu, 0x54D4B0E5u, 0x9F886340u, 0x828D53F8u, 0x49D1805Du, 0xCF45F2F3u, 0x04192156u, 0xF54F9383u, 0x3E134026u, 0xB8873288u, 0x73DBE12Du, 0x6EDED195u, 0xA5820230u, 0x2316709Eu, 0xE84AA33Bu, 0x1ACA1375u, 0xD196C0D0u, 0x5702B27Eu, 0x9C5E61DBu, 0x815B5163u, 0x4A0782C6u, 0xCC93F068u, 0x07CF23CDu, 0xF6999118u, 0x3DC542BDu, 0xBB513013u, 0x700DE3B6u, 0x6D08D30Eu, 0xA65400ABu, 0x20C07205u, 0xEB9CA1A0u, 0x11E81EB4u, 0xDAB4CD11u, 0x5C20BFBFu, 0x977C6C1Au, 0x8A795CA2u, 0x41258F07u, 0xC7B1FDA9u, 0x0CED2E0Cu, 0xFDBB9CD9u, 0x36E74F7Cu, 0xB0733DD2u, 0x7B2FEE77u, 0x662ADECFu, 0xAD760D6Au, 0x2BE27FC4u, 0xE0BEAC61u, 0x123E1C2Fu, 0xD962CF8Au, 0x5FF6BD24u, 0x94AA6E81u, 0x89AF5E39u, 0x42F38D9Cu, 0xC467FF32u, 0x0F3B2C97u, 0xFE6D9E42u, 0x35314DE7u, 0xB3A53F49u, 0x78F9ECECu, 0x65FCDC54u, 0xAEA00FF1u, 0x28347D5Fu, 0xE368AEFAu, 0x16441B82u, 0xDD18C827u, 0x5B8CBA89u, 0x90D0692Cu, 0x8DD55994u, 0x46898A31u, 0xC01DF89Fu, 0x0B412B3Au, 0xFA1799EFu, 0x314B4A4Au, 0xB7DF38E4u, 0x7C83EB41u, 0x6186DBF9u, 0xAADA085Cu, 0x2C4E7AF2u, 0xE712A957u, 0x15921919u, 0xDECECABCu, 0x585AB812u, 0x93066BB7u, 0x8E035B0Fu, 0x455F88AAu, 0xC3CBFA04u, 0x089729A1u, 0xF9C19B74u, 0x329D48D1u, 0xB4093A7Fu, 0x7F55E9DAu, 0x6250D962u, 0xA90C0AC7u, 0x2F987869u, 0xE4C4ABCCu }; private static readonly uint[] s_crcTable_6 = new uint[256] { 0x00000000u, 0xA6770BB4u, 0x979F1129u, 0x31E81A9Du, 0xF44F2413u, 0x52382FA7u, 0x63D0353Au, 0xC5A73E8Eu, 0x33EF4E67u, 0x959845D3u, 0xA4705F4Eu, 0x020754FAu, 0xC7A06A74u, 0x61D761C0u, 0x503F7B5Du, 0xF64870E9u, 0x67DE9CCEu, 0xC1A9977Au, 0xF0418DE7u, 0x56368653u, 0x9391B8DDu, 0x35E6B369u, 0x040EA9F4u, 0xA279A240u, 0x5431D2A9u, 0xF246D91Du, 0xC3AEC380u, 0x65D9C834u, 0xA07EF6BAu, 0x0609FD0Eu, 0x37E1E793u, 0x9196EC27u, 0xCFBD399Cu, 0x69CA3228u, 0x582228B5u, 0xFE552301u, 0x3BF21D8Fu, 0x9D85163Bu, 0xAC6D0CA6u, 0x0A1A0712u, 0xFC5277FBu, 0x5A257C4Fu, 0x6BCD66D2u, 0xCDBA6D66u, 0x081D53E8u, 0xAE6A585Cu, 0x9F8242C1u, 0x39F54975u, 0xA863A552u, 0x0E14AEE6u, 0x3FFCB47Bu, 0x998BBFCFu, 0x5C2C8141u, 0xFA5B8AF5u, 0xCBB39068u, 0x6DC49BDCu, 0x9B8CEB35u, 0x3DFBE081u, 0x0C13FA1Cu, 0xAA64F1A8u, 0x6FC3CF26u, 0xC9B4C492u, 0xF85CDE0Fu, 0x5E2BD5BBu, 0x440B7579u, 0xE27C7ECDu, 0xD3946450u, 0x75E36FE4u, 0xB044516Au, 0x16335ADEu, 0x27DB4043u, 0x81AC4BF7u, 0x77E43B1Eu, 0xD19330AAu, 0xE07B2A37u, 0x460C2183u, 0x83AB1F0Du, 0x25DC14B9u, 0x14340E24u, 0xB2430590u, 0x23D5E9B7u, 0x85A2E203u, 0xB44AF89Eu, 0x123DF32Au, 0xD79ACDA4u, 0x71EDC610u, 0x4005DC8Du, 0xE672D739u, 0x103AA7D0u, 0xB64DAC64u, 0x87A5B6F9u, 0x21D2BD4Du, 0xE47583C3u, 0x42028877u, 0x73EA92EAu, 0xD59D995Eu, 0x8BB64CE5u, 0x2DC14751u, 0x1C295DCCu, 0xBA5E5678u, 0x7FF968F6u, 0xD98E6342u, 0xE86679DFu, 0x4E11726Bu, 0xB8590282u, 0x1E2E0936u, 0x2FC613ABu, 0x89B1181Fu, 0x4C162691u, 0xEA612D25u, 0xDB8937B8u, 0x7DFE3C0Cu, 0xEC68D02Bu, 0x4A1FDB9Fu, 0x7BF7C102u, 0xDD80CAB6u, 0x1827F438u, 0xBE50FF8Cu, 0x8FB8E511u, 0x29CFEEA5u, 0xDF879E4Cu, 0x79F095F8u, 0x48188F65u, 0xEE6F84D1u, 0x2BC8BA5Fu, 0x8DBFB1EBu, 0xBC57AB76u, 0x1A20A0C2u, 0x8816EAF2u, 0x2E61E146u, 0x1F89FBDBu, 0xB9FEF06Fu, 0x7C59CEE1u, 0xDA2EC555u, 0xEBC6DFC8u, 0x4DB1D47Cu, 0xBBF9A495u, 0x1D8EAF21u, 0x2C66B5BCu, 0x8A11BE08u, 0x4FB68086u, 0xE9C18B32u, 0xD82991AFu, 0x7E5E9A1Bu, 0xEFC8763Cu, 0x49BF7D88u, 0x78576715u, 0xDE206CA1u, 0x1B87522Fu, 0xBDF0599Bu, 0x8C184306u, 0x2A6F48B2u, 0xDC27385Bu, 0x7A5033EFu, 0x4BB82972u, 0xEDCF22C6u, 0x28681C48u, 0x8E1F17FCu, 0xBFF70D61u, 0x198006D5u, 0x47ABD36Eu, 0xE1DCD8DAu, 0xD034C247u, 0x7643C9F3u, 0xB3E4F77Du, 0x1593FCC9u, 0x247BE654u, 0x820CEDE0u, 0x74449D09u, 0xD23396BDu, 0xE3DB8C20u, 0x45AC8794u, 0x800BB91Au, 0x267CB2AEu, 0x1794A833u, 0xB1E3A387u, 0x20754FA0u, 0x86024414u, 0xB7EA5E89u, 0x119D553Du, 0xD43A6BB3u, 0x724D6007u, 0x43A57A9Au, 0xE5D2712Eu, 0x139A01C7u, 0xB5ED0A73u, 0x840510EEu, 0x22721B5Au, 0xE7D525D4u, 0x41A22E60u, 0x704A34FDu, 0xD63D3F49u, 0xCC1D9F8Bu, 0x6A6A943Fu, 0x5B828EA2u, 0xFDF58516u, 0x3852BB98u, 0x9E25B02Cu, 0xAFCDAAB1u, 0x09BAA105u, 0xFFF2D1ECu, 0x5985DA58u, 0x686DC0C5u, 0xCE1ACB71u, 0x0BBDF5FFu, 0xADCAFE4Bu, 0x9C22E4D6u, 0x3A55EF62u, 0xABC30345u, 0x0DB408F1u, 0x3C5C126Cu, 0x9A2B19D8u, 0x5F8C2756u, 0xF9FB2CE2u, 0xC813367Fu, 0x6E643DCBu, 0x982C4D22u, 0x3E5B4696u, 0x0FB35C0Bu, 0xA9C457BFu, 0x6C636931u, 0xCA146285u, 0xFBFC7818u, 0x5D8B73ACu, 0x03A0A617u, 0xA5D7ADA3u, 0x943FB73Eu, 0x3248BC8Au, 0xF7EF8204u, 0x519889B0u, 0x6070932Du, 0xC6079899u, 0x304FE870u, 0x9638E3C4u, 0xA7D0F959u, 0x01A7F2EDu, 0xC400CC63u, 0x6277C7D7u, 0x539FDD4Au, 0xF5E8D6FEu, 0x647E3AD9u, 0xC209316Du, 0xF3E12BF0u, 0x55962044u, 0x90311ECAu, 0x3646157Eu, 0x07AE0FE3u, 0xA1D90457u, 0x579174BEu, 0xF1E67F0Au, 0xC00E6597u, 0x66796E23u, 0xA3DE50ADu, 0x05A95B19u, 0x34414184u, 0x92364A30u }; private static readonly uint[] s_crcTable_7 = new uint[256] { 0x00000000u, 0xCCAA009Eu, 0x4225077Du, 0x8E8F07E3u, 0x844A0EFAu, 0x48E00E64u, 0xC66F0987u, 0x0AC50919u, 0xD3E51BB5u, 0x1F4F1B2Bu, 0x91C01CC8u, 0x5D6A1C56u, 0x57AF154Fu, 0x9B0515D1u, 0x158A1232u, 0xD92012ACu, 0x7CBB312Bu, 0xB01131B5u, 0x3E9E3656u, 0xF23436C8u, 0xF8F13FD1u, 0x345B3F4Fu, 0xBAD438ACu, 0x767E3832u, 0xAF5E2A9Eu, 0x63F42A00u, 0xED7B2DE3u, 0x21D12D7Du, 0x2B142464u, 0xE7BE24FAu, 0x69312319u, 0xA59B2387u, 0xF9766256u, 0x35DC62C8u, 0xBB53652Bu, 0x77F965B5u, 0x7D3C6CACu, 0xB1966C32u, 0x3F196BD1u, 0xF3B36B4Fu, 0x2A9379E3u, 0xE639797Du, 0x68B67E9Eu, 0xA41C7E00u, 0xAED97719u, 0x62737787u, 0xECFC7064u, 0x205670FAu, 0x85CD537Du, 0x496753E3u, 0xC7E85400u, 0x0B42549Eu, 0x01875D87u, 0xCD2D5D19u, 0x43A25AFAu, 0x8F085A64u, 0x562848C8u, 0x9A824856u, 0x140D4FB5u, 0xD8A74F2Bu, 0xD2624632u, 0x1EC846ACu, 0x9047414Fu, 0x5CED41D1u, 0x299DC2EDu, 0xE537C273u, 0x6BB8C590u, 0xA712C50Eu, 0xADD7CC17u, 0x617DCC89u, 0xEFF2CB6Au, 0x2358CBF4u, 0xFA78D958u, 0x36D2D9C6u, 0xB85DDE25u, 0x74F7DEBBu, 0x7E32D7A2u, 0xB298D73Cu, 0x3C17D0DFu, 0xF0BDD041u, 0x5526F3C6u, 0x998CF358u, 0x1703F4BBu, 0xDBA9F425u, 0xD16CFD3Cu, 0x1DC6FDA2u, 0x9349FA41u, 0x5FE3FADFu, 0x86C3E873u, 0x4A69E8EDu, 0xC4E6EF0Eu, 0x084CEF90u, 0x0289E689u, 0xCE23E617u, 0x40ACE1F4u, 0x8C06E16Au, 0xD0EBA0BBu, 0x1C41A025u, 0x92CEA7C6u, 0x5E64A758u, 0x54A1AE41u, 0x980BAEDFu, 0x1684A93Cu, 0xDA2EA9A2u, 0x030EBB0Eu, 0xCFA4BB90u, 0x412BBC73u, 0x8D81BCEDu, 0x8744B5F4u, 0x4BEEB56Au, 0xC561B289u, 0x09CBB217u, 0xAC509190u, 0x60FA910Eu, 0xEE7596EDu, 0x22DF9673u, 0x281A9F6Au, 0xE4B09FF4u, 0x6A3F9817u, 0xA6959889u, 0x7FB58A25u, 0xB31F8ABBu, 0x3D908D58u, 0xF13A8DC6u, 0xFBFF84DFu, 0x37558441u, 0xB9DA83A2u, 0x7570833Cu, 0x533B85DAu, 0x9F918544u, 0x111E82A7u, 0xDDB48239u, 0xD7718B20u, 0x1BDB8BBEu, 0x95548C5Du, 0x59FE8CC3u, 0x80DE9E6Fu, 0x4C749EF1u, 0xC2FB9912u, 0x0E51998Cu, 0x04949095u, 0xC83E900Bu, 0x46B197E8u, 0x8A1B9776u, 0x2F80B4F1u, 0xE32AB46Fu, 0x6DA5B38Cu, 0xA10FB312u, 0xABCABA0Bu, 0x6760BA95u, 0xE9EFBD76u, 0x2545BDE8u, 0xFC65AF44u, 0x30CFAFDAu, 0xBE40A839u, 0x72EAA8A7u, 0x782FA1BEu, 0xB485A120u, 0x3A0AA6C3u, 0xF6A0A65Du, 0xAA4DE78Cu, 0x66E7E712u, 0xE868E0F1u, 0x24C2E06Fu, 0x2E07E976u, 0xE2ADE9E8u, 0x6C22EE0Bu, 0xA088EE95u, 0x79A8FC39u, 0xB502FCA7u, 0x3B8DFB44u, 0xF727FBDAu, 0xFDE2F2C3u, 0x3148F25Du, 0xBFC7F5BEu, 0x736DF520u, 0xD6F6D6A7u, 0x1A5CD639u, 0x94D3D1DAu, 0x5879D144u, 0x52BCD85Du, 0x9E16D8C3u, 0x1099DF20u, 0xDC33DFBEu, 0x0513CD12u, 0xC9B9CD8Cu, 0x4736CA6Fu, 0x8B9CCAF1u, 0x8159C3E8u, 0x4DF3C376u, 0xC37CC495u, 0x0FD6C40Bu, 0x7AA64737u, 0xB60C47A9u, 0x3883404Au, 0xF42940D4u, 0xFEEC49CDu, 0x32464953u, 0xBCC94EB0u, 0x70634E2Eu, 0xA9435C82u, 0x65E95C1Cu, 0xEB665BFFu, 0x27CC5B61u, 0x2D095278u, 0xE1A352E6u, 0x6F2C5505u, 0xA386559Bu, 0x061D761Cu, 0xCAB77682u, 0x44387161u, 0x889271FFu, 0x825778E6u, 0x4EFD7878u, 0xC0727F9Bu, 0x0CD87F05u, 0xD5F86DA9u, 0x19526D37u, 0x97DD6AD4u, 0x5B776A4Au, 0x51B26353u, 0x9D1863CDu, 0x1397642Eu, 0xDF3D64B0u, 0x83D02561u, 0x4F7A25FFu, 0xC1F5221Cu, 0x0D5F2282u, 0x079A2B9Bu, 0xCB302B05u, 0x45BF2CE6u, 0x89152C78u, 0x50353ED4u, 0x9C9F3E4Au, 0x121039A9u, 0xDEBA3937u, 0xD47F302Eu, 0x18D530B0u, 0x965A3753u, 0x5AF037CDu, 0xFF6B144Au, 0x33C114D4u, 0xBD4E1337u, 0x71E413A9u, 0x7B211AB0u, 0xB78B1A2Eu, 0x39041DCDu, 0xF5AE1D53u, 0x2C8E0FFFu, 0xE0240F61u, 0x6EAB0882u, 0xA201081Cu, 0xA8C40105u, 0x646E019Bu, 0xEAE10678u, 0x264B06E6u }; private static uint ManagedCrc32(uint crc32, byte[] buffer, int offset, int length) { Debug.Assert(BitConverter.IsLittleEndian, "ManagedCrc32 Expects Little Endian"); uint term1, term2, term3 = 0; crc32 ^= 0xFFFFFFFFU; int runningLength = (length / 8) * 8; int endBytes = length - runningLength; for (int i = 0; i < runningLength / 8; i++) { crc32 ^= (uint)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24); offset += 4; term1 = s_crcTable_7[crc32 & 0x000000FF] ^ s_crcTable_6[(crc32 >> 8) & 0x000000FF]; term2 = crc32 >> 16; crc32 = term1 ^ s_crcTable_5[term2 & 0x000000FF] ^ s_crcTable_4[(term2 >> 8) & 0x000000FF]; term3 = (uint)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16 | buffer[offset + 3] << 24); offset += 4; term1 = s_crcTable_3[term3 & 0x000000FF] ^ s_crcTable_2[(term3 >> 8) & 0x000000FF]; term2 = term3 >> 16; crc32 ^= term1 ^ s_crcTable_1[term2 & 0x000000FF] ^ s_crcTable_0[(term2 >> 8) & 0x000000FF]; } for (int i = 0; i < endBytes; i++) { crc32 = s_crcTable_0[(crc32 ^ buffer[offset++]) & 0x000000FF] ^ (crc32 >> 8); } crc32 ^= 0xFFFFFFFFU; return crc32; } #endif } }
using System; using System.Collections.Generic; using Orleans.Runtime; using Orleans.Streams; namespace Orleans.Providers.Streams.Common { /// <summary> /// CachedMessageBlock is a block of tightly packed structures containing tracking data for cached messages. This data is /// tightly packed to reduced GC pressure. The tracking data is used by the queue cache to walk the cache serving ordered /// queue messages by stream. /// </summary> public class CachedMessageBlock : PooledResource<CachedMessageBlock> { private const int OneKb = 1024; private const int DefaultCachedMessagesPerBlock = 16 * OneKb; // 16kb private readonly CachedMessage[] cachedMessages; private readonly int blockSize; private int writeIndex; private int readIndex; /// <summary> /// Linked list node, so this message block can be kept in a linked list. /// </summary> public LinkedListNode<CachedMessageBlock> Node { get; private set; } /// <summary> /// Gets a value indicating whether more messages can be added to the block. /// </summary> public bool HasCapacity => writeIndex < blockSize; /// <summary> /// Gets a value indicating whether this block is empty. /// </summary> public bool IsEmpty => readIndex >= writeIndex; /// <summary> /// Gets the index of most recent message added to the block. /// </summary> public int NewestMessageIndex => writeIndex - 1; /// <summary> /// Gets the index of the oldest message in this block. /// </summary> public int OldestMessageIndex => readIndex; /// <summary> /// Gets the oldest message in the block. /// </summary> public CachedMessage OldestMessage => cachedMessages[OldestMessageIndex]; /// <summary> /// Gets the newest message in this block. /// </summary> public CachedMessage NewestMessage => cachedMessages[NewestMessageIndex]; /// <summary> /// Gets the number of messages in this block. /// </summary> public int ItemCount { get { int count = writeIndex - readIndex; return count >= 0 ? count : 0; } } /// <summary> /// Block of cached messages. /// </summary> /// <param name="blockSize">The block size, expressed as a number of messages.</param> public CachedMessageBlock(int blockSize = DefaultCachedMessagesPerBlock) { this.blockSize = blockSize; cachedMessages = new CachedMessage[blockSize]; writeIndex = 0; readIndex = 0; Node = new LinkedListNode<CachedMessageBlock>(this); } /// <summary> /// Removes a message from the start of the block (oldest data). /// </summary> /// <returns><see langword="true"/> if there are more items remaining; otherwise <see langword="false"/>.</returns> public bool Remove() { if (readIndex < writeIndex) { readIndex++; return true; } return false; } /// <summary> /// Add a message from the queue to the block. /// Converts the queue message to a cached message and stores it at the end of the block. /// </summary> /// <param name="message"> /// The message to add to this block. /// </param> public void Add(CachedMessage message) { if (!HasCapacity) { throw new InvalidOperationException("Block is full"); } int index = writeIndex++; cachedMessages[index] = message; } /// <summary> /// Access the cached message at the provided index. /// </summary> /// <param name="index">The index to access.</param> /// <returns>The message at the specified index.</returns> public CachedMessage this[int index] { get { if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException("index"); } return cachedMessages[index]; } } /// <summary> /// Gets the sequence token of the cached message a the provided index /// </summary> /// <param name="index">The index of the message to access.</param> /// <param name="dataAdapter">The data adapter.</param> /// <returns>The sequence token.</returns> public StreamSequenceToken GetSequenceToken(int index, ICacheDataAdapter dataAdapter) { if (index >= writeIndex || index < readIndex) { throw new ArgumentOutOfRangeException(nameof(index)); } return dataAdapter.GetSequenceToken(ref cachedMessages[index]); } /// <summary> /// Gets the sequence token of the newest message in this block /// </summary> /// <param name="dataAdapter">The data adapter.</param> /// <returns>The sequence token of the newest message in this block.</returns> public StreamSequenceToken GetNewestSequenceToken(ICacheDataAdapter dataAdapter) { return GetSequenceToken(NewestMessageIndex, dataAdapter); } /// <summary> /// Gets the sequence token of the oldest message in this block /// </summary> /// <param name="dataAdapter">The data adapter.</param> /// <returns>The sequence token of the oldest message in this block.</returns> public StreamSequenceToken GetOldestSequenceToken(ICacheDataAdapter dataAdapter) { return GetSequenceToken(OldestMessageIndex, dataAdapter); } /// <summary> /// Gets the index of the first message in this block that has a sequence token at or before the provided token /// </summary> /// <param name="token">The sequence token.</param> /// <returns>The index of the first message in this block that has a sequence token equal to or before the provided token.</returns> public int GetIndexOfFirstMessageLessThanOrEqualTo(StreamSequenceToken token) { for (int i = writeIndex - 1; i >= readIndex; i--) { if (cachedMessages[i].Compare(token) <= 0) { return i; } } throw new ArgumentOutOfRangeException("token"); } /// <summary> /// Tries to find the first message in the block that is part of the provided stream. /// </summary> /// <param name="streamId">The stream identifier.</param> /// <param name="dataAdapter">The data adapter.</param> /// <param name="index">The index.</param> /// <returns><see langword="true" /> if the message was found, <see langword="false" /> otherwise.</returns> public bool TryFindFirstMessage(StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { return TryFindNextMessage(readIndex, streamId, dataAdapter, out index); } /// <summary> /// Tries to get the next message from the provided stream, starting at the start index. /// </summary> /// <param name="start">The start index.</param> /// <param name="streamId">The stream identifier.</param> /// <param name="dataAdapter">The data adapter.</param> /// <param name="index">The index.</param> /// <returns><see langword="true" /> if the message was found, <see langword="false" /> otherwise.</returns> public bool TryFindNextMessage(int start, StreamId streamId, ICacheDataAdapter dataAdapter, out int index) { if (start < readIndex) { throw new ArgumentOutOfRangeException("start"); } for (int i = start; i < writeIndex; i++) { if (cachedMessages[i].CompareStreamId(streamId)) { index = i; return true; } } index = writeIndex - 1; return false; } /// <inheritdoc/> public override void OnResetState() { writeIndex = 0; readIndex = 0; } } }
// 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.Linq; using Xunit; namespace Test { public class UnionTests { private const int DuplicateFactor = 8; // Get two ranges, with the right starting where the left ends public static IEnumerable<object[]> UnionUnorderedData(object[] leftCounts, object[] rightCounts) { foreach (object[] parms in UnorderedSources.BinaryRanges(leftCounts.Cast<int>(), (l, r) => l, rightCounts.Cast<int>())) { yield return parms.Take(4).ToArray(); } } // Union returns only the ordered portion ordered. See Issue #1331 // Get two ranges, both ordered. public static IEnumerable<object[]> UnionData(object[] leftCounts, object[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, with only the left being ordered. public static IEnumerable<object[]> UnionFirstOrderedData(object[] leftCounts, object[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { ((Labeled<ParallelQuery<int>>)parms[0]).Order(), parms[1], parms[2], parms[3] }; } } // Get two ranges, with only the right being ordered. public static IEnumerable<object[]> UnionSecondOrderedData(object[] leftCounts, object[] rightCounts) { foreach (object[] parms in UnionUnorderedData(leftCounts, rightCounts)) { yield return new object[] { parms[0], parms[1], ((Labeled<ParallelQuery<int>>)parms[2]).Order(), parms[3] }; } } // Get two ranges, both sourced from arrays, with duplicate items in each array. // Used in distinctness tests, in contrast to relying on a Select predicate to generate duplicate items. public static IEnumerable<object[]> UnionSourceMultipleData(object[] counts) { foreach (int leftCount in counts.Cast<int>()) { ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel(); foreach (int rightCount in new int[] { 0, 1, Math.Max(DuplicateFactor, leftCount / 2), Math.Max(DuplicateFactor, leftCount) }) { int rightStart = leftCount - Math.Min(leftCount, rightCount) / 2; ParallelQuery<int> right = Enumerable.Range(0, rightCount * DuplicateFactor).Select(x => x % rightCount + rightStart).ToArray().AsParallel(); yield return new object[] { left, leftCount, right, rightCount, Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2 }; } } } // // Union // [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); foreach (int i in leftQuery.Union(rightQuery)) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { Assert.Equal(seen++, i); } Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; foreach (int i in leftQuery.Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery)) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seen = new IntegerRangeSet(0, leftCount + rightCount); Assert.All(leftQuery.Union(rightQuery).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(leftCount + rightCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, rightCount); int seen = 0; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x < leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; Assert.All(leftQuery.Union(rightQuery).ToList(), x => { if (x >= leftCount) Assert.Equal(seen++, x); else seenUnordered.Add(x); }); Assert.Equal(leftCount + rightCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { Assert.Equal(seen++, i); } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionFirstOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_FirstOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, expectedCount - leftCount); int seen = 0; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i < leftCount) { Assert.Equal(seen++, i); } else { Assert.Equal(leftCount, seen); seenUnordered.Add(i); } } seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionFirstOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_FirstOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_FirstOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSecondOrderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_SecondOrdered_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2))) { if (i >= leftCount) { seenUnordered.AssertComplete(); Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionSecondOrderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_SecondOrdered_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_SecondOrdered_Distinct(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionUnorderedData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Unordered_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; IntegerRangeSet seen = new IntegerRangeSet(0, expectedCount); Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionUnorderedData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Unordered_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Unordered_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionData", new int[] { 0, 1, 2, 16 }, new int[] { 0, 1, 8 })] public static void Union_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; leftCount = Math.Min(DuplicateFactor, leftCount); rightCount = Math.Min(DuplicateFactor, rightCount); int offset = leftCount - Math.Min(leftCount, rightCount) / 2; int expectedCount = Math.Max(leftCount, rightCount) + (Math.Min(leftCount, rightCount) + 1) / 2; int seen = 0; Assert.All(leftQuery.Select(x => x % DuplicateFactor).Union(rightQuery.Select(x => (x - leftCount) % DuplicateFactor + offset), new ModularCongruenceComparer(DuplicateFactor + DuplicateFactor / 2)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(expectedCount, seen); } [Theory] [OuterLoop] [MemberData("UnionData", new int[] { 512, 1024 * 8 }, new int[] { 0, 1, 1024, 1024 * 16 })] public static void Union_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { Union_Distinct_NotPipelined(left, leftCount, right, rightCount); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { // The difference between this test and the previous, is that it's not possible to // get non-unique results from ParallelEnumerable.Range()... // Those tests either need modification of source (via .Select(x => x / DuplicateFactor) or similar, // or via a comparator that considers some elements equal. IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(leftQuery.Union(rightQuery), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { int seen = 0; Assert.All(leftQuery.AsOrdered().Union(rightQuery.AsOrdered()), x => Assert.Equal(seen++, x)); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_FirstOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(leftCount, count - leftCount); int seen = 0; foreach (int i in leftQuery.AsOrdered().Union(rightQuery)) { if (i < leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(leftCount, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_FirstOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_FirstOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Theory] [MemberData("UnionSourceMultipleData", (object)(new int[] { 0, 1, 2, 16 }))] public static void Union_SecondOrdered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { IntegerRangeSet seenUnordered = new IntegerRangeSet(0, leftCount); int seen = leftCount; foreach (int i in leftQuery.Union(rightQuery.AsOrdered())) { if (i >= leftCount) { Assert.Equal(seen++, i); } else { seenUnordered.Add(i); } } Assert.Equal(count, seen); seenUnordered.AssertComplete(); } [Theory] [OuterLoop] [MemberData("UnionSourceMultipleData", (object)(new int[] { 512, 1024 * 8 }))] public static void Union_SecondOrdered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count) { Union_SecondOrdered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count); } [Fact] public static void Union_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Union(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] public static void Union_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Union(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Range(0, 1).Union(null, EqualityComparer<int>.Default)); } } }
#nullable enable using System; using Avalonia.Controls.Diagnostics; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; namespace Avalonia.Controls { /// <summary> /// A control which pops up a hint when a control is hovered. /// </summary> /// <remarks> /// You will probably not want to create a <see cref="ToolTip"/> control directly: if added to /// the tree it will act as a simple <see cref="ContentControl"/> styled to look like a tooltip. /// To add a tooltip to a control, use the <see cref="TipProperty"/> attached property, /// assigning the content that you want displayed. /// </remarks> [PseudoClasses(":open")] public class ToolTip : ContentControl, IPopupHostProvider { /// <summary> /// Defines the ToolTip.Tip attached property. /// </summary> public static readonly AttachedProperty<object?> TipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, object?>("Tip"); /// <summary> /// Defines the ToolTip.IsOpen attached property. /// </summary> public static readonly AttachedProperty<bool> IsOpenProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, bool>("IsOpen"); /// <summary> /// Defines the ToolTip.Placement property. /// </summary> public static readonly AttachedProperty<PlacementMode> PlacementProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, PlacementMode>("Placement", defaultValue: PlacementMode.Pointer); /// <summary> /// Defines the ToolTip.HorizontalOffset property. /// </summary> public static readonly AttachedProperty<double> HorizontalOffsetProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, double>("HorizontalOffset"); /// <summary> /// Defines the ToolTip.VerticalOffset property. /// </summary> public static readonly AttachedProperty<double> VerticalOffsetProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, double>("VerticalOffset", 20); /// <summary> /// Defines the ToolTip.ShowDelay property. /// </summary> public static readonly AttachedProperty<int> ShowDelayProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, int>("ShowDelay", 400); /// <summary> /// Stores the current <see cref="ToolTip"/> instance in the control. /// </summary> internal static readonly AttachedProperty<ToolTip?> ToolTipProperty = AvaloniaProperty.RegisterAttached<ToolTip, Control, ToolTip?>("ToolTip"); private IPopupHost? _popupHost; private Action<IPopupHost?>? _popupHostChangedHandler; /// <summary> /// Initializes static members of the <see cref="ToolTip"/> class. /// </summary> static ToolTip() { TipProperty.Changed.Subscribe(ToolTipService.Instance.TipChanged); IsOpenProperty.Changed.Subscribe(ToolTipService.Instance.TipOpenChanged); IsOpenProperty.Changed.Subscribe(IsOpenChanged); HorizontalOffsetProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); VerticalOffsetProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); PlacementProperty.Changed.Subscribe(RecalculatePositionOnPropertyChanged); } /// <summary> /// Gets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// The content to be displayed in the control's tooltip. /// </returns> public static object? GetTip(Control element) { return element.GetValue(TipProperty); } /// <summary> /// Sets the value of the ToolTip.Tip attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">The content to be displayed in the control's tooltip.</param> public static void SetTip(Control element, object? value) { element.SetValue(TipProperty, value); } /// <summary> /// Gets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating whether the tool tip is visible. /// </returns> public static bool GetIsOpen(Control element) { return element.GetValue(IsOpenProperty); } /// <summary> /// Sets the value of the ToolTip.IsOpen attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating whether the tool tip is visible.</param> public static void SetIsOpen(Control element, bool value) { element.SetValue(IsOpenProperty, value); } /// <summary> /// Gets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static PlacementMode GetPlacement(Control element) { return element.GetValue(PlacementProperty); } /// <summary> /// Sets the value of the ToolTip.Placement attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetPlacement(Control element, PlacementMode value) { element.SetValue(PlacementProperty, value); } /// <summary> /// Gets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetHorizontalOffset(Control element) { return element.GetValue(HorizontalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.HorizontalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetHorizontalOffset(Control element, double value) { element.SetValue(HorizontalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating how the tool tip is positioned. /// </returns> public static double GetVerticalOffset(Control element) { return element.GetValue(VerticalOffsetProperty); } /// <summary> /// Sets the value of the ToolTip.VerticalOffset attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating how the tool tip is positioned.</param> public static void SetVerticalOffset(Control element, double value) { element.SetValue(VerticalOffsetProperty, value); } /// <summary> /// Gets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <returns> /// A value indicating the time, in milliseconds, before a tool tip opens. /// </returns> public static int GetShowDelay(Control element) { return element.GetValue(ShowDelayProperty); } /// <summary> /// Sets the value of the ToolTip.ShowDelay attached property. /// </summary> /// <param name="element">The control to get the property from.</param> /// <param name="value">A value indicating the time, in milliseconds, before a tool tip opens.</param> public static void SetShowDelay(Control element, int value) { element.SetValue(ShowDelayProperty, value); } private static void IsOpenChanged(AvaloniaPropertyChangedEventArgs e) { var control = (Control)e.Sender; var newValue = (bool)e.NewValue!; ToolTip? toolTip; if (newValue) { var tip = GetTip(control); if (tip == null) return; toolTip = control.GetValue(ToolTipProperty); if (toolTip == null || (tip != toolTip && tip != toolTip.Content)) { toolTip?.Close(); toolTip = tip as ToolTip ?? new ToolTip { Content = tip }; control.SetValue(ToolTipProperty, toolTip); } toolTip.Open(control); } else { toolTip = control.GetValue(ToolTipProperty); toolTip?.Close(); } toolTip?.UpdatePseudoClasses(newValue); } private static void RecalculatePositionOnPropertyChanged(AvaloniaPropertyChangedEventArgs args) { var control = (Control)args.Sender; var tooltip = control.GetValue(ToolTipProperty); if (tooltip == null) { return; } tooltip.RecalculatePosition(control); } IPopupHost? IPopupHostProvider.PopupHost => _popupHost; event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged { add => _popupHostChangedHandler += value; remove => _popupHostChangedHandler -= value; } internal void RecalculatePosition(Control control) { _popupHost?.ConfigurePosition(control, GetPlacement(control), new Point(GetHorizontalOffset(control), GetVerticalOffset(control))); } private void Open(Control control) { Close(); _popupHost = OverlayPopupHost.CreatePopupHost(control, null); _popupHost.SetChild(this); ((ISetLogicalParent)_popupHost).SetParent(control); _popupHost.ConfigurePosition(control, GetPlacement(control), new Point(GetHorizontalOffset(control), GetVerticalOffset(control))); WindowManagerAddShadowHintChanged(_popupHost, false); _popupHost.Show(); _popupHostChangedHandler?.Invoke(_popupHost); } private void Close() { if (_popupHost != null) { _popupHost.SetChild(null); _popupHost.Dispose(); _popupHost = null; _popupHostChangedHandler?.Invoke(null); } } private void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint) { if (host is PopupRoot pr) { pr.PlatformImpl.SetWindowManagerAddShadowHint(hint); } } private void UpdatePseudoClasses(bool newValue) { PseudoClasses.Set(":open", newValue); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; // for fxcop using System.IO; using System.Linq; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Runtime.Serialization; using System.Threading; using Microsoft.PowerShell.Commands; using Dbg = System.Management.Automation.Diagnostics; #if LEGACYTELEMETRY using Microsoft.PowerShell.Telemetry.Internal; #endif #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings namespace System.Management.Automation.Runspaces { /// <summary> /// Runspace class for local runspace. /// </summary> internal sealed partial class LocalRunspace : RunspaceBase { #region constructors /// <summary> /// Construct an instance of an Runspace using a custom implementation /// of PSHost. /// </summary> /// <param name="host"> /// The explicit PSHost implementation /// </param> /// <param name="initialSessionState"> /// configuration information for this minshell. /// </param> /// <param name="suppressClone"> /// If true, don't make a copy of the initial session state object /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] internal LocalRunspace(PSHost host, InitialSessionState initialSessionState, bool suppressClone) : base(host, initialSessionState, suppressClone) { } /// <summary> /// Construct an instance of an Runspace using a custom implementation /// of PSHost. /// </summary> /// <param name="host"> /// The explicit PSHost implementation /// </param> /// <param name="initialSessionState"> /// configuration information for this minshell. /// </param> [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] internal LocalRunspace(PSHost host, InitialSessionState initialSessionState) : base(host, initialSessionState) { } #endregion constructors /// <summary> /// Private data to be used by applications built on top of PowerShell. /// /// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>. /// /// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool. /// </summary> public override PSPrimitiveDictionary GetApplicationPrivateData() { // if we didn't get applicationPrivateData from a runspace pool, // then we create a new one if (_applicationPrivateData == null) { lock (this.SyncRoot) { if (_applicationPrivateData == null) { _applicationPrivateData = new PSPrimitiveDictionary(); } } } return _applicationPrivateData; } /// <summary> /// A method that runspace pools can use to propagate application private data into runspaces. /// </summary> /// <param name="applicationPrivateData"></param> internal override void SetApplicationPrivateData(PSPrimitiveDictionary applicationPrivateData) { _applicationPrivateData = applicationPrivateData; } private PSPrimitiveDictionary _applicationPrivateData; /// <summary> /// Gets the event manager. /// </summary> public override PSEventManager Events { get { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; if (context == null) { return null; } return context.Events; } } /// <summary> /// This property determines whether a new thread is create for each invocation. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the Runspace is opened /// </remarks> /// <exception cref="InvalidRunspaceStateException"> /// An attempt to change this property was made after opening the Runspace /// </exception> /// <exception cref="InvalidOperationException"> /// The thread options cannot be changed to the requested value /// </exception> public override PSThreadOptions ThreadOptions { get { return _createThreadOptions; } set { lock (this.SyncRoot) { if (value == _createThreadOptions) { return; } if (this.RunspaceStateInfo.State != RunspaceState.BeforeOpen) { if (!IsValidThreadOptionsConfiguration(value)) { throw new InvalidOperationException(StringUtil.Format(RunspaceStrings.InvalidThreadOptionsChange)); } } _createThreadOptions = value; } } } private bool IsValidThreadOptionsConfiguration(PSThreadOptions options) { // If the runspace is already opened, we only allow changing options when: // - The new value is ReuseThread, and // - The apartment state is not STA return options == PSThreadOptions.ReuseThread && this.ApartmentState != ApartmentState.STA; } private PSThreadOptions _createThreadOptions = PSThreadOptions.Default; /// <summary> /// Resets the runspace state to allow for fast reuse. Not all of the runspace /// elements are reset. The goal is to minimize the chance of the user taking /// accidental dependencies on prior runspace state. /// </summary> public override void ResetRunspaceState() { PSInvalidOperationException invalidOperation = null; if (this.InitialSessionState == null) { invalidOperation = PSTraceSource.NewInvalidOperationException(); } else if (this.RunspaceState != Runspaces.RunspaceState.Opened) { invalidOperation = PSTraceSource.NewInvalidOperationException( RunspaceStrings.RunspaceNotInOpenedState, this.RunspaceState); } else if (this.RunspaceAvailability != Runspaces.RunspaceAvailability.Available) { invalidOperation = PSTraceSource.NewInvalidOperationException( RunspaceStrings.ConcurrentInvokeNotAllowed); } if (invalidOperation != null) { invalidOperation.Source = "ResetRunspaceState"; throw invalidOperation; } this.InitialSessionState.ResetRunspaceState(this.ExecutionContext); // Finally, reset history for this runspace. This needs to be done // last to so that changes to the default MaximumHistorySize will be picked up. _history = new History(this.ExecutionContext); } #region protected_methods /// <summary> /// Create a pipeline from a command string. /// </summary> /// <param name="command">A valid command string. Can be null.</param> /// <param name="addToHistory">If true command is added to history.</param> /// <param name="isNested">True for nested pipeline.</param> /// <returns> /// A pipeline pre-filled with Commands specified in commandString. /// </returns> protected override Pipeline CoreCreatePipeline(string command, bool addToHistory, bool isNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return (Pipeline)new LocalPipeline(this, command, addToHistory, isNested); } #endregion protected_methods #region protected_properties /// <summary> /// Gets the execution context. /// </summary> internal override System.Management.Automation.ExecutionContext GetExecutionContext { get { if (_engine == null) return null; else return _engine.Context; } } /// <summary> /// Returns true if the internal host is in a nested prompt. /// </summary> internal override bool InNestedPrompt { get { System.Management.Automation.ExecutionContext context = this.GetExecutionContext; if (context == null) { return false; } return context.InternalHost.HostInNestedPrompt() || InInternalNestedPrompt; } } /// <summary> /// Allows internal nested commands to be run as "HostInNestedPrompt" so that CreatePipelineProcessor() does /// not set CommandOrigin to Internal as it normally does by default. This then allows cmdlets like Invoke-History /// to replay history command lines in the current runspace with the same language mode context as the host. /// </summary> internal bool InInternalNestedPrompt { get; set; } #endregion protected_properties #region internal_properties /// <summary> /// Gets history manager for this runspace. /// </summary> /// <value></value> internal History History { get { return _history; } } /// <summary> /// Gets transcription data for this runspace. /// </summary> /// <value></value> internal TranscriptionData TranscriptionData { get { return _transcriptionData; } } private TranscriptionData _transcriptionData = null; private JobRepository _jobRepository; /// <summary> /// List of jobs in this runspace. /// </summary> internal JobRepository JobRepository { get { return _jobRepository; } } private JobManager _jobManager; /// <summary> /// Manager for JobSourceAdapters registered in this runspace. /// </summary> public override JobManager JobManager { get { return _jobManager; } } private RunspaceRepository _runspaceRepository; /// <summary> /// List of remote runspaces in this runspace. /// </summary> internal RunspaceRepository RunspaceRepository { get { return _runspaceRepository; } } #endregion internal_properties #region Debugger /// <summary> /// Debugger. /// </summary> public override Debugger Debugger { get { return InternalDebugger ?? base.Debugger; } } private static readonly string s_debugPreferenceCachePath = Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell", "DebugPreference.clixml"); private static readonly object s_debugPreferenceLockObject = new object(); /// <summary> /// DebugPreference serves as a property bag to keep /// track of all process specific debug preferences. /// </summary> public class DebugPreference { public string[] AppDomainNames; } /// <summary> /// CreateDebugPerfStruct is a helper method to populate DebugPreference. /// </summary> /// <param name="AppDomainNames">App Domain Names.</param> /// <returns>DebugPreference.</returns> private static DebugPreference CreateDebugPreference(string[] AppDomainNames) { DebugPreference DebugPreference = new DebugPreference(); DebugPreference.AppDomainNames = AppDomainNames; return DebugPreference; } /// <summary> /// SetDebugPreference is a helper method used to enable and disable debug preference. /// </summary> /// <param name="processName">Process Name.</param> /// <param name="appDomainName">App Domain Name.</param> /// <param name="enable">Indicates if the debug preference has to be enabled or disabled.</param> internal static void SetDebugPreference(string processName, List<string> appDomainName, bool enable) { lock (s_debugPreferenceLockObject) { bool iscacheUpdated = false; Hashtable debugPreferenceCache = null; string[] appDomainNames = null; if (appDomainName != null) { appDomainNames = appDomainName.ToArray(); } if (!File.Exists(LocalRunspace.s_debugPreferenceCachePath)) { if (enable) { DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache = new Hashtable(); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } } else { debugPreferenceCache = GetDebugPreferenceCache(null); if (debugPreferenceCache != null) { if (enable) { // Debug preference is set to enable. // If the cache does not contain the process name, then we just update the cache. if (!debugPreferenceCache.ContainsKey(processName)) { DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } else { // In this case, the cache contains the process name, hence we check the list of // app domains for which the debug preference is set to enable. DebugPreference processDebugPreference = GetProcessSpecificDebugPreference(debugPreferenceCache[processName]); // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. if (processDebugPreference != null) { List<string> cachedAppDomainNames = null; if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List<string>(processDebugPreference.AppDomainNames); foreach (string currentAppDomainName in appDomainName) { if (!cachedAppDomainNames.Contains(currentAppDomainName, StringComparer.OrdinalIgnoreCase)) { cachedAppDomainNames.Add(currentAppDomainName); iscacheUpdated = true; } } } if (iscacheUpdated) { DebugPreference DebugPreference = CreateDebugPreference(cachedAppDomainNames.ToArray()); debugPreferenceCache[processName] = DebugPreference; } } } } else { // Debug preference is set to disable. if (debugPreferenceCache.ContainsKey(processName)) { if (appDomainName == null) { debugPreferenceCache.Remove(processName); iscacheUpdated = true; } else { DebugPreference processDebugPreference = GetProcessSpecificDebugPreference(debugPreferenceCache[processName]); // processDebugPreference would point to null if debug preference is enabled for all app domains. // If processDebugPreference is not null then it means that user has selected specific // appdomins for which the debug preference has to be enabled. if (processDebugPreference != null) { List<string> cachedAppDomainNames = null; if (processDebugPreference.AppDomainNames != null && processDebugPreference.AppDomainNames.Length > 0) { cachedAppDomainNames = new List<string>(processDebugPreference.AppDomainNames); foreach (string currentAppDomainName in appDomainName) { if (cachedAppDomainNames.Contains(currentAppDomainName, StringComparer.OrdinalIgnoreCase)) { // remove requested appdomains debug preference details. cachedAppDomainNames.Remove(currentAppDomainName); iscacheUpdated = true; } } } if (iscacheUpdated) { DebugPreference DebugPreference = CreateDebugPreference(cachedAppDomainNames.ToArray()); debugPreferenceCache[processName] = DebugPreference; } } } } } } else { // For whatever reason, cache is corrupted. Hence override the cache content. if (enable) { debugPreferenceCache = new Hashtable(); DebugPreference DebugPreference = CreateDebugPreference(appDomainNames); debugPreferenceCache.Add(processName, DebugPreference); iscacheUpdated = true; } } } if (iscacheUpdated) { using (PowerShell ps = PowerShell.Create()) { ps.AddCommand("Export-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath).AddParameter("InputObject", debugPreferenceCache); ps.Invoke(); } } } } /// <summary> /// GetDebugPreferenceCache is a helper method used to fetch /// the debug preference cache contents as a Hashtable. /// </summary> /// <param name="runspace">Runspace.</param> /// <returns>If the Debug preference is persisted then a hashtable containing /// the debug preference is returned or else Null is returned.</returns> private static Hashtable GetDebugPreferenceCache(Runspace runspace) { Hashtable debugPreferenceCache = null; using (PowerShell ps = PowerShell.Create()) { if (runspace != null) { ps.Runspace = runspace; } ps.AddCommand("Import-Clixml").AddParameter("Path", LocalRunspace.s_debugPreferenceCachePath); Collection<PSObject> psObjects = ps.Invoke(); if (psObjects != null && psObjects.Count == 1) { debugPreferenceCache = psObjects[0].BaseObject as Hashtable; } } return debugPreferenceCache; } /// <summary> /// GetProcessSpecificDebugPreference is a helper method used to fetch persisted process specific debug preference. /// </summary> /// <param name="debugPreference"></param> /// <returns></returns> private static DebugPreference GetProcessSpecificDebugPreference(object debugPreference) { DebugPreference processDebugPreference = null; if (debugPreference != null) { PSObject debugPreferencePsObject = debugPreference as PSObject; if (debugPreferencePsObject != null) { processDebugPreference = LanguagePrimitives.ConvertTo<DebugPreference>(debugPreferencePsObject); } } return processDebugPreference; } #endregion /// <summary> /// Open the runspace. /// </summary> /// <param name="syncCall"> /// parameter which control if Open is done synchronously or asynchronously /// </param> protected override void OpenHelper(bool syncCall) { if (syncCall) { // Open runspace synchronously DoOpenHelper(); } else { // Open runspace in another thread Thread asyncThread = new Thread(new ThreadStart(this.OpenThreadProc)); asyncThread.Start(); } } /// <summary> /// Start method for asynchronous open. /// </summary> private void OpenThreadProc() { #pragma warning disable 56500 try { DoOpenHelper(); } catch (Exception) { // This exception is reported by raising RunspaceState // change event. } #pragma warning restore 56500 } /// <summary> /// Helper function used for opening a runspace. /// </summary> private void DoOpenHelper() { Dbg.Assert(InitialSessionState != null, "InitialSessionState should not be null"); // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } bool startLifeCycleEventWritten = false; s_runspaceInitTracer.WriteLine("begin open runspace"); try { _transcriptionData = new TranscriptionData(); // All ISS-based configuration of the engine itself is done by AutomationEngine, // which calls InitialSessionState.Bind(). Anything that doesn't // require an active and open runspace should be done in ISS.Bind() _engine = new AutomationEngine(Host, InitialSessionState); _engine.Context.CurrentRunspace = this; // Log engine for start of engine life MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Available); startLifeCycleEventWritten = true; _history = new History(_engine.Context); _jobRepository = new JobRepository(); _jobManager = new JobManager(); _runspaceRepository = new RunspaceRepository(); s_runspaceInitTracer.WriteLine("initializing built-in aliases and variable information"); InitializeDefaults(); } catch (Exception exception) { s_runspaceInitTracer.WriteLine("Runspace open failed"); // Log engine health event LogEngineHealthEvent(exception); // Log engine for end of engine life if (startLifeCycleEventWritten) { Dbg.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); } // Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, exception); // Raise the event RaiseRunspaceStateEvents(); // Rethrow the exception. For asynchronous execution, // OpenThreadProc will catch it. For synchronous execution // caller of open will catch it. throw; } SetRunspaceState(RunspaceState.Opened); RunspaceOpening.Set(); // Raise the event RaiseRunspaceStateEvents(); s_runspaceInitTracer.WriteLine("runspace opened successfully"); // Now do initial state configuration that requires an active runspace Exception initError = InitialSessionState.BindRunspace(this, s_runspaceInitTracer); if (initError != null) { // Log engine health event LogEngineHealthEvent(initError); // Log engine for end of engine life Debug.Assert(_engine.Context != null, "if startLifeCycleEventWritten is true, ExecutionContext must be present"); MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); // Open failed. Set the RunspaceState to Broken. SetRunspaceState(RunspaceState.Broken, initError); // Raise the event RaiseRunspaceStateEvents(); // Throw the exception. For asynchronous execution, // OpenThreadProc will catch it. For synchronous execution // caller of open will catch it. throw initError; } #if LEGACYTELEMETRY TelemetryAPI.ReportLocalSessionCreated(InitialSessionState, TranscriptionData); #endif } /// <summary> /// Logs engine health event. /// </summary> internal void LogEngineHealthEvent(Exception exception) { LogEngineHealthEvent( exception, Severity.Error, MshLog.EVENT_ID_CONFIGURATION_FAILURE, null); } /// <summary> /// Logs engine health event. /// </summary> internal void LogEngineHealthEvent(Exception exception, Severity severity, int id, Dictionary<string, string> additionalInfo) { Dbg.Assert(exception != null, "Caller should validate the parameter"); LogContext logContext = new LogContext(); logContext.EngineVersion = Version.ToString(); logContext.HostId = Host.InstanceId.ToString(); logContext.HostName = Host.Name; logContext.HostVersion = Host.Version.ToString(); logContext.RunspaceId = InstanceId.ToString(); logContext.Severity = severity.ToString(); logContext.ShellId = Utils.DefaultPowerShellShellID; MshLog.LogEngineHealthEvent( logContext, id, exception, additionalInfo); } /// <summary> /// Returns the thread that must be used to execute pipelines when CreateThreadOptions is ReuseThread. /// </summary> /// <remarks> /// The pipeline calls this function after ensuring there is a single thread in the pipeline, so no locking is necessary /// </remarks> internal PipelineThread GetPipelineThread() { if (_pipelineThread == null) { _pipelineThread = new PipelineThread(this.ApartmentState); } return _pipelineThread; } private PipelineThread _pipelineThread = null; protected override void CloseHelper(bool syncCall) { if (syncCall) { // Do close synchronously DoCloseHelper(); } else { // Do close asynchronously Thread asyncThread = new Thread(new ThreadStart(this.CloseThreadProc)); asyncThread.Start(); } } /// <summary> /// Start method for asynchronous close. /// </summary> private void CloseThreadProc() { #pragma warning disable 56500 try { DoCloseHelper(); } catch (Exception) { } #pragma warning restore 56500 } /// <summary> /// Close the runspace. /// </summary> /// <remarks> /// Attempts to create/execute pipelines after a call to /// close will fail. /// </remarks> private void DoCloseHelper() { var isPrimaryRunspace = (Runspace.PrimaryRunspace == this); var haveOpenRunspaces = false; foreach (Runspace runspace in RunspaceList) { if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { haveOpenRunspaces = true; break; } } // When closing the primary runspace, ensure all other local runspaces are closed. var closeAllOpenRunspaces = isPrimaryRunspace && haveOpenRunspaces; // Stop all transcriptions and un-initialize AMSI if we're the last runspace to exit or we are exiting the primary runspace. if (!haveOpenRunspaces) { ExecutionContext executionContext = this.GetExecutionContext; if (executionContext != null) { PSHostUserInterface hostUI = executionContext.EngineHostInterface.UI; if (hostUI != null) { hostUI.StopAllTranscribing(); } } AmsiUtils.Uninitialize(); } // Generate the shutdown event if (Events != null) Events.GenerateEvent(PSEngineEvent.Exiting, null, Array.Empty<object>(), null, true, false); // Stop all running pipelines // Note:Do not perform the Cancel in lock. Reason is // Pipeline executes in separate thread, say threadP. // When pipeline is canceled/failed/completed in // Pipeline.ExecuteThreadProc it removes the pipeline // from the list of running pipelines. threadP will need // lock to remove the pipelines from the list of running pipelines // And we will deadlock. // Note:It is possible that one or more pipelines in the list // of active pipelines have completed before we call cancel. // That is fine since Pipeline.Cancel handles that( It ignores // the cancel request if pipeline execution has already // completed/failed/canceled. StopPipelines(); // Disconnect all disconnectable jobs in the job repository. StopOrDisconnectAllJobs(); // Close or disconnect all the remote runspaces available in the // runspace repository. CloseOrDisconnectAllRemoteRunspaces(() => { List<RemoteRunspace> runspaces = new List<RemoteRunspace>(); foreach (PSSession psSession in this.RunspaceRepository.Runspaces) { runspaces.Add(psSession.Runspace as RemoteRunspace); } return runspaces; }); // Notify Engine components that that runspace is closing. _engine.Context.RunspaceClosingNotification(); // Log engine lifecycle event. MshLog.LogEngineLifecycleEvent(_engine.Context, EngineState.Stopped); // All pipelines have been canceled. Close the runspace. _engine = null; SetRunspaceState(RunspaceState.Closed); // Raise Event RaiseRunspaceStateEvents(); if (closeAllOpenRunspaces) { foreach (Runspace runspace in RunspaceList) { if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { runspace.Dispose(); } } } // Report telemetry if we have no more open runspaces. #if LEGACYTELEMETRY bool allRunspacesClosed = true; bool hostProvidesExitTelemetry = false; foreach (var r in Runspace.RunspaceList) { if (r.RunspaceStateInfo.State != RunspaceState.Closed) { allRunspacesClosed = false; break; } var localRunspace = r as LocalRunspace; if (localRunspace != null && localRunspace.Host is IHostProvidesTelemetryData) { hostProvidesExitTelemetry = true; break; } } if (allRunspacesClosed && !hostProvidesExitTelemetry) { TelemetryAPI.ReportExitTelemetry(null); } #endif } /// <summary> /// Closes or disconnects all the remote runspaces passed in by the getRunspace /// function. If a remote runspace supports disconnect then it will be disconnected /// rather than closed. /// </summary> private static void CloseOrDisconnectAllRemoteRunspaces(Func<List<RemoteRunspace>> getRunspaces) { List<RemoteRunspace> runspaces = getRunspaces(); if (runspaces.Count == 0) { return; } // whether the close of all remoterunspaces completed using (ManualResetEvent remoteRunspaceCloseCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); throttleManager.ThrottleComplete += (object sender, EventArgs e) => remoteRunspaceCloseCompleted.Set(); foreach (RemoteRunspace remoteRunspace in runspaces) { IThrottleOperation operation = new CloseOrDisconnectRunspaceOperationHelper(remoteRunspace); throttleManager.AddOperation(operation); } throttleManager.EndSubmitOperations(); remoteRunspaceCloseCompleted.WaitOne(); } } /// <summary> /// Disconnects all disconnectable jobs listed in the JobRepository. /// </summary> private void StopOrDisconnectAllJobs() { if (JobRepository.Jobs.Count == 0) { return; } List<RemoteRunspace> disconnectRunspaces = new List<RemoteRunspace>(); using (ManualResetEvent jobsStopCompleted = new ManualResetEvent(false)) { ThrottleManager throttleManager = new ThrottleManager(); throttleManager.ThrottleComplete += (object sender, EventArgs e) => jobsStopCompleted.Set(); foreach (Job job in this.JobRepository.Jobs) { // Only stop or disconnect PowerShell jobs. if (job is not PSRemotingJob) { continue; } if (!job.CanDisconnect) { // If the job cannot be disconnected then add it to // the stop list. throttleManager.AddOperation(new StopJobOperationHelper(job)); } else if (job.JobStateInfo.State == JobState.Running) { // Otherwise add disconnectable runspaces to list so that // they can be disconnected. IEnumerable<RemoteRunspace> jobRunspaces = job.GetRunspaces(); if (jobRunspaces != null) { disconnectRunspaces.AddRange(jobRunspaces); } } } // Stop jobs. throttleManager.EndSubmitOperations(); jobsStopCompleted.WaitOne(); } // Disconnect all disconnectable job runspaces found. CloseOrDisconnectAllRemoteRunspaces(() => disconnectRunspaces); } internal void ReleaseDebugger() { Debugger debugger = Debugger; if (debugger != null) { try { if (debugger.UnhandledBreakpointMode == UnhandledBreakpointProcessingMode.Wait) { // Sets the mode and also releases a held debug stop. debugger.UnhandledBreakpointMode = UnhandledBreakpointProcessingMode.Ignore; } } catch (PSNotImplementedException) { } } } #region SessionStateProxy protected override void DoSetVariable(string name, object value) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } _engine.Context.EngineSessionState.SetVariableValue(name, value, CommandOrigin.Internal); } protected override object DoGetVariable(string name) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.GetVariableValue(name); } protected override List<string> DoApplications { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Applications; } } protected override List<string> DoScripts { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Scripts; } } protected override DriveManagementIntrinsics DoDrive { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Drive; } } protected override PSLanguageMode DoLanguageMode { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.LanguageMode; } set { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } _engine.Context.SessionState.LanguageMode = value; } } protected override PSModuleInfo DoModule { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineSessionState.Module; } } protected override PathIntrinsics DoPath { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Path; } } protected override CmdletProviderManagementIntrinsics DoProvider { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.Provider; } } protected override PSVariableIntrinsics DoPSVariable { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.SessionState.PSVariable; } } protected override CommandInvocationIntrinsics DoInvokeCommand { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineIntrinsics.InvokeCommand; } } protected override ProviderIntrinsics DoInvokeProvider { get { if (_disposed) { throw PSTraceSource.NewObjectDisposedException("runspace"); } return _engine.Context.EngineIntrinsics.InvokeProvider; } } #endregion SessionStateProxy #region IDisposable Members /// <summary> /// Set to true when object is disposed. /// </summary> private bool _disposed; /// <summary> /// Protected dispose which can be overridden by derived classes. /// </summary> /// <param name="disposing"></param> [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "pipelineThread", Justification = "pipelineThread is disposed in Close()")] protected override void Dispose(bool disposing) { try { if (_disposed) { return; } lock (SyncRoot) { if (_disposed) { return; } _disposed = true; } if (disposing) { Close(); _engine = null; _history = null; _transcriptionData = null; _jobManager = null; _jobRepository = null; _runspaceRepository = null; if (RunspaceOpening != null) { RunspaceOpening.Dispose(); RunspaceOpening = null; } // Dispose the event manager if (this.ExecutionContext != null && this.ExecutionContext.Events != null) { try { this.ExecutionContext.Events.Dispose(); } catch (ObjectDisposedException) { } } } } finally { base.Dispose(disposing); } } /// <summary> /// Close the runspace. /// </summary> public override void Close() { // Do not put cleanup activities in here, as they aren't // captured in CloseAsync() case. Instead, put them in // DoCloseHelper() base.Close(); // call base.Close() first to make it stop the pipeline if (_pipelineThread != null) { _pipelineThread.Close(); } } #endregion IDisposable Members #region private fields /// <summary> /// AutomationEngine instance for this runspace. /// </summary> private AutomationEngine _engine; internal AutomationEngine Engine { get { return _engine; } } /// <summary> /// Manages history for this runspace. /// </summary> private History _history; [TraceSource("RunspaceInit", "Initialization code for Runspace")] private static readonly PSTraceSource s_runspaceInitTracer = PSTraceSource.GetTracer("RunspaceInit", "Initialization code for Runspace", false); /// <summary> /// This ensures all processes have a server/listener. /// </summary> private static readonly RemoteSessionNamedPipeServer s_IPCNamedPipeServer = RemoteSessionNamedPipeServer.IPCNamedPipeServer; #endregion private fields } #region Helper Class /// <summary> /// Helper class to stop a running job. /// </summary> internal sealed class StopJobOperationHelper : IThrottleOperation { private readonly Job _job; /// <summary> /// Internal constructor. /// </summary> /// <param name="job">Job object to stop.</param> internal StopJobOperationHelper(Job job) { _job = job; _job.StateChanged += HandleJobStateChanged; } /// <summary> /// Handles the Job state change event. /// </summary> /// <param name="sender">Originator of event, unused.</param> /// <param name="eventArgs">Event arguments containing Job state.</param> private void HandleJobStateChanged(object sender, JobStateEventArgs eventArgs) { if (_job.IsFinishedState(_job.JobStateInfo.State)) { // We are done when the job is in the finished state. RaiseOperationCompleteEvent(); } } /// <summary> /// Override method to start the operation. /// </summary> internal override void StartOperation() { if (_job.IsFinishedState(_job.JobStateInfo.State)) { // The job is already in the finished state and so cannot be stopped. RaiseOperationCompleteEvent(); } else { // Otherwise stop the job. _job.StopJob(); } } /// <summary> /// Override method to stop the operation. Not used, stop operation must /// run to completion. /// </summary> internal override void StopOperation() { } /// <summary> /// Event to signal ThrottleManager when the operation is complete. /// </summary> internal override event EventHandler<OperationStateEventArgs> OperationComplete; /// <summary> /// Raise the OperationComplete event. /// </summary> private void RaiseOperationCompleteEvent() { _job.StateChanged -= HandleJobStateChanged; OperationStateEventArgs operationStateArgs = new OperationStateEventArgs(); operationStateArgs.OperationState = OperationState.StartComplete; operationStateArgs.BaseEvent = EventArgs.Empty; OperationComplete.SafeInvoke(this, operationStateArgs); } } /// <summary> /// Helper class to disconnect a runspace if the runspace supports disconnect /// semantics or otherwise close the runspace. /// </summary> internal sealed class CloseOrDisconnectRunspaceOperationHelper : IThrottleOperation { private readonly RemoteRunspace _remoteRunspace; /// <summary> /// Internal constructor. /// </summary> /// <param name="remoteRunspace"></param> internal CloseOrDisconnectRunspaceOperationHelper(RemoteRunspace remoteRunspace) { _remoteRunspace = remoteRunspace; _remoteRunspace.StateChanged += HandleRunspaceStateChanged; } /// <summary> /// Handle the runspace state changed event. /// </summary> /// <param name="sender">Sender of this information, unused.</param> /// <param name="eventArgs">Runspace event args.</param> private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { switch (eventArgs.RunspaceStateInfo.State) { case RunspaceState.BeforeOpen: case RunspaceState.Closing: case RunspaceState.Opened: case RunspaceState.Opening: case RunspaceState.Disconnecting: return; } // remoteRunspace.Dispose(); // remoteRunspace = null; RaiseOperationCompleteEvent(); } /// <summary> /// Start the operation of closing the runspace. /// </summary> internal override void StartOperation() { if (_remoteRunspace.RunspaceStateInfo.State == RunspaceState.Closed || _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Broken || _remoteRunspace.RunspaceStateInfo.State == RunspaceState.Disconnected) { // If the runspace is currently in a disconnected state then leave it // as is. // in this case, calling a close won't raise any events. Simply raise // the OperationCompleted event. After the if check, but before we // get to this point if the state was changed, then the StateChanged // event handler will anyway raise the event and so we are fine RaiseOperationCompleteEvent(); } else { // If the runspace supports disconnect semantics and is running a command, // then disconnect it rather than closing it. if (_remoteRunspace.CanDisconnect && _remoteRunspace.GetCurrentlyRunningPipeline() != null) { _remoteRunspace.DisconnectAsync(); } else { _remoteRunspace.CloseAsync(); } } } /// <summary> /// There is no scenario where we are going to cancel this close /// Hence this method is intentionally empty. /// </summary> internal override void StopOperation() { } /// <summary> /// Event raised when the required operation is complete. /// </summary> internal override event EventHandler<OperationStateEventArgs> OperationComplete; /// <summary> /// Raise the operation completed event. /// </summary> private void RaiseOperationCompleteEvent() { _remoteRunspace.StateChanged -= HandleRunspaceStateChanged; OperationStateEventArgs operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.OperationState = OperationState.StartComplete; operationStateEventArgs.BaseEvent = EventArgs.Empty; OperationComplete.SafeInvoke(this, operationStateEventArgs); } } /// <summary> /// Defines the exception thrown an error loading modules occurs while opening the runspace. It /// contains a list of all of the module errors that have occurred. /// </summary> [Serializable] public class RunspaceOpenModuleLoadException : RuntimeException { #region ctor /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException /// with the message set to typeof(ScriptBlockToPowerShellNotSupportedException).FullName. /// </summary> public RunspaceOpenModuleLoadException() : base(typeof(ScriptBlockToPowerShellNotSupportedException).FullName) { } /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message. /// </summary> /// <param name="message">The exception's message.</param> public RunspaceOpenModuleLoadException(string message) : base(message) { } /// <summary> /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException. /// </summary> /// <param name="message">The exception's message.</param> /// <param name="innerException">The exceptions's inner exception.</param> public RunspaceOpenModuleLoadException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Recommended constructor for the class. /// </summary> /// <param name="moduleName">The name of the module that cause the error.</param> /// <param name="errors">The collection of errors that occurred during module processing.</param> internal RunspaceOpenModuleLoadException( string moduleName, PSDataCollection<ErrorRecord> errors) : base(StringUtil.Format(RunspaceStrings.ErrorLoadingModulesOnRunspaceOpen, moduleName, (errors != null && errors.Count > 0 && errors[0] != null) ? errors[0].ToString() : string.Empty), null) { _errors = errors; this.SetErrorId("ErrorLoadingModulesOnRunspaceOpen"); this.SetErrorCategory(ErrorCategory.OpenError); } #endregion ctor /// <summary> /// The collection of error records generated while loading the modules. /// </summary> public PSDataCollection<ErrorRecord> ErrorRecords { get { return _errors; } } private readonly PSDataCollection<ErrorRecord> _errors; #region Serialization /// <summary> /// Initializes a new instance of RunspaceOpenModuleLoadException with serialization parameters. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected RunspaceOpenModuleLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Populates a <see cref="SerializationInfo"/> with the /// data needed to serialize the RunspaceOpenModuleLoadException object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination for this serialization.</param> public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new PSArgumentNullException(nameof(info)); } base.GetObjectData(info, context); } #endregion Serialization } #endregion Helper Class }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; /// <summary> /// System.Collections.IDictionary.Clear() /// </summary> public class IDictionaryClear { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Using Dictionary<string,Byte> to implemented the clear method"); try { IDictionary iDictionary = new Dictionary<string,Byte>(); string[] key = new string[1000]; Byte[] value = new Byte[1000]; for (int i = 0; i < 1000; i++) { key[i] = TestLibrary.Generator.GetString(-55, false, 1, 100); } TestLibrary.Generator.GetBytes(-55, value); for (int i = 0; i < 1000; i++) { while (iDictionary.Contains(key[i])) { key[i] = TestLibrary.Generator.GetString(false, 1, 100); } iDictionary.Add(key[i], value[i]); } iDictionary.Clear(); if (iDictionary.Count != 0) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Using Dictionary<Int32,Byte> to implemented the clear method"); try { IDictionary iDictionary = new Dictionary<Int32,Byte>(); Int32[] key = new Int32[1000]; Byte[] value = new Byte[1000]; for (int i = 0; i < 1000; i++) { key[i] = i; } TestLibrary.Generator.GetBytes(-55, value); for (int i = 0; i < 1000; i++) { iDictionary.Add(key[i], value[i]); } iDictionary.Clear(); if (iDictionary.Count != 0) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected "); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The IDictionary is read-only"); try { IDictionary iDictionary = new MyIDictionary(); iDictionary.Clear(); TestLibrary.TestFramework.LogError("101", "The NotSupportedException was not thrown as expected"); retVal = false; } catch (NotSupportedException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { IDictionaryClear test = new IDictionaryClear(); TestLibrary.TestFramework.BeginTestCase("IDictionaryClear"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } } public class MyIDictionary : IDictionary { #region IDictionary Members public void Add(object key, object value) { throw new Exception("The method or operation is not implemented."); } public void Clear() { if (this.IsReadOnly) { throw new NotSupportedException("The IDictionary is read-only"); } else { throw new Exception("The method or operation is not implemented."); } } public bool Contains(object key) { throw new Exception("The method or operation is not implemented."); } public IDictionaryEnumerator GetEnumerator() { throw new Exception("The method or operation is not implemented."); } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public ICollection Keys { get { throw new Exception("The method or operation is not implemented."); } } public void Remove(object key) { throw new Exception("The method or operation is not implemented."); } public ICollection Values { get { throw new Exception("The method or operation is not implemented."); } } public object this[object key] { get { throw new Exception("The method or operation is not implemented."); } set { throw new Exception("The method or operation is not implemented."); } } #endregion #region ICollection Members public void CopyTo(Array array, int index) { throw new Exception("The method or operation is not implemented."); } public int Count { get { throw new Exception("The method or operation is not implemented."); } } public bool IsSynchronized { get { throw new Exception("The method or operation is not implemented."); } } public object SyncRoot { get { throw new Exception("The method or operation is not implemented."); } } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { throw new Exception("The method or operation is not implemented."); } #endregion }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; using System.Collections.Specialized; using System; using System.Text; public class LogitechGSDK { //ARX CONTROL SDK public const int LOGI_ARX_ORIENTATION_PORTRAIT = 0x01; public const int LOGI_ARX_ORIENTATION_LANDSCAPE = 0x10; public const int LOGI_ARX_EVENT_FOCUS_ACTIVE = 0x01; public const int LOGI_ARX_EVENT_FOCUS_INACTIVE = 0x02; public const int LOGI_ARX_EVENT_TAP_ON_TAG = 0x04; public const int LOGI_ARX_EVENT_MOBILEDEVICE_ARRIVAL = 0x08; public const int LOGI_ARX_EVENT_MOBILEDEVICE_REMOVAL = 0x10; public const int LOGI_ARX_DEVICETYPE_IPHONE = 0x01; public const int LOGI_ARX_DEVICETYPE_IPAD = 0x02; public const int LOGI_ARX_DEVICETYPE_ANDROID_SMALL = 0x03; public const int LOGI_ARX_DEVICETYPE_ANDROID_NORMAL = 0x04; public const int LOGI_ARX_DEVICETYPE_ANDROID_LARGE = 0x05; public const int LOGI_ARX_DEVICETYPE_ANDROID_XLARGE = 0x06; public const int LOGI_ARX_DEVICETYPE_ANDROID_OTHER = 0x07; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void logiArxCB(int eventType, int eventValue, [MarshalAs(UnmanagedType.LPWStr)]String eventArg, IntPtr context); public struct logiArxCbContext { public logiArxCB arxCallBack; public IntPtr arxContext; } [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxInit(String identifier, String friendlyName, ref logiArxCbContext callback); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxAddFileAs(String filePath, String fileName, String mimeType); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxAddContentAs(byte[] content, int size, String fileName, String mimeType =""); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxAddUTF8StringAs(String stringContent, String fileName, String mimeType =""); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxAddImageFromBitmap(byte[] bitmap, int width, int height, String fileName); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxSetIndex(String fileName); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxSetTagPropertyById(String tagId, String prop, String newValue); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxSetTagsPropertyByClass(String tagsClass, String prop, String newValue); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxSetTagContentById(String tagId, String newContent); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiArxSetTagsContentByClass(String tagsClass, String newContent); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiArxGetLastError(); [DllImport("LogitechGArxControlEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern void LogiArxShutdown(); //LED SDK public const int LOGI_LED_BITMAP_WIDTH = 21; public const int LOGI_LED_BITMAP_HEIGHT = 6; public const int LOGI_LED_BITMAP_BYTES_PER_KEY = 4; public const int LOGI_LED_BITMAP_SIZE = LOGI_LED_BITMAP_WIDTH*LOGI_LED_BITMAP_HEIGHT*LOGI_LED_BITMAP_BYTES_PER_KEY; public const int LOGI_LED_DURATION_INFINITE = 0; private const int LOGI_DEVICETYPE_MONOCHROME_ORD = 0; private const int LOGI_DEVICETYPE_RGB_ORD = 1; private const int LOGI_DEVICETYPE_PERKEY_RGB_ORD = 2; public const int LOGI_DEVICETYPE_MONOCHROME = (1 << LOGI_DEVICETYPE_MONOCHROME_ORD); public const int LOGI_DEVICETYPE_RGB = (1 << LOGI_DEVICETYPE_RGB_ORD); public const int LOGI_DEVICETYPE_PERKEY_RGB = (1 << LOGI_DEVICETYPE_PERKEY_RGB_ORD); public enum keyboardNames { ESC = 0x01, F1 = 0x3b, F2 = 0x3c, F3 = 0x3d, F4 = 0x3e, F5 = 0x3f, F6 = 0x40, F7 = 0x41, F8 = 0x42, F9 = 0x43, F10 = 0x44, F11 = 0x57, F12 = 0x58, PRINT_SCREEN = 0x137, SCROLL_LOCK = 0x46, PAUSE_BREAK = 0x45, TILDE = 0x29, ONE = 0x02, TWO = 0x03, THREE = 0x04, FOUR = 0x05, FIVE = 0x06, SIX = 0x07, SEVEN = 0x08, EIGHT = 0x09, NINE = 0x0A, ZERO = 0x0B, MINUS = 0x0C, EQUALS = 0x0D, BACKSPACE = 0x0E, INSERT = 0x152, HOME = 0x147, PAGE_UP = 0x149, NUM_LOCK = 0x145, NUM_SLASH = 0x135, NUM_ASTERISK = 0x37, NUM_MINUS = 0x4A, TAB = 0x0F, Q = 0x10, W = 0x11, E = 0x12, R = 0x13, T = 0x14, Y = 0x15, U = 0x16, I = 0x17, O = 0x18, P = 0x19, OPEN_BRACKET = 0x1A, CLOSE_BRACKET = 0x1B, BACKSLASH = 0x2B, KEYBOARD_DELETE = 0x153, END = 0x14F, PAGE_DOWN = 0x151, NUM_SEVEN = 0x47, NUM_EIGHT = 0x48, NUM_NINE = 0x49, NUM_PLUS = 0x4E, CAPS_LOCK = 0x3A, A = 0x1E, S = 0x1F, D = 0x20, F = 0x21, G = 0x22, H = 0x23, J = 0x24, K = 0x25, L = 0x26, SEMICOLON = 0x27, APOSTROPHE = 0x28, ENTER = 0x1C, NUM_FOUR = 0x4B, NUM_FIVE = 0x4C, NUM_SIX = 0x4D, LEFT_SHIFT = 0x2A, Z = 0x2C, X = 0x2D, C = 0x2E, V = 0x2F, B = 0x30, N = 0x31, M = 0x32, COMMA = 0x33, PERIOD = 0x34, FORWARD_SLASH = 0x35, RIGHT_SHIFT = 0x36, ARROW_UP = 0x148, NUM_ONE = 0x4F, NUM_TWO = 0x50, NUM_THREE = 0x51, NUM_ENTER = 0x11C, LEFT_CONTROL = 0x1D, LEFT_WINDOWS = 0x15B, LEFT_ALT = 0x38, SPACE = 0x39, RIGHT_ALT = 0x138, RIGHT_WINDOWS = 0x15C, APPLICATION_SELECT = 0x15D, RIGHT_CONTROL = 0x11D, ARROW_LEFT = 0x14B, ARROW_DOWN = 0x150, ARROW_RIGHT = 0x14D, NUM_ZERO = 0x52, NUM_PERIOD = 0x53, }; [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedInit(); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetTargetDevice(int targetDevice); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedGetSdkVersion(ref int majorNum, ref int minorNum, ref int buildNum); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSaveCurrentLighting(); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLighting(int redPercentage, int greenPercentage, int bluePercentage); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedRestoreLighting(); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedFlashLighting(int redPercentage, int greenPercentage, int bluePercentage, int milliSecondsDuration, int milliSecondsInterval); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedPulseLighting(int redPercentage, int greenPercentage, int bluePercentage, int milliSecondsDuration, int milliSecondsInterval); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedStopEffects(); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLightingFromBitmap(byte[] bitmap); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLightingForKeyWithScanCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLightingForKeyWithHidCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLightingForKeyWithQuartzCode(int keyCode, int redPercentage, int greenPercentage, int bluePercentage); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSetLightingForKeyWithKeyName(keyboardNames keyCode, int redPercentage, int greenPercentage, int bluePercentage); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedSaveLightingForKey(keyboardNames keyName); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedRestoreLightingForKey(keyboardNames keyName); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedFlashSingleKey(keyboardNames keyName, int redPercentage, int greenPercentage, int bluePercentage, int msDuration, int msInterval); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedPulseSingleKey(keyboardNames keyName, int startRedPercentage, int startGreenPercentage, int startBluePercentage, int finishRedPercentage, int finishGreenPercentage, int finishBluePercentage, int msDuration, bool isInfinite); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLedStopEffectsOnKey(keyboardNames keyName); [DllImport("LogitechLedEnginesWrapper ", CallingConvention = CallingConvention.Cdecl)] public static extern void LogiLedShutdown(); //END OF LED SDK //LCD SDK public const int LOGI_LCD_COLOR_BUTTON_LEFT = (0x00000100); public const int LOGI_LCD_COLOR_BUTTON_RIGHT = (0x00000200); public const int LOGI_LCD_COLOR_BUTTON_OK = (0x00000400); public const int LOGI_LCD_COLOR_BUTTON_CANCEL = (0x00000800); public const int LOGI_LCD_COLOR_BUTTON_UP = (0x00001000); public const int LOGI_LCD_COLOR_BUTTON_DOWN = (0x00002000); public const int LOGI_LCD_COLOR_BUTTON_MENU = (0x00004000); public const int LOGI_LCD_MONO_BUTTON_0 = (0x00000001); public const int LOGI_LCD_MONO_BUTTON_1 = (0x00000002); public const int LOGI_LCD_MONO_BUTTON_2 = (0x00000004); public const int LOGI_LCD_MONO_BUTTON_3 = (0x00000008); public const int LOGI_LCD_MONO_WIDTH = 160; public const int LOGI_LCD_MONO_HEIGHT = 43; public const int LOGI_LCD_COLOR_WIDTH = 320; public const int LOGI_LCD_COLOR_HEIGHT = 240; public const int LOGI_LCD_TYPE_MONO = (0x00000001); public const int LOGI_LCD_TYPE_COLOR = (0x00000002); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdInit(String friendlyName, int lcdType); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdIsConnected(int lcdType); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdIsButtonPressed(int button); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern void LogiLcdUpdate(); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern void LogiLcdShutdown(); // Monochrome LCD functions [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdMonoSetBackground(byte [] monoBitmap); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdMonoSetText(int lineNumber, String text); // Color LCD functions [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdColorSetBackground(byte [] colorBitmap); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdColorSetTitle(String text, int red , int green , int blue ); [DllImport("LogitechLcdEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiLcdColorSetText(int lineNumber, String text, int red, int green, int blue); //END OF LCD SDK //G-KEY SDK public const int LOGITECH_MAX_MOUSE_BUTTONS = 20; public const int LOGITECH_MAX_GKEYS = 29; public const int LOGITECH_MAX_M_STATES = 3; [StructLayout(LayoutKind.Sequential, Pack=2)] public struct GkeyCode { public ushort complete; // index of the G key or mouse button, for example, 6 for G6 or Button 6 public int keyIdx{ get{ return complete & 255; } } // key up or down, 1 is down, 0 is up public int keyDown{ get{ return (complete >> 8) & 1; } } // mState (1, 2 or 3 for M1, M2 and M3) public int mState{ get{ return (complete >> 9) & 3; } } // indicate if the Event comes from a mouse, 1 is yes, 0 is no. public int mouse{ get{ return (complete >> 11) & 15; } } // reserved1 public int reserved1{ get{ return (complete >> 15) & 1; } } // reserved2 public int reserved2{ get{ return (complete >> 16) & 131071; } } } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void logiGkeyCB(GkeyCode gkeyCode, [MarshalAs(UnmanagedType.LPWStr)]String gkeyOrButtonString, IntPtr context); public struct logiGKeyCbContext { public logiGkeyCB gkeyCallBack; public IntPtr gkeyContext; } [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGkeyInitWithoutCallback(); [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGkeyInitWithoutContext(logiGkeyCB gkeyCB); [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGkeyInit(ref logiGKeyCbContext cbStruct); [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGkeyIsMouseButtonPressed(int buttonNumber); [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr LogiGkeyGetMouseButtonString(int buttonNumber); public static String LogiGkeyGetMouseButtonStr(int buttonNumber){ String str = Marshal.PtrToStringUni(LogiGkeyGetMouseButtonString(buttonNumber)); return str; } [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGkeyIsKeyboardGkeyPressed(int gkeyNumber, int modeNumber); [DllImport("LogitechGKeyEnginesWrapper")] private static extern IntPtr LogiGkeyGetKeyboardGkeyString(int gkeyNumber, int modeNumber); public static String LogiGkeyGetKeyboardGkeyStr(int gkeyNumber, int modeNumber){ String str = Marshal.PtrToStringUni(LogiGkeyGetKeyboardGkeyString(gkeyNumber, modeNumber)); return str; } [DllImport("LogitechGKeyEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern void LogiGkeyShutdown(); //STEERING WHEEL SDK public const int LOGI_MAX_CONTROLLERS = 2; //Force types public const int LOGI_FORCE_NONE = -1; public const int LOGI_FORCE_SPRING = 0; public const int LOGI_FORCE_CONSTANT = 1; public const int LOGI_FORCE_DAMPER = 2; public const int LOGI_FORCE_SIDE_COLLISION = 3; public const int LOGI_FORCE_FRONTAL_COLLISION = 4; public const int LOGI_FORCE_DIRT_ROAD = 5; public const int LOGI_FORCE_BUMPY_ROAD = 6; public const int LOGI_FORCE_SLIPPERY_ROAD = 7; public const int LOGI_FORCE_SURFACE_EFFECT = 8; public const int LOGI_NUMBER_FORCE_EFFECTS = 9; public const int LOGI_FORCE_SOFTSTOP = 10; public const int LOGI_FORCE_CAR_AIRBORNE = 11; //Periodic types for surface effect public const int LOGI_PERIODICTYPE_NONE = -1; public const int LOGI_PERIODICTYPE_SINE = 0; public const int LOGI_PERIODICTYPE_SQUARE = 1; public const int LOGI_PERIODICTYPE_TRIANGLE = 2; //Devices types public const int LOGI_DEVICE_TYPE_NONE = -1; public const int LOGI_DEVICE_TYPE_WHEEL = 0; public const int LOGI_DEVICE_TYPE_JOYSTICK = 1; public const int LOGI_DEVICE_TYPE_GAMEPAD = 2; public const int LOGI_DEVICE_TYPE_OTHER = 3; public const int LOGI_NUMBER_DEVICE_TYPES = 4; //Manufacturer types public const int LOGI_MANUFACTURER_NONE = -1; public const int LOGI_MANUFACTURER_LOGITECH = 0; public const int LOGI_MANUFACTURER_MICROSOFT = 1; public const int LOGI_MANUFACTURER_OTHER = 2; //Model types public const int LOGI_MODEL_G27 = 0; public const int LOGI_MODEL_DRIVING_FORCE_GT = 1; public const int LOGI_MODEL_G25 = 2; public const int LOGI_MODEL_MOMO_RACING = 3; public const int LOGI_MODEL_MOMO_FORCE = 4; public const int LOGI_MODEL_DRIVING_FORCE_PRO = 5; public const int LOGI_MODEL_DRIVING_FORCE = 6; public const int LOGI_MODEL_NASCAR_RACING_WHEEL = 7; public const int LOGI_MODEL_FORMULA_FORCE = 8; public const int LOGI_MODEL_FORMULA_FORCE_GP = 9; public const int LOGI_MODEL_FORCE_3D_PRO = 10; public const int LOGI_MODEL_EXTREME_3D_PRO = 11; public const int LOGI_MODEL_FREEDOM_24 = 12; public const int LOGI_MODEL_ATTACK_3 = 13; public const int LOGI_MODEL_FORCE_3D = 14; public const int LOGI_MODEL_STRIKE_FORCE_3D = 15; public const int LOGI_MODEL_G940_JOYSTICK = 16; public const int LOGI_MODEL_G940_THROTTLE = 17; public const int LOGI_MODEL_G940_PEDALS = 18; public const int LOGI_MODEL_RUMBLEPAD = 19; public const int LOGI_MODEL_RUMBLEPAD_2 = 20; public const int LOGI_MODEL_CORDLESS_RUMBLEPAD_2 = 21; public const int LOGI_MODEL_CORDLESS_GAMEPAD = 22; public const int LOGI_MODEL_DUAL_ACTION_GAMEPAD = 23; public const int LOGI_MODEL_PRECISION_GAMEPAD_2 = 24; public const int LOGI_MODEL_CHILLSTREAM = 25; public const int LOGI_NUMBER_MODELS = 26; [StructLayout(LayoutKind.Sequential, Pack=2)] public struct LogiControllerPropertiesData { public bool forceEnable; public int overallGain; public int springGain; public int damperGain; public bool defaultSpringEnabled; public int defaultSpringGain; public bool combinePedals; public int wheelRange; public bool gameSettingsEnabled; public bool allowGameSettings; } [StructLayout(LayoutKind.Sequential, Pack=2)] public struct DIJOYSTATE2ENGINES { public int lX; /* x-axis position */ public int lY; /* y-axis position */ public int lZ; /* z-axis position */ public int lRx; /* x-axis rotation */ public int lRy; /* y-axis rotation */ public int lRz; /* z-axis rotation */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int [] rglSlider; /* extra axes positions */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public uint []rgdwPOV; /* POV directions */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] public byte [] rgbButtons; /* 128 buttons */ public int lVX; /* x-axis velocity */ public int lVY; /* y-axis velocity */ public int lVZ; /* z-axis velocity */ public int lVRx; /* x-axis angular velocity */ public int lVRy; /* y-axis angular velocity */ public int lVRz; /* z-axis angular velocity */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int [] rglVSlider; /* extra axes velocities */ public int lAX; /* x-axis acceleration */ public int lAY; /* y-axis acceleration */ public int lAZ; /* z-axis acceleration */ public int lARx; /* x-axis angular acceleration */ public int lARy; /* y-axis angular acceleration */ public int lARz; /* z-axis angular acceleration */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int [] rglASlider; /* extra axes accelerations */ public int lFX; /* x-axis force */ public int lFY; /* y-axis force */ public int lFZ; /* z-axis force */ public int lFRx; /* x-axis torque */ public int lFRy; /* y-axis torque */ public int lFRz; /* z-axis torque */ [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)] public int[] rglFSlider; /* extra axes forces */ }; [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiSteeringInitialize(bool ignoreXInputControllers); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiUpdate(); [DllImport("LogitechSteeringWheelEnginesWrapper", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr LogiGetStateENGINES(int index); public static DIJOYSTATE2ENGINES LogiGetStateUnity(int index) { DIJOYSTATE2ENGINES ret = new DIJOYSTATE2ENGINES(); ret.rglSlider = new int[2]; ret.rgdwPOV = new uint[4]; ret.rgbButtons = new byte[128]; ret.rglVSlider = new int[2]; ret.rglASlider = new int[2]; ret.rglFSlider = new int[2]; try { ret = (DIJOYSTATE2ENGINES)Marshal.PtrToStructure(LogiGetStateENGINES(index), typeof(DIJOYSTATE2ENGINES)); } catch (System.ArgumentException) { Debug.Log("Exception catched"); } return ret; } [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiGetFriendlyProductName(int index, StringBuilder buffer, int bufferSize); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiIsConnected(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiIsDeviceConnected(int index, int deviceType); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiIsManufacturerConnected(int index, int manufacturerName); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiIsModelConnected(int index, int modelName); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiButtonTriggered(int index, int buttonNbr); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiButtonReleased(int index, int buttonNbr); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiButtonIsPressed(int index, int buttonNbr); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiGenerateNonLinearValues(int index, int nonLinCoeff); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGetNonLinearValue(int index, int inputValue); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiHasForceFeedback(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiIsPlaying(int index, int forceType); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlaySpringForce(int index, int offsetPercentage, int saturationPercentage, int coefficientPercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopSpringForce(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayConstantForce(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopConstantForce(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayDamperForce(int index, int coefficientPercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopDamperForce(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlaySideCollisionForce(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayFrontalCollisionForce(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayDirtRoadEffect(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopDirtRoadEffect(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayBumpyRoadEffect(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopBumpyRoadEffect(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlaySlipperyRoadEffect(int index, int magnitudePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopSlipperyRoadEffect(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlaySurfaceEffect(int index, int type, int magnitudePercentage, int period); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopSurfaceEffect(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayCarAirborne(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopCarAirborne(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlaySoftstopForce(int index, int usableRangePercentage); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiStopSoftstopForce(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiSetPreferredControllerProperties(LogiControllerPropertiesData properties); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiGetCurrentControllerProperties(int index, ref LogiControllerPropertiesData properties); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern int LogiGetShifterMode(int index); [DllImport("LogitechSteeringWheelEnginesWrapper", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)] public static extern bool LogiPlayLeds(int index, float currentRPM, float rpmFirstLedTurnsOn, float rpmRedLine); }
/** Implementation of the Client class. Handle socket message protocol for connections to Motion Service data streams. @file tools/sdk/cs/Client.cs @author Luke Tokheim, luke@motionnode.com @version 2.2 Copyright (c) 2015, Motion Workshop All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Net; using System.Net.Sockets; using System.Text; namespace Motion { namespace SDK { /** Implements a simple socket based data client and the Motion Service stream binary message protocol. Provide a simple interface to develop external applications that can read real-time Motion device data. This class only handles the socket connection and single message transfer. The @ref Format class implements interfaces to the service specific data formats. Example usage: @code //using Motion.SDK // ... try { // Open connection to a Motion Service on the localhost, // port 32079. Client client = new Client("", 32079); // This is application dependent. Use a loop to keep trying // to read data even after time outs. while (true) { // Wait until there is incoming data on the open connection, // timing out after 5 seconds. if (client.waitForData()) { // Read data samples in a loop. This will block by default // for 1 second. We can simply wait on an open connection // until a data sample comes in, or fall back to the // wait loop. while (true) { byte[] data = client.readData(data)); if (null == data) { break; } // Do something useful with the current real-time sample. // Probably use the Format class to generate a IDictionary // object of [int] => Format.(Preview|Sensor|Raw)Element // elements. } } } } catch (Exception e) { // The Client class with throw exceptions for any error // conditions. Even if the connection to the remote host fails. } @endcode */ public class Client { /** @param host IP address of remote host, the empty string defaults to "127.0.0.1" @param port port name of remote host @pre a service is accepting connections on the socket described by the host, port pair @post this client is connected to the remote service described by the host, port pair @throws std::runtime_error if the client connection fails for any reason */ public Client(String host, int port) { if (0 == host.Length) { host = DefaultAddress; } if (port < 0) { port = 0; } try { Socket socket = null; IPHostEntry ipHostInfo = Dns.GetHostEntry(host); foreach (IPAddress ipAddress in ipHostInfo.AddressList) { IPEndPoint ipe = new IPEndPoint(ipAddress, port); if (ProtocolFamily.InterNetworkV6.ToString() == ipe.AddressFamily.ToString()) { continue; } Socket tempSocket = new Socket( ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { socket = tempSocket; break; } } if ((null != socket) && socket.Connected) { socket.NoDelay = true; m_socket = socket; m_connected = true; // Read the first message. This is an XML // description of the service. m_socket.ReceiveTimeout = TimeOutWaitForData * 1000; byte[] message = receive(); if (message.Length > 0) { m_description = Encoding.UTF8.GetString(message, 0, message.Length); } } } catch (SocketException) { close(); } } /** Does not throw any exceptions. Close this client connection if it is open. */ ~Client() { close(); } /** Close the current client connection. @throws Exception if this client is not connected or the close procedure fails for any reason */ public void close() { if (null != m_socket) { try { m_socket.Shutdown(SocketShutdown.Both); m_socket.Close(); } catch (SocketException) { } m_socket = null; m_connected = false; m_description = ""; m_xml_string = ""; } } /** Returns true if the current connection is active. */ public bool isConnected() { if ((null != m_socket) && m_connected) { return true; } else { return false; } } /** Read a single sample of data from the open connection. This method will time out and return null if no data comes in after time_out_second seconds. @return a single sample of data, or null if the incoming data is invalid */ public byte[] readData(int time_out_second) { byte[] data = null; if (isConnected()) { // Set receive time out for this set of calls. if (time_out_second < 0) { if (TimeOutReadData * 1000 != m_socket.ReceiveTimeout) { m_socket.ReceiveTimeout = TimeOutReadData * 1000; } } else { m_socket.ReceiveTimeout = time_out_second * 1000; } byte[] message = receive(); // Consume any XML messages. Store the most recent one. if ((null != message) && (message.Length >= XMLMagic.Length) && (XMLMagic == Encoding.UTF8.GetString(message, 0, XMLMagic.Length))) { m_xml_string = Encoding.UTF8.GetString(message, 0, message.Length); message = receive(); } if ((null != message) && (message.Length > 0)) { data = message; } } return data; } /** @ref Client#readData(-1) */ public byte[] readData() { return readData(-1); } /** Wait until there is incoming data on this client connection and then returns true. @param time_out_second time out and return false after this many seconds, 0 value specifies no time out, negative value specifies default time out @pre this object has an open socket connection */ public bool waitForData(int time_out_second) { bool result = false; if (isConnected()) { // Set receive time out for this set of calls. if (time_out_second < 0) { if (TimeOutReadData * 1000 != m_socket.ReceiveTimeout) { m_socket.ReceiveTimeout = TimeOutWaitForData * 1000; } } else { m_socket.ReceiveTimeout = time_out_second * 1000; } byte[] message = receive(); if ((null != message) && (message.Length > 0)) { if ((message.Length >= XMLMagic.Length) && (XMLMagic == Encoding.UTF8.GetString(message, 0, XMLMagic.Length))) { m_xml_string = Encoding.UTF8.GetString(message, 0, message.Length); } result = true; } } return result; } /** @ref Client#waitForData(-1) */ public bool waitForData() { return waitForData(-1); } /** Write a variable length binary message to the socket link. @param time_out_second time out and return false after this many seconds, 0 value specifies no time out, negative value specifies default time out @pre this object has an open socket connection */ public bool writeData(byte[] data, int time_out_second) { bool result = false; if (isConnected() && (null != data) && (data.Length > 0)) { // Set receive time out for this set of calls. if (time_out_second < 0) { if (TimeOutWriteData * 1000 != m_socket.SendTimeout) { m_socket.SendTimeout = TimeOutWriteData * 1000; } } else { m_socket.SendTimeout = time_out_second * 1000; } byte[] header = BitConverter.GetBytes(IPAddress.HostToNetworkOrder(data.Length)); if (null != header) { byte[] buffer = new byte[header.Length + data.Length]; { System.Array.Copy(header, 0, buffer, 0, header.Length); System.Array.Copy(data, 0, buffer, header.Length, data.Length); } try { int num_sent = m_socket.Send(buffer); if (buffer.Length == num_sent) { result = true; } else if (0 == num_sent) { close(); } } catch (SocketException e) { if ((SocketError.TimedOut == e.SocketErrorCode) || (SocketError.WouldBlock == e.SocketErrorCode)) { // OK, we can try again later. } else { close(); } } } } return result; } /** @ref Client#writeData(byte[], int) */ public bool writeData(byte[] data) { return writeData(data, -1); } /** Create a byte[] from the input string and pass it along to the writeData method. @ref Client#writeData(byte[], int) */ public bool writeData(String message, int time_out_second) { return writeData(Encoding.ASCII.GetBytes(message), -1); } /** @ref Client#writeData(String, int) */ public bool writeData(String message) { return writeData(message, -1); } /** Accessor for the last XML message received. */ public String getXMLString() { return m_xml_string; } /** Accessor for the internal socket class. */ public Socket getSocket() { return m_socket; } /** Implements the actual message reading. First get the message length header integer = N. Then read N bytes of raw data and return them. */ private byte[] receive() { byte[] data = null; try { if (isConnected()) { byte[] buffer = new byte[sizeof(int)]; int message_length = 0; if (sizeof(int) == m_socket.Receive(buffer, sizeof(int), SocketFlags.None)) { // Network order message length integer header. message_length = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(buffer, 0)); } if ((message_length > 0) && (message_length <= MaximumMessageLength)) { // Read the binary message. data = new byte[message_length]; if (message_length != m_socket.Receive(data, message_length, SocketFlags.None)) { data = null; } } else if (0 == message_length) { close(); } } } catch (SocketException e) { if ((SocketError.TimedOut == e.SocketErrorCode) || (SocketError.WouldBlock == e.SocketErrorCode)) { data = null; } } return data; } /** Built in Socket class. Does most of the work. */ private Socket m_socket = null; /** Keep track of our own connection state that does supports timeouts. */ private Boolean m_connected = false; /** String description of the remote service. */ private String m_description = ""; /** Last XML message received. */ private String m_xml_string = ""; /** Default value, in seconds, for the socket receive time out in the Client#readData method. */ private const int TimeOutReadData = 1; /** Default value, in seconds, for the socket send time out in the Client#writeData method. */ private const int TimeOutWriteData = 1; /** Default value, in seconds, for the socket receive time out in the Client#waitForData method. Zero denotes blocking receive. */ private const int TimeOutWaitForData = 5; /** Set the address to this value if we get an empty string. */ private const String DefaultAddress = "127.0.0.1"; /** Detect XML message with the following header bytes. */ private const String XMLMagic = "<?xml"; /** Set a limit on the incoming message size. Assume that there is something wrong if a message is "too long". */ private const int MaximumMessageLength = 65535; } // class Client } // namespace SDK } // namespace Motion
using System; using System.Data; using System.Data.Common; using System.Linq; using Microsoft.Data.Sqlite; using WidgetScmDataAccess; using Xunit; namespace SqliteScmTest { public class UnitTest1 : IClassFixture<SampleScmDataFixture> { private SampleScmDataFixture fixture; private ScmContext context; public UnitTest1(SampleScmDataFixture fixture) { this.fixture = fixture; this.context = new ScmContext(fixture.Connection); } [Fact] public void Test1() { var parts = context.Parts; Assert.Equal(1, parts.Count()); var part = parts.First(); Assert.Equal("8289 L-shaped plate", part.Name); var inventory = context.Inventory; Assert.Equal(1, inventory.Count()); var item = inventory.First(); Assert.Equal(part.Id, item.PartTypeId); Assert.Equal(100, item.Count); Assert.Equal(10, item.OrderThreshold); Assert.Equal(item.Part.Id, item.PartTypeId); } [Fact] public void TestPartCommands() { var item = context.Inventory.First(); var startCount = item.Count; context.CreatePartCommand(new PartCommand() { PartTypeId = item.PartTypeId, PartCount = 10, Command = PartCountOperation.Add }); context.CreatePartCommand(new PartCommand() { PartTypeId = item.PartTypeId, PartCount = 5, Command = PartCountOperation.Remove }); var inventory = new Inventory(context); inventory.UpdateInventory(); Assert.Equal(startCount + 5, item.Count); } [Fact] public void TestUpdateInventory() { var item = context.Inventory.First(); var totalCount = item.Count; context.CreatePartCommand(new PartCommand() { PartTypeId = item.PartTypeId, PartCount = totalCount, Command = PartCountOperation.Remove }); var inventory = new Inventory(context); inventory.UpdateInventory(); var order = context.GetOrders().FirstOrDefault( o => o.PartTypeId == item.PartTypeId && !o.FulfilledDate.HasValue); Assert.NotNull(order); context.CreatePartCommand(new PartCommand() { PartTypeId = item.PartTypeId, PartCount = totalCount, Command = PartCountOperation.Add }); inventory.UpdateInventory(); Assert.Equal(totalCount, item.Count); } [Fact] public void TestCreateOrder() { var placedDate = DateTime.Now; var supplier = context.Suppliers.First(); var order = new Order() { PartTypeId = supplier.PartTypeId, Part = context.Parts.Single(p => p.Id == supplier.PartTypeId), SupplierId = supplier.Id, Supplier = supplier, PartCount = 10, PlacedDate = placedDate }; context.CreateOrder(order); var command = new SqliteCommand( @"SELECT Id FROM [Order] WHERE SupplierId=@supplierId AND PartTypeId=@partTypeId AND PlacedDate=@placedDate AND PartCount=10 AND FulfilledDate IS NULL", fixture.Connection); AddParameter(command, "@supplierId", supplier.Id); AddParameter(command, "@partTypeId", supplier.PartTypeId); AddParameter(command, "@placedDate", placedDate); var scalar = command.ExecuteScalar(); Assert.NotNull(scalar); Assert.IsType<long>(scalar); long orderId = (long)scalar; Assert.Equal(order.Id, orderId); command = new SqliteCommand( $@"SELECT Count(*) FROM SendEmailCommand WHERE [To]=@email AND Subject LIKE @subject", fixture.Connection); AddParameter(command, "@email", supplier.Email); AddParameter(command, "@subject", $"Order #{order.Id}%"); Assert.Equal(1, (long)command.ExecuteScalar()); } [Fact] public void TestCreateOrderTransaction() { var placedDate = DateTime.Now; var supplier = context.Suppliers.First(); var order = new Order() { PartTypeId = supplier.PartTypeId, SupplierId = supplier.Id, PartCount = 10, PlacedDate = placedDate }; Assert.Throws<NullReferenceException>(() => context.CreateOrder(order)); var command = new SqliteCommand( @"SELECT Count(*) FROM [Order] WHERE SupplierId=@supplierId AND PartTypeId=@partTypeId AND PlacedDate=@placedDate AND PartCount=10 AND FulfilledDate IS NULL", fixture.Connection); AddParameter(command, "@supplierId", supplier.Id); AddParameter(command, "@partTypeId", supplier.PartTypeId); AddParameter(command, "@placedDate", placedDate); Assert.Equal(0, (long)command.ExecuteScalar()); } [Fact] public void TestCreateOrderSysTx() { var placedDate = DateTime.Now; var supplier = context.Suppliers.First(); var order = new Order() { PartTypeId = supplier.PartTypeId, SupplierId = supplier.Id, PartCount = 10, PlacedDate = placedDate }; Assert.Throws<NullReferenceException>(() => context.CreateOrderSysTx(order)); var command = new SqliteCommand( @"SELECT Count(*) FROM [Order] WHERE SupplierId=@supplierId AND PartTypeId=@partTypeId AND PlacedDate=@placedDate AND PartCount=10 AND FulfilledDate IS NULL", fixture.Connection); AddParameter(command, "@supplierId", supplier.Id); AddParameter(command, "@partTypeId", supplier.PartTypeId); AddParameter(command, "@placedDate", placedDate); Assert.Equal(0, (long)command.ExecuteScalar()); } private void AddParameter(DbCommand cmd, string name, object value) { var p = cmd.CreateParameter(); if (value == null) throw new ArgumentNullException("value"); Type t = value.GetType(); if (t == typeof(int)) p.DbType = DbType.Int32; else if (t == typeof(string)) p.DbType = DbType.String; else if (t == typeof(DateTime)) p.DbType = DbType.DateTime; p.Direction = ParameterDirection.Input; p.ParameterName = name; p.Value = value; cmd.Parameters.Add(p); } } }
using Game.Lockstep; using Game.Network; using Game.Players; using Game.Utils; using LiteNetLib; using LiteNetLib.Utils; using System.Collections.Generic; namespace Presentation.Network { /// <summary> /// Monobehaviour class listening to network events regarding players. /// The static functions are thread safe in order to use them from the simulation thread, /// if needed. /// </summary> public class PlayerManager : SingletonMono<PlayerManager>, IResettable { private Dictionary<int, Player> players; private Player identity; private int totalPlayers; private int activePlayers; //lock for each field private object playersLock; private object countLock; private object idLock; #region Monobehaviour void Awake() { players = new Dictionary<int, Player>(); totalPlayers = 0; activePlayers = 0; playersLock = new object(); countLock = new object(); idLock = new object(); } void OnEnable() { GameClient.Register(NetPacketType.PlayerEnter, OnPlayerEnter); GameClient.Register(NetPacketType.PlayerLeave, OnPlayerLeave); GameClient.Register(NetPacketType.PlayerReady, OnPlayerReady); } void OnDisable() { GameClient.Unregister(NetPacketType.PlayerEnter, OnPlayerEnter); GameClient.Unregister(NetPacketType.PlayerLeave, OnPlayerLeave); GameClient.Unregister(NetPacketType.PlayerReady, OnPlayerReady); } void OnDestroy() { Reset(); } #endregion #region Resettable public void Reset() { players.Clear(); identity = null; totalPlayers = 0; activePlayers = 0; } #endregion #region Singleton public static Player Identity { get { lock (instance.idLock) { return instance.identity; } } } public static Dictionary<int, Player> Players { get { lock (instance.playersLock) { return instance.players; } } } public static int PlayerCount { get { return instance.TotalPlayersInternal; } } public static int ActivePlayerCount { get { return instance.ActivePlayersInternal; } } public static void SetIdentity(Player identity) { lock (instance.idLock) { instance.identity = identity; } } public static void Add(Player player) { lock (instance.playersLock) { instance.players.Add(player.ID, player); instance.TotalPlayersInternal++; instance.ActivePlayersInternal++; } } public static void Remove(Player player) { lock (instance.playersLock) { if (instance.players.Remove(player.ID)) { instance.TotalPlayersInternal--; instance.ActivePlayersInternal--; } } } public static void SetDisconnected(int playerID) { lock (instance.playersLock) { Player player = null; if (instance.players.TryGetValue(playerID, out player)) { player.SetActive(false); instance.ActivePlayersInternal--; } } } #endregion #region Event Handlers /// <summary> /// Handler for "player enter" packets. /// </summary> /// <param name="peer">server</param> /// <param name="args">raw data containing the player packet</param> private void OnPlayerEnter(NetPeer peer, NetEventArgs args) { if (GameClient.CurrentState == ClientState.Game) return; PacketPlayerEnter message = PacketBase.Read<PacketPlayerEnter>((NetDataReader)(args.Data)); if (message.Player.ID == identity.ID) { SetIdentity(message.Player); } Add(message.Player); NetEventManager.Trigger(NetEventType.PlayerEnter, args); } /// <summary> /// Handler for 'player leaving' packets. /// Removes the player if the game is not started yet, otherwise mark him as 'disconnected'. /// </summary> /// <param name="peer">server</param> /// <param name="args">wrapper around raw data containing the packet</param> private void OnPlayerLeave(NetPeer peer, NetEventArgs args) { PacketPlayerEnter message = PacketBase.Read<PacketPlayerEnter>((NetDataReader)(args.Data)); if (message.Player.ID == Identity.ID) { UnityEngine.Debug.LogWarning("Dafuq, I can't leave myself!"); return; } if (GameClient.CurrentState != ClientState.Game) { Remove(message.Player); } else { SetDisconnected(message.Player.ID); LockstepLogic.Instance.UpdatePlayersCount(activePlayers, message.Player.ID); } NetEventManager.Trigger(NetEventType.PlayerLeave, args); } private void OnPlayerReady(NetPeer peer, NetEventArgs args) { if (GameClient.CurrentState == ClientState.Game) return; PacketPlayerReady message = PacketBase.Read<PacketPlayerReady>((NetDataReader)(args.Data)); Player player = null; if (players.TryGetValue(message.Sender, out player)) { player.SetReady(message.Value); NetEventManager.Trigger(NetEventType.PlayerReady, args); } } #endregion #region Private Helper functions private int TotalPlayersInternal { get { lock (countLock) { return totalPlayers; } } set { lock (countLock) { totalPlayers = value; } } } private int ActivePlayersInternal { get { return activePlayers; } set { activePlayers = value; } } #endregion } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Data; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.Geometry; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SpatialAnalysis.Miscellaneous; namespace SpatialAnalysis.Agents.MandatoryScenario { /// <summary> /// This class includes the mechanism for updating of the agent's state in mandatory and is designed for use in training process. /// </summary> /// <seealso cref="SpatialAnalysis.Agents.IAgent" /> public class MandatoryScenarioTrainer: IAgent { /// <summary> /// Updates the agent. /// </summary> /// <param name="newState">The new state.</param> public void UpdateAgent(StateBase newState) { this.CurrentState = newState; this.TotalWalkTime = 0; this.EdgeCollisionState = null; while (this.TotalWalkTime < this.Duration) { this.TimeStep = this.FixedTimeStep; this.TotalWalkTime += this.FixedTimeStep; while (this.TimeStep != 0.0d) { this.TimeStepUpdate(); } } } /// <summary> /// Initializes a new instance of the <see cref="MandatoryScenarioTrainer"/> class. /// </summary> /// <param name="host">The host.</param> /// <param name="fixedTimeStep">The fixed time step.</param> /// <param name="duration">The duration.</param> /// <param name="activity">The activity.</param> public MandatoryScenarioTrainer (OSMDocument host, double fixedTimeStep, double duration, Activity activity) { this.Duration = duration; this.FixedTimeStep = fixedTimeStep / 1000.0d; this._random = new Random(DateTime.Now.Millisecond); this._cellularFloor = host.cellularFloor; this.BarrierRepulsionRange = host.Parameters[AgentParameters.GEN_BarrierRepulsionRange.ToString()].Value; this.RepulsionChangeRate = host.Parameters[AgentParameters.GEN_MaximumRepulsion.ToString()].Value; this.BarrierFriction = host.Parameters[AgentParameters.GEN_BarrierFriction.ToString()].Value; this.BodyElasticity = host.Parameters[AgentParameters.GEN_AgentBodyElasticity.ToString()].Value; this.AccelerationMagnitude = host.Parameters[AgentParameters.GEN_AccelerationMagnitude.ToString()].Value; this.AngularVelocity = host.Parameters[AgentParameters.GEN_AngularVelocity.ToString()].Value; this.BodySize = host.Parameters[AgentParameters.GEN_BodySize.ToString()].Value; this.VelocityMagnitude = host.Parameters[AgentParameters.GEN_VelocityMagnitude.ToString()].Value; this.CurrentActivity = activity; } private Random _random { get; set; } private CellularFloor _cellularFloor { get; set; } /// <summary> /// Gets or sets the current activity. /// </summary> /// <value>The current activity.</value> public Activity CurrentActivity { get; set; } /// <summary> /// Gets or sets the body elasticity. /// </summary> /// <value>The body elasticity.</value> public double BodyElasticity { get; set; } /// <summary> /// Gets or sets the barrier friction. /// </summary> /// <value>The barrier friction.</value> public double BarrierFriction { get; set; } /// <summary> /// Gets or sets the barrier repulsion range. /// </summary> /// <value>The barrier repulsion range.</value> public double BarrierRepulsionRange { get; set; } /// <summary> /// Gets or sets the repulsion change rate. /// </summary> /// <value>The repulsion change rate.</value> public double RepulsionChangeRate { get; set; } /// <summary> /// Gets or sets the angular velocity. /// </summary> /// <value>The angular velocity.</value> public double AngularVelocity { get; set; } /// <summary> /// Gets or sets the size of the body. /// </summary> /// <value>The size of the body.</value> public double BodySize { get; set; } /// <summary> /// Gets or sets the velocity magnitude. /// </summary> /// <value>The velocity magnitude.</value> public double VelocityMagnitude { get; set; } /// <summary> /// Gets or sets the acceleration magnitude. /// </summary> /// <value>The acceleration magnitude.</value> public double AccelerationMagnitude { get; set; } /// <summary> /// Gets or sets the current state of the agent. /// </summary> /// <value>The state of the current.</value> public StateBase CurrentState { get; set; } /// <summary> /// Gets or sets the occupancy duration per hour. /// </summary> /// <value>The duration.</value> public double Duration { get; set; } /// <summary> /// Gets or sets the time-step. /// </summary> /// <value>The time step.</value> public double TimeStep { get; set; } /// <summary> /// Gets or sets the fixed time-step. /// </summary> /// <value>The fixed time step.</value> public double FixedTimeStep { get; set; } /// <summary> /// Gets or sets the total walk time. /// </summary> /// <value>The total walk time.</value> public double TotalWalkTime { get; set; } /// <summary> /// Gets or sets the state of the edge collision. /// </summary> /// <value>The state of the edge collision.</value> public CollisionAnalyzer EdgeCollisionState { get; set; } /// <summary> /// Determines whether the agent should stops and orient towards the focal point of the activity. /// </summary> /// <returns><c>true</c> if the agent is in the destination, <c>false</c> otherwise.</returns> public bool StopAndOrientCheck() { UV direction = this.CurrentActivity.DefaultState.Location - this.CurrentState.Location; if (direction.GetLengthSquared() == 0.0d) { return true; } if (UV.GetLengthSquared(this.CurrentState.Location, this.CurrentActivity.DefaultState.Location) < this.BodySize || UV.GetLengthSquared(this.CurrentState.Location, this.CurrentActivity.DefaultState.Location) < this._cellularFloor.CellSize) { return true; } double directionLength = direction.GetLength(); direction /= directionLength; var velocity_x = direction * (direction.DotProduct(this.CurrentState.Velocity)); var velocity_y = this.CurrentState.Velocity - velocity_x; //both velocity_x and velocity_y should become zeros var velocity_x_length = velocity_x.GetLength(); var tx = velocity_x_length / this.AccelerationMagnitude; velocity_x /= velocity_x_length; var velocity_y_length = velocity_y.GetLength(); //when velocity_y is zero var ty = velocity_y_length / this.AccelerationMagnitude; velocity_y /= velocity_y_length; //where velocity_y is zero var location1 = this.CurrentState.Location + (0.5 * this.AccelerationMagnitude * ty * ty) * velocity_y + ty * velocity_x * velocity_x_length; //where velocity_x is zero var location2 = location1 + (0.5 * this.AccelerationMagnitude * tx * tx) * velocity_x; return directionLength * directionLength < UV.GetLengthSquared(this.CurrentState.Location, location2); } /// <summary> /// Sets the velocity vector when the agent is in the destination area and needs to stop and then orient. /// </summary> /// <returns>UV.</returns> public UV StopAndOrientVelocity() { //decomposing the velocity to its components towards center (x) and perpendicular to it (y) UV direction = this.CurrentActivity.DefaultState.Location - this.CurrentState.Location; if (direction.GetLengthSquared() != 0.0d) { direction.Unitize(); } else { if (this.CurrentState.Velocity.GetLengthSquared() > this.AccelerationMagnitude * this.TimeStep * this.AccelerationMagnitude * this.TimeStep) { double velocityMagnitude = this.CurrentState.Velocity.GetLength(); var nextVelocity = this.CurrentState.Velocity - this.AccelerationMagnitude * this.TimeStep * (this.CurrentState.Velocity / velocityMagnitude); return nextVelocity; } else { return UV.ZeroBase.Copy(); } } var velocity_xDir = direction * (direction.DotProduct(this.CurrentState.Velocity)); var velocity_yDir = this.CurrentState.Velocity - velocity_xDir; //calculating the length of the velocity components and unitizing them var velocity_x_length = velocity_xDir.GetLength(); if (velocity_x_length != 0.0d) { velocity_xDir /= velocity_x_length; } var velocity_y_length = velocity_yDir.GetLength(); if (velocity_y_length != 0.0d) { velocity_yDir /= velocity_y_length; } //creating a copy of the velocity of the current state var velocity = this.CurrentState.Velocity.Copy(); //checking if exerting the acceleration can stop the perpendicular component of the velocity if (velocity_y_length >= this.AccelerationMagnitude * this.TimeStep) { //all of the the acceleration force in the timestep is assigned to stop the perpendicular component of the velocity velocity -= this.TimeStep * this.AccelerationMagnitude * velocity_yDir; return velocity; } else { //finding part of the timestep when the excursion of the acceleration force stops the the perpendicular component of the velocity //velocity_y_length = this.AccelerationMagnitude * timeStep_y; double timeStep_y = velocity_y_length / this.AccelerationMagnitude; //update the velocity and location after first portion of the timestep var velocity1 = velocity - timeStep_y * this.AccelerationMagnitude * velocity_yDir; UV location_y = this.CurrentState.Location + velocity1 * timeStep_y; //calculating the remainder of the timestep double timeStep_x = this.TimeStep - timeStep_y; //checking the direction of the velocity agenst x direction var sign = Math.Sign(direction.DotProduct(velocity_xDir)); if (sign == 1)//moving towards destination { //the time needed to make the velocity zero with the same acceleration double t = velocity_x_length / this.AccelerationMagnitude; //traveled distance within this time double traveledDistance = 0.5d * this.AccelerationMagnitude * t * t; double distance = location_y.DistanceTo(this.CurrentActivity.DefaultState.Location); //if traveled distance is larger than the current distance use acceleration to adjust velocity if (traveledDistance >= distance) { velocity = velocity1 - timeStep_x * this.AccelerationMagnitude * velocity_xDir; } else//do not excert velocity to change the celocity { velocity = velocity1 + timeStep_x * this.AccelerationMagnitude * velocity_xDir; } } else if (sign == -1)//exert the acceleration force to change the direction { velocity = velocity1 - timeStep_x * this.AccelerationMagnitude * velocity_xDir; } else if (sign == 0) //which means velocity_x_length =0 { velocity = velocity1 + timeStep_x * this.AccelerationMagnitude * direction; } } return velocity; } /// <summary> /// Loads the repulsion vector's magnitude. /// </summary> /// <returns>System.Double.</returns> public double LoadRepulsionMagnitude() { return Function.BezierRepulsionMethod(this.EdgeCollisionState.DistanceToBarrier); } /// <summary> /// Updates the time-step. /// </summary> /// <exception cref="System.ArgumentException"> /// Collision not found /// or /// The proportion of timestep before collision is out of range: " + collision.TimeStepRemainderProportion.ToString() /// </exception> /// <exception cref="System.ArgumentNullException"> /// Collision Analyzer failed! /// or /// Collision Analyzer failed! /// </exception> public void TimeStepUpdate() { // make a copy of current state var newState = this.CurrentState.Copy(); var previousState = this.CurrentState.Copy(); // direction update UV direction = this.CurrentState.Direction; try { var filed_direction = this.CurrentActivity.Differentiate(this.CurrentState.Location); if (filed_direction != null) { direction = filed_direction; } } catch (Exception error) { throw new ArgumentException(error.Report()); } direction.Unitize(); #region update barrier relation factors UV repulsionForce = new UV(0.0, 0.0); // this condition is for the first time only when walking begins if (this.EdgeCollisionState == null) { this.EdgeCollisionState = CollisionAnalyzer.GetCollidingEdge(newState.Location, this._cellularFloor, BarrierType.Field); } if (this.EdgeCollisionState != null) { //only if the barrier is visible to the agent the repulsion force will be applied if (this.EdgeCollisionState.NormalizedRepulsion.DotProduct(newState.Direction) >= 0.0d)//this.VisibilityCosineFactor) { ////render agent color //this.Fill = VisualAgentMandatoryScenario.OutsideRange; //this.Stroke = VisualAgentMandatoryScenario.OutsideRange; } else { double repulsionMagnitude = this.LoadRepulsionMagnitude(); if (repulsionMagnitude != 0.0d) { ////render agent color //this.Fill = VisualAgentMandatoryScenario.InsideRange; //this.Stroke = VisualAgentMandatoryScenario.InsideRange; //calculate repulsion force repulsionForce = this.EdgeCollisionState.NormalizedRepulsion * repulsionMagnitude; } else { ////render agent color //this.Fill = VisualAgentMandatoryScenario.OutsideRange; //this.Stroke = VisualAgentMandatoryScenario.OutsideRange; } } } else { throw new ArgumentNullException("Collision Analyzer failed!"); } #endregion // find Acceleration force and update velocity UV acceleration = new UV(0, 0); acceleration += this.AccelerationMagnitude * direction + repulsionForce; newState.Velocity += acceleration * this.TimeStep; //check velocity magnitude against the cap if (newState.Velocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { newState.Velocity.Unitize(); newState.Velocity *= this.VelocityMagnitude; } //update location var location = newState.Location + this.TimeStep * newState.Velocity; newState.Location = location; //update the location of the agent in the transformation matrix //this._matrix.OffsetX = newState.Location.U; //this._matrix.OffsetY = newState.Location.V; // update direction double deltaAngle = this.AngularVelocity * this.TimeStep; Axis axis = new Axis(this.CurrentState.Direction, direction, deltaAngle); newState.Direction = axis.V_Axis; //update state newState.Direction.Unitize(); //checking for collisions var newEdgeCollisionState = CollisionAnalyzer.GetCollidingEdge(newState.Location, this._cellularFloor, BarrierType.Field); if (newEdgeCollisionState == null) { this.EdgeCollisionState = CollisionAnalyzer.GetCollidingEdge(newState.Location, this._cellularFloor, BarrierType.Field); throw new ArgumentNullException("Collision Analyzer failed!"); } else { if (this.EdgeCollisionState.DistanceToBarrier > this.BodySize / 2 && newEdgeCollisionState.DistanceToBarrier < this.BodySize / 2) { var collision = CollisionAnalyzer.GetCollision(this.EdgeCollisionState, newEdgeCollisionState, this.BodySize / 2, OSMDocument.AbsoluteTolerance); if (collision == null) { throw new ArgumentException("Collision not found"); } else { if (collision.TimeStepRemainderProportion > 1.0 || collision.TimeStepRemainderProportion < 0.0d) { throw new ArgumentException("The proportion of timestep before collision is out of range: " + collision.TimeStepRemainderProportion.ToString()); } else { //update for partial timestep //update timestep double newTimeStep = this.TimeStep * collision.TimeStepRemainderProportion; this.TimeStep -= newTimeStep; // update location newState.Location = collision.CollisionPoint; //this._matrix.OffsetX = newState.Location.U; //this._matrix.OffsetY = newState.Location.V; // update velocity var velocity = this.CurrentState.Velocity + newTimeStep * acceleration; if (velocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { velocity.Unitize(); velocity *= this.VelocityMagnitude; } //decompose velocity UV velocityVerticalComponent = newEdgeCollisionState.NormalizedRepulsion * (newEdgeCollisionState.NormalizedRepulsion.DotProduct(velocity)); double velocityVerticalComponentLength = velocityVerticalComponent.GetLength(); UV velocityHorizontalComponent = velocity - velocityVerticalComponent; double velocityHorizontalComponentLength = velocityHorizontalComponent.GetLength(); //decompose acceleration UV accelerationVerticalComponent = newEdgeCollisionState.NormalizedRepulsion * (newEdgeCollisionState.NormalizedRepulsion.DotProduct(acceleration)); // elasticity UV ve = this.BodyElasticity * velocityVerticalComponent; //friction double f1 = this.BarrierFriction * velocityVerticalComponentLength; double f2 = velocityHorizontalComponentLength; UV vf = velocityHorizontalComponent - Math.Min(f1, f2) * velocityHorizontalComponent / velocityHorizontalComponentLength; //update velocity var adjustedVelocity = vf - ve - newTimeStep * accelerationVerticalComponent; if (adjustedVelocity.GetLengthSquared() > this.VelocityMagnitude * this.VelocityMagnitude) { adjustedVelocity.Unitize(); adjustedVelocity *= this.VelocityMagnitude; } newState.Velocity = adjustedVelocity; //update direction deltaAngle = this.AngularVelocity * newTimeStep; axis = new Axis(this.CurrentState.Direction, direction, deltaAngle); newState.Direction = axis.V_Axis; //update state newEdgeCollisionState.DistanceToBarrier = this.BodySize / 2; newEdgeCollisionState.Location = newState.Location; this.EdgeCollisionState = newEdgeCollisionState; this.CurrentState = newState; } } } else { //update state for the full timestep length this.EdgeCollisionState = newEdgeCollisionState; this.CurrentState = newState; this.TimeStep = 0.0d; } } } /// <summary> /// Gets or sets the visibility angle. /// </summary> /// <value>The visibility angle.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double VisibilityAngle { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the visibility cosine factor. /// </summary> /// <value>The visibility cosine factor.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double VisibilityCosineFactor { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the walked total length. /// </summary> /// <value>The total length of the walked.</value> /// <exception cref="System.NotImplementedException"> /// </exception> public double TotalWalkedLength { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } } }
using System; using System.Runtime.InteropServices; using System.Security; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: This is the implementation of the DataCollector /// functionality. To enable safe access to the DataCollector from /// untrusted code, there is one thread-local instance of this structure /// per thread. The instance must be Enabled before any data is written to /// it. The instance must be Finished before the data is passed to /// EventWrite. The instance must be Disabled before the arrays referenced /// by the pointers are freed or unpinned. /// </summary> [SecurityCritical] internal unsafe struct DataCollector { [ThreadStatic] internal static DataCollector ThreadInstance; private byte* scratchEnd; private EventSource.EventData* datasEnd; private GCHandle* pinsEnd; private EventSource.EventData* datasStart; private byte* scratch; private EventSource.EventData* datas; private GCHandle* pins; private byte[] buffer; private int bufferPos; private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this. private bool writingScalars; internal void Enable( byte* scratch, int scratchSize, EventSource.EventData* datas, int dataCount, GCHandle* pins, int pinCount) { this.datasStart = datas; this.scratchEnd = scratch + scratchSize; this.datasEnd = datas + dataCount; this.pinsEnd = pins + pinCount; this.scratch = scratch; this.datas = datas; this.pins = pins; this.writingScalars = false; } internal void Disable() { this = new DataCollector(); } /// <summary> /// Completes the list of scalars. Finish must be called before the data /// descriptor array is passed to EventWrite. /// </summary> /// <returns> /// A pointer to the next unused data descriptor, or datasEnd if they were /// all used. (Descriptors may be unused if a string or array was null.) /// </returns> internal EventSource.EventData* Finish() { this.ScalarsEnd(); return this.datas; } internal void AddScalar(void* value, int size) { var pb = (byte*)value; if (this.bufferNesting == 0) { var scratchOld = this.scratch; var scratchNew = scratchOld + size; if (this.scratchEnd < scratchNew) { #if PROJECTN throw new IndexOutOfRangeException(SR.GetResourceString("EventSource_AddScalarOutOfRange", null)); #else throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_AddScalarOutOfRange")); #endif } this.ScalarsBegin(); this.scratch = scratchNew; for (int i = 0; i != size; i++) { scratchOld[i] = pb[i]; } } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); for (int i = 0; i != size; i++, oldPos++) { this.buffer[oldPos] = pb[i]; } } } internal void AddBinary(string value, int size) { if (size > ushort.MaxValue) { size = ushort.MaxValue - 1; } if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&size, 2); if (size != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); fixed (void* p = value) { Marshal.Copy((IntPtr)p, this.buffer, oldPos, size); } } } } internal void AddBinary(Array value, int size) { this.AddArray(value, size, 1); } internal void AddArray(Array value, int length, int itemSize) { if (length > ushort.MaxValue) { length = ushort.MaxValue; } var size = length * itemSize; if (this.bufferNesting != 0) { this.EnsureBuffer(size + 2); } this.AddScalar(&length, 2); if (length != 0) { if (this.bufferNesting == 0) { this.ScalarsEnd(); this.PinArray(value, size); } else { var oldPos = this.bufferPos; this.bufferPos = checked(this.bufferPos + size); this.EnsureBuffer(); Buffer.BlockCopy(value, 0, this.buffer, oldPos, size); } } } /// <summary> /// Marks the start of a non-blittable array or enumerable. /// </summary> /// <returns>Bookmark to be passed to EndBufferedArray.</returns> internal int BeginBufferedArray() { this.BeginBuffered(); this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable) return this.bufferPos; } /// <summary> /// Marks the end of a non-blittable array or enumerable. /// </summary> /// <param name="bookmark">The value returned by BeginBufferedArray.</param> /// <param name="count">The number of items in the array.</param> internal void EndBufferedArray(int bookmark, int count) { this.EnsureBuffer(); this.buffer[bookmark - 2] = unchecked((byte)count); this.buffer[bookmark - 1] = unchecked((byte)(count >> 8)); this.EndBuffered(); } /// <summary> /// Marks the start of dynamically-buffered data. /// </summary> internal void BeginBuffered() { this.ScalarsEnd(); this.bufferNesting += 1; } /// <summary> /// Marks the end of dynamically-buffered data. /// </summary> internal void EndBuffered() { this.bufferNesting -= 1; if (this.bufferNesting == 0) { /* TODO (perf): consider coalescing adjacent buffered regions into a single buffer, similar to what we're already doing for adjacent scalars. In addition, if a type contains a buffered region adjacent to a blittable array, and the blittable array is small, it would be more efficient to buffer the array instead of pinning it. */ this.EnsureBuffer(); this.PinArray(this.buffer, this.bufferPos); this.buffer = null; this.bufferPos = 0; } } private void EnsureBuffer() { var required = this.bufferPos; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void EnsureBuffer(int additionalSize) { var required = this.bufferPos + additionalSize; if (this.buffer == null || this.buffer.Length < required) { this.GrowBuffer(required); } } private void GrowBuffer(int required) { var newSize = this.buffer == null ? 64 : this.buffer.Length; do { newSize *= 2; } while (newSize < required); Array.Resize(ref this.buffer, newSize); } private void PinArray(object value, int size) { var pinsTemp = this.pins; if (this.pinsEnd <= pinsTemp) { #if PROJECTN throw new IndexOutOfRangeException(SR.GetResourceString("EventSource_PinArrayOutOfRange", null)); #else throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_PinArrayOutOfRange")); #endif } var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { #if PROJECTN throw new IndexOutOfRangeException(SR.GetResourceString("EventSource_DataDescriptorsOutOfRange", null)); #else throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_DataDescriptorsOutOfRange")); #endif } this.pins = pinsTemp + 1; this.datas = datasTemp + 1; *pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned); datasTemp->m_Ptr = (long)(ulong)(UIntPtr)(void*)pinsTemp->AddrOfPinnedObject(); datasTemp->m_Size = size; } private void ScalarsBegin() { if (!this.writingScalars) { var datasTemp = this.datas; if (this.datasEnd <= datasTemp) { #if PROJECTN throw new IndexOutOfRangeException(SR.GetResourceString("EventSource_DataDescriptorsOutOfRange", null)); #else throw new IndexOutOfRangeException(Environment.GetResourceString("EventSource_DataDescriptorsOutOfRange")); #endif } datasTemp->m_Ptr = (long)(ulong)(UIntPtr)this.scratch; this.writingScalars = true; } } private void ScalarsEnd() { if (this.writingScalars) { var datasTemp = this.datas; datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr)); this.datas = datasTemp + 1; this.writingScalars = false; } } } }
// <copyright file="SafariDriverServer.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Permissions; using System.Text; using System.Threading; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; using OpenQA.Selenium.Safari.Internal; namespace OpenQA.Selenium.Safari { /// <summary> /// Provides the WebSockets server for communicating with the Safari extension. /// </summary> public class SafariDriverServer : ICommandServer { private WebSocketServer webSocketServer; private Queue<SafariDriverConnection> connections = new Queue<SafariDriverConnection>(); private Uri serverUri; private string temporaryDirectoryPath; private string safariExecutableLocation; private Process safariProcess; private SafariDriverConnection connection; /// <summary> /// Initializes a new instance of the <see cref="SafariDriverServer"/> class using the specified options. /// </summary> /// <param name="options">The <see cref="SafariOptions"/> defining the browser settings.</param> public SafariDriverServer(SafariOptions options) { if (options == null) { throw new ArgumentNullException("options", "options must not be null"); } int webSocketPort = options.Port; if (webSocketPort == 0) { webSocketPort = PortUtilities.FindFreePort(); } this.webSocketServer = new WebSocketServer(webSocketPort, "ws://localhost/wd"); this.webSocketServer.Opened += new EventHandler<ConnectionEventArgs>(this.ServerOpenedEventHandler); this.webSocketServer.Closed += new EventHandler<ConnectionEventArgs>(this.ServerClosedEventHandler); this.webSocketServer.StandardHttpRequestReceived += new EventHandler<StandardHttpRequestReceivedEventArgs>(this.ServerStandardHttpRequestReceivedEventHandler); this.serverUri = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}/", webSocketPort.ToString(CultureInfo.InvariantCulture))); if (string.IsNullOrEmpty(options.SafariLocation)) { this.safariExecutableLocation = GetDefaultSafariLocation(); } else { this.safariExecutableLocation = options.SafariLocation; } } /// <summary> /// Starts the server. /// </summary> public void Start() { this.webSocketServer.Start(); string connectFileName = this.PrepareConnectFile(); this.LaunchSafariProcess(connectFileName); this.connection = this.WaitForConnection(TimeSpan.FromSeconds(45)); this.DeleteConnectFile(); if (this.connection == null) { throw new WebDriverException("Did not receive a connection from the Safari extension. Please verify that it is properly installed and is the proper version."); } } /// <summary> /// Sends a command to the server. /// </summary> /// <param name="commandToSend">The <see cref="Command"/> to send.</param> /// <returns>The command <see cref="Response"/>.</returns> public Response SendCommand(Command commandToSend) { return this.connection.Send(commandToSend); } /// <summary> /// Waits for a connection to be established with the server by the Safari browser extension. /// </summary> /// <param name="timeout">A <see cref="TimeSpan"/> containing the amount of time to wait for the connection.</param> /// <returns>A <see cref="SafariDriverConnection"/> representing the connection to the browser.</returns> public SafariDriverConnection WaitForConnection(TimeSpan timeout) { SafariDriverConnection foundConnection = null; DateTime end = DateTime.Now.Add(timeout); while (this.connections.Count == 0 && DateTime.Now < end) { Thread.Sleep(250); } if (this.connections.Count > 0) { foundConnection = this.connections.Dequeue(); } return foundConnection; } /// <summary> /// Releases all resources used by the <see cref="SafariDriverServer"/>. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="SafariDriverServer"/> and optionally /// releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { this.webSocketServer.Dispose(); if (this.safariProcess != null) { this.CloseSafariProcess(); this.safariProcess.Dispose(); } } } private static string GetDefaultSafariLocation() { string safariPath = string.Empty; if (Environment.OSVersion.Platform == PlatformID.Win32NT) { // Safari remains a 32-bit application. Use a hack to look for it // in the 32-bit program files directory. If a 64-bit version of // Safari for Windows is released, this needs to be revisited. string programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); if (Directory.Exists(programFilesDirectory + " (x86)")) { programFilesDirectory += " (x86)"; } safariPath = Path.Combine(programFilesDirectory, Path.Combine("Safari", "safari.exe")); } else { safariPath = "/Applications/Safari.app/Contents/MacOS/Safari"; } return safariPath; } [SecurityPermission(SecurityAction.Demand)] private void LaunchSafariProcess(string initialPage) { this.safariProcess = new Process(); this.safariProcess.StartInfo.FileName = this.safariExecutableLocation; this.safariProcess.StartInfo.Arguments = string.Format(CultureInfo.InvariantCulture, "\"{0}\"", initialPage); this.safariProcess.Start(); } [SecurityPermission(SecurityAction.Demand)] private void CloseSafariProcess() { if (this.safariProcess != null && !this.safariProcess.HasExited) { this.safariProcess.Kill(); while (!this.safariProcess.HasExited) { Thread.Sleep(250); } } } private string PrepareConnectFile() { string directoryName = FileUtilities.GenerateRandomTempDirectoryName("SafariDriverConnect.{0}"); this.temporaryDirectoryPath = Path.Combine(Path.GetTempPath(), directoryName); string tempFileName = Path.Combine(this.temporaryDirectoryPath, "connect.html"); string contents = string.Format(CultureInfo.InvariantCulture, "<!DOCTYPE html><script>window.location = '{0}';</script>", this.serverUri.ToString()); Directory.CreateDirectory(this.temporaryDirectoryPath); using (FileStream stream = File.Create(tempFileName)) { stream.Write(Encoding.UTF8.GetBytes(contents), 0, Encoding.UTF8.GetByteCount(contents)); } return tempFileName; } private void DeleteConnectFile() { Directory.Delete(this.temporaryDirectoryPath, true); } private void ServerOpenedEventHandler(object sender, ConnectionEventArgs e) { this.connections.Enqueue(new SafariDriverConnection(e.Connection)); } private void ServerClosedEventHandler(object sender, ConnectionEventArgs e) { } private void ServerStandardHttpRequestReceivedEventHandler(object sender, StandardHttpRequestReceivedEventArgs e) { const string PageSource = @"<!DOCTYPE html> <script> window.onload = function() {{ window.postMessage({{ 'type': 'connect', 'origin': 'webdriver', 'url': 'ws://localhost:{0}/wd' }}, '*'); }}; </script>"; string redirectPage = string.Format(CultureInfo.InvariantCulture, PageSource, this.webSocketServer.Port.ToString(CultureInfo.InvariantCulture)); StringBuilder builder = new StringBuilder(); builder.AppendLine("HTTP/1.1 200"); builder.AppendLine("Content-Length: " + redirectPage.Length.ToString(CultureInfo.InvariantCulture)); builder.AppendLine("Connection:close"); builder.AppendLine(); builder.AppendLine(redirectPage); e.Connection.SendRaw(builder.ToString()); } } }
/* * 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.Portable.IO { using System; using System.IO; using System.Text; /// <summary> /// Portable onheap stream. /// </summary> internal unsafe class PortableHeapStream : PortableAbstractStream { /** Data array. */ protected byte[] Data; /// <summary> /// Constructor. /// </summary> /// <param name="cap">Initial capacity.</param> public PortableHeapStream(int cap) { Data = new byte[cap]; } /// <summary> /// Constructor. /// </summary> /// <param name="data">Data array.</param> public PortableHeapStream(byte[] data) { Data = data; } /** <inheritdoc /> */ public override void WriteByte(byte val) { int pos0 = EnsureWriteCapacityAndShift(1); Data[pos0] = val; } /** <inheritdoc /> */ public override byte ReadByte() { int pos0 = EnsureReadCapacityAndShift(1); return Data[pos0]; } /** <inheritdoc /> */ public override void WriteByteArray(byte[] val) { int pos0 = EnsureWriteCapacityAndShift(val.Length); fixed (byte* data0 = Data) { WriteByteArray0(val, data0 + pos0); } } /** <inheritdoc /> */ public override byte[] ReadByteArray(int cnt) { int pos0 = EnsureReadCapacityAndShift(cnt); fixed (byte* data0 = Data) { return ReadByteArray0(cnt, data0 + pos0); } } /** <inheritdoc /> */ public override void WriteBoolArray(bool[] val) { int pos0 = EnsureWriteCapacityAndShift(val.Length); fixed (byte* data0 = Data) { WriteBoolArray0(val, data0 + pos0); } } /** <inheritdoc /> */ public override bool[] ReadBoolArray(int cnt) { int pos0 = EnsureReadCapacityAndShift(cnt); fixed (byte* data0 = Data) { return ReadBoolArray0(cnt, data0 + pos0); } } /** <inheritdoc /> */ public override void WriteShort(short val) { int pos0 = EnsureWriteCapacityAndShift(2); fixed (byte* data0 = Data) { WriteShort0(val, data0 + pos0); } } /** <inheritdoc /> */ public override short ReadShort() { int pos0 = EnsureReadCapacityAndShift(2); fixed (byte* data0 = Data) { return ReadShort0(data0 + pos0); } } /** <inheritdoc /> */ public override void WriteShortArray(short[] val) { int cnt = val.Length << 1; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteShortArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override short[] ReadShortArray(int cnt) { int cnt0 = cnt << 1; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadShortArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override void WriteCharArray(char[] val) { int cnt = val.Length << 1; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteCharArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override char[] ReadCharArray(int cnt) { int cnt0 = cnt << 1; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadCharArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override void WriteInt(int val) { int pos0 = EnsureWriteCapacityAndShift(4); fixed (byte* data0 = Data) { WriteInt0(val, data0 + pos0); } } /** <inheritdoc /> */ public override void WriteInt(int writePos, int val) { EnsureWriteCapacity(writePos + 4); fixed (byte* data0 = Data) { WriteInt0(val, data0 + writePos); } } /** <inheritdoc /> */ public override int ReadInt() { int pos0 = EnsureReadCapacityAndShift(4); fixed (byte* data0 = Data) { return ReadInt0(data0 + pos0); } } /** <inheritdoc /> */ public override void WriteIntArray(int[] val) { int cnt = val.Length << 2; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteIntArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override int[] ReadIntArray(int cnt) { int cnt0 = cnt << 2; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadIntArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override void WriteFloatArray(float[] val) { int cnt = val.Length << 2; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteFloatArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override float[] ReadFloatArray(int cnt) { int cnt0 = cnt << 2; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadFloatArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override void WriteLong(long val) { int pos0 = EnsureWriteCapacityAndShift(8); fixed (byte* data0 = Data) { WriteLong0(val, data0 + pos0); } } /** <inheritdoc /> */ public override long ReadLong() { int pos0 = EnsureReadCapacityAndShift(8); fixed (byte* data0 = Data) { return ReadLong0(data0 + pos0); } } /** <inheritdoc /> */ public override void WriteLongArray(long[] val) { int cnt = val.Length << 3; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteLongArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override long[] ReadLongArray(int cnt) { int cnt0 = cnt << 3; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadLongArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override void WriteDoubleArray(double[] val) { int cnt = val.Length << 3; int pos0 = EnsureWriteCapacityAndShift(cnt); fixed (byte* data0 = Data) { WriteDoubleArray0(val, data0 + pos0, cnt); } } /** <inheritdoc /> */ public override double[] ReadDoubleArray(int cnt) { int cnt0 = cnt << 3; int pos0 = EnsureReadCapacityAndShift(cnt0); fixed (byte* data0 = Data) { return ReadDoubleArray0(cnt, data0 + pos0, cnt0); } } /** <inheritdoc /> */ public override int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding) { int pos0 = EnsureWriteCapacityAndShift(byteCnt); int written; fixed (byte* data0 = Data) { written = WriteString0(chars, charCnt, byteCnt, encoding, data0 + pos0); } return written; } /** <inheritdoc /> */ public override void Write(byte* src, int cnt) { EnsureWriteCapacity(Pos + cnt); fixed (byte* data0 = Data) { WriteInternal(src, cnt, data0); } ShiftWrite(cnt); } /** <inheritdoc /> */ public override void Read(byte* dest, int cnt) { fixed (byte* data0 = Data) { ReadInternal(dest, cnt, data0); } } /** <inheritdoc /> */ public override int Remaining() { return Data.Length - Pos; } /** <inheritdoc /> */ public override byte[] Array() { return Data; } /** <inheritdoc /> */ public override byte[] ArrayCopy() { byte[] copy = new byte[Pos]; Buffer.BlockCopy(Data, 0, copy, 0, Pos); return copy; } /** <inheritdoc /> */ public override bool IsSameArray(byte[] arr) { return Data == arr; } /** <inheritdoc /> */ protected override void Dispose(bool disposing) { // No-op. } /// <summary> /// Internal array. /// </summary> internal byte[] InternalArray { get { return Data; } } /** <inheritdoc /> */ protected override void EnsureWriteCapacity(int cnt) { if (cnt > Data.Length) { int newCap = Capacity(Data.Length, cnt); byte[] data0 = new byte[newCap]; // Copy the whole initial array length here because it can be changed // from Java without position adjusting. Buffer.BlockCopy(Data, 0, data0, 0, Data.Length); Data = data0; } } /** <inheritdoc /> */ protected override void EnsureReadCapacity(int cnt) { if (Data.Length - Pos < cnt) throw new EndOfStreamException("Not enough data in stream [expected=" + cnt + ", remaining=" + (Data.Length - Pos) + ']'); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using Azure.Core; using Azure.Messaging.EventHubs.Consumer; using Azure.Messaging.EventHubs.Producer; using Azure.Storage.Blobs; using Microsoft.Azure.WebJobs.EventHubs.Processor; using Microsoft.Azure.WebJobs.Extensions.Clients.Shared; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Azure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; namespace Microsoft.Azure.WebJobs.EventHubs { internal class EventHubClientFactory { private readonly IConfiguration _configuration; private readonly AzureComponentFactory _componentFactory; private readonly EventHubOptions _options; private readonly INameResolver _nameResolver; private readonly ConcurrentDictionary<string, EventHubProducerClient> _producerCache; private readonly ConcurrentDictionary<string, IEventHubConsumerClient> _consumerCache = new (); public EventHubClientFactory( IConfiguration configuration, AzureComponentFactory componentFactory, IOptions<EventHubOptions> options, INameResolver nameResolver) { _configuration = configuration; _componentFactory = componentFactory; _options = options.Value; _nameResolver = nameResolver; _producerCache = new ConcurrentDictionary<string, EventHubProducerClient>(_options.RegisteredProducers); } internal EventHubProducerClient GetEventHubProducerClient(string eventHubName, string connection) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); return _producerCache.GetOrAdd(eventHubName, key => { if (!string.IsNullOrWhiteSpace(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { return new EventHubProducerClient( info.FullyQualifiedEndpoint, eventHubName, info.TokenCredential, new EventHubProducerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } return new EventHubProducerClient( NormalizeConnectionString(info.ConnectionString, eventHubName), new EventHubProducerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } throw new InvalidOperationException("No event hub sender named " + eventHubName); }); } internal EventProcessorHost GetEventProcessorHost(string eventHubName, string connection, string consumerGroup) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); consumerGroup ??= EventHubConsumerClient.DefaultConsumerGroupName; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { return new EventProcessorHost(consumerGroup: consumerGroup, connectionString: creds.EventHubConnectionString, eventHubName: eventHubName, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } else if (!string.IsNullOrEmpty(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { return new EventProcessorHost(consumerGroup: consumerGroup, fullyQualifiedNamespace: info.FullyQualifiedEndpoint, eventHubName: eventHubName, credential: info.TokenCredential, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } return new EventProcessorHost(consumerGroup: consumerGroup, connectionString: NormalizeConnectionString(info.ConnectionString, eventHubName), eventHubName: eventHubName, options: _options.EventProcessorOptions, eventBatchMaximumCount: _options.MaxBatchSize, invokeProcessorAfterReceiveTimeout: _options.InvokeFunctionAfterReceiveTimeout, exceptionHandler: _options.ExceptionHandler); } throw new InvalidOperationException("No event hub receiver named " + eventHubName); } internal IEventHubConsumerClient GetEventHubConsumerClient(string eventHubName, string connection, string consumerGroup) { eventHubName = _nameResolver.ResolveWholeString(eventHubName); consumerGroup ??= EventHubConsumerClient.DefaultConsumerGroupName; return _consumerCache.GetOrAdd(eventHubName, name => { EventHubConsumerClient client = null; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { client = new EventHubConsumerClient( consumerGroup, creds.EventHubConnectionString, eventHubName, new EventHubConsumerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } else if (!string.IsNullOrEmpty(connection)) { var info = ResolveConnectionInformation(connection); if (info.FullyQualifiedEndpoint != null && info.TokenCredential != null) { client = new EventHubConsumerClient( consumerGroup, info.FullyQualifiedEndpoint, eventHubName, info.TokenCredential, new EventHubConsumerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } else { client = new EventHubConsumerClient( consumerGroup, NormalizeConnectionString(info.ConnectionString, eventHubName), new EventHubConsumerClientOptions { RetryOptions = _options.RetryOptions, ConnectionOptions = _options.ConnectionOptions }); } } if (client != null) { return new EventHubConsumerClientImpl(client); } throw new InvalidOperationException("No event hub receiver named " + eventHubName); }); } internal BlobContainerClient GetCheckpointStoreClient(string eventHubName) { string storageConnectionString = null; if (_options.RegisteredConsumerCredentials.TryGetValue(eventHubName, out var creds)) { storageConnectionString = creds.StorageConnectionString; } // Fall back to default if not explicitly registered return new BlobContainerClient(storageConnectionString ?? _configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage), _options.CheckpointContainer); } internal static string NormalizeConnectionString(string originalConnectionString, string eventHubName) { var connectionString = ConnectionString.Parse(originalConnectionString); if (!connectionString.ContainsSegmentKey("EntityPath")) { connectionString.Add("EntityPath", eventHubName); } return connectionString.ToString(); } private EventHubsConnectionInformation ResolveConnectionInformation(string connection) { IConfigurationSection connectionSection = _configuration.GetWebJobsConnectionStringSection(connection); if (!connectionSection.Exists()) { // Not found throw new InvalidOperationException($"EventHub account connection string '{connection}' does not exist." + $"Make sure that it is a defined App Setting."); } if (!string.IsNullOrWhiteSpace(connectionSection.Value)) { return new EventHubsConnectionInformation(connectionSection.Value); } var fullyQualifiedNamespace = connectionSection["fullyQualifiedNamespace"]; if (string.IsNullOrWhiteSpace(fullyQualifiedNamespace)) { // Not found throw new InvalidOperationException($"Connection should have an 'fullyQualifiedNamespace' property or be a string representing a connection string."); } var credential = _componentFactory.CreateTokenCredential(connectionSection); return new EventHubsConnectionInformation(fullyQualifiedNamespace, credential); } private record EventHubsConnectionInformation { public EventHubsConnectionInformation(string connectionString) { ConnectionString = connectionString; } public EventHubsConnectionInformation(string fullyQualifiedEndpoint, TokenCredential tokenCredential) { FullyQualifiedEndpoint = fullyQualifiedEndpoint; TokenCredential = tokenCredential; } public string ConnectionString { get; } public string FullyQualifiedEndpoint { get; } public TokenCredential TokenCredential { get; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using Internal.Cryptography; using Internal.Cryptography.Pal; namespace System.Security.Cryptography.X509Certificates { public class X509Certificate : IDisposable { public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. Pal = CertificatePal.FromBlob(data, null, X509KeyStorageFlags.DefaultKeySet); } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); Pal = CertificatePal.FromBlob(rawData, password, keyStorageFlags); } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePal pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); Pal = CertificatePal.FromFile(fileName, password, keyStorageFlags); } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { ICertificatePal pal = Pal; Pal = null; if (pal != null) pal.Dispose(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, null); } public virtual byte[] Export(X509ContentType contentType, string password) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (IStorePal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, password); } } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetFormat() { return "X509"; } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); return GetRawSerialNumber().CloneByteArray(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } internal ICertificatePal Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these cases, we need to fall back to a calendar which can express the dates /// </summary> internal static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; private const X509KeyStorageFlags KeyStorageFlagsAll = (X509KeyStorageFlags)0x1f; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using Microsoft.Scripting.Runtime; [assembly: PythonModule("binascii", typeof(IronPython.Modules.PythonBinaryAscii))] namespace IronPython.Modules { public static class PythonBinaryAscii { public const string __doc__ = "Provides functions for converting between binary data encoded in various formats and ASCII."; private const int MAXLINESIZE = 76; private static readonly object _ErrorKey = new object(); private static readonly object _IncompleteKey = new object(); private static Exception Error(CodeContext/*!*/ context, params object[] args) { return PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState(_ErrorKey), args); } private static Exception Incomplete(CodeContext/*!*/ context, params object[] args) { return PythonExceptions.CreateThrowable((PythonType)context.LanguageContext.GetModuleState(_IncompleteKey), args); } [SpecialName] public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) { context.EnsureModuleException(_ErrorKey, dict, "Error", "binascii"); context.EnsureModuleException(_IncompleteKey, dict, "Incomplete", "binascii"); } private static int UuDecFunc(char val) { if (val > 32 && val < 96) return val - 32; switch (val) { case '\n': case '\r': case (char)32: case (char)96: return EmptyByte; default: return InvalidByte; } } public static string a2b_uu(CodeContext/*!*/ context, string data) { if (data == null) throw PythonOps.TypeError("expected string, got NoneType"); if (data.Length < 1) return new string(Char.MinValue, 32); int lenDec = (data[0] + 32) % 64; // decoded length in bytes int lenEnc = (lenDec * 4 + 2) / 3; // encoded length in 6-bit chunks string suffix = null; if (data.Length - 1 > lenEnc) { suffix = data.Substring(1 + lenEnc); data = data.Substring(1, lenEnc); } else { data = data.Substring(1); } StringBuilder res = DecodeWorker(context, data, true, UuDecFunc); if (suffix == null) { res.Append((char)0, lenDec - res.Length); } else { ProcessSuffix(context, suffix, UuDecFunc); } return res.ToString(); } public static string b2a_uu(CodeContext/*!*/ context, string data) { if (data == null) throw PythonOps.TypeError("expected string, got NoneType"); if (data.Length > 45) throw Error(context, "At most 45 bytes at once"); StringBuilder res = EncodeWorker(data, ' ', delegate(int val) { return (char)(32 + (val % 64)); }); res.Insert(0, ((char)(32 + data.Length)).ToString()); res.Append('\n'); return res.ToString(); } private static int Base64DecFunc(char val) { if (val >= 'A' && val <= 'Z') return val - 'A'; if (val >= 'a' && val <= 'z') return val - 'a' + 26; if (val >= '0' && val <= '9') return val - '0' + 52; switch (val) { case '+': return 62; case '/': return 63; case '=': return PadByte; default: return IgnoreByte; } } public static object a2b_base64(CodeContext/*!*/ context, [BytesConversion]string data) { if (data == null) throw PythonOps.TypeError("expected string, got NoneType"); data = RemovePrefix(context, data, Base64DecFunc); if (data.Length == 0) return String.Empty; StringBuilder res = DecodeWorker(context, data, false, Base64DecFunc); return res.ToString(); } public static object b2a_base64([BytesConversion]string data) { if (data == null) throw PythonOps.TypeError("expected string, got NoneType"); if (data.Length == 0) return String.Empty; StringBuilder res = EncodeWorker(data, '=', EncodeValue); res.Append('\n'); return res.ToString(); } private static char EncodeValue(int val) { if (val < 26) return (char)('A' + val); if (val < 52) return (char)('a' + val - 26); if (val < 62) return (char)('0' + val - 52); switch (val) { case 62: return '+'; case 63: return '/'; default: throw new InvalidOperationException(String.Format("Bad int val: {0}", val)); } } public static object a2b_qp(object data) { throw new NotImplementedException(); } [LightThrowing] public static object a2b_qp(object data, object header) { return LightExceptions.Throw(new NotImplementedException()); } private static void to_hex(char ch, StringBuilder s, int index) { int uvalue = ch, uvalue2 = ch / 16; s.Append("0123456789ABCDEF"[uvalue2 % 16]); s.Append("0123456789ABCDEF"[uvalue % 16]); } [Documentation(@"b2a_qp(data, quotetabs=0, istext=1, header=0) -> s; Encode a string using quoted-printable encoding. On encoding, when istext is set, newlines are not encoded, and white space at end of lines is. When istext is not set, \\r and \\n (CR/LF) are both encoded. When quotetabs is set, space and tabs are encoded.")] public static object b2a_qp(string data, [DefaultParameterValue(0)] int quotetabs, [DefaultParameterValue(1)] int istext, [DefaultParameterValue(0)] int header) { bool crlf = data.Contains("\r\n"); int linelen = 0, odatalen = 0; int incount = 0, outcount = 0; bool quotetabs_ = quotetabs != 0; bool header_ = header != 0; bool istext_ = istext != 0; while(incount < data.Length) { if ((data[incount] > 126) || (data[incount] == '=') || (header_ && data[incount] == '_') || ((data[incount] == '.') && (linelen == 0) && (data[incount+1] == '\n' || data[incount+1] == '\r' || data[incount+1] == 0)) || (!istext_ && ((data[incount] == '\r') || (data[incount] == '\n'))) || ((data[incount] == '\t' || data[incount] == ' ') && (incount +1 == data.Length)) || ((data[incount] < 33) && (data[incount] != '\r') && (data[incount] != '\n') && (quotetabs_ || (!quotetabs_ && ((data[incount] != '\t') && (data[incount] != ' ')))))) { if ((linelen + 3) >= MAXLINESIZE) { linelen = 0; if (crlf) odatalen += 3; else odatalen += 2; } linelen += 3; odatalen += 3; incount++; } else { if (istext_ && ((data[incount] == '\n') || ((incount + 1 < data.Length) && (data[incount] == '\r') && (data[incount + 1] == '\n')))) { linelen = 0; /* Protect against whitespace on end of line */ if (incount > 0 && ((data[incount - 1] == ' ') || (data[incount - 1] == '\t'))) odatalen += 2; if (crlf) odatalen += 2; else odatalen += 1; if (data[incount] == '\r') incount += 2; else incount++; } else { if ((incount + 1 != data.Length) && (data[incount + 1] != '\n') && (linelen + 1) >= MAXLINESIZE) { linelen = 0; if (crlf) odatalen += 3; else odatalen += 2; } linelen++; odatalen++; incount++; } } } StringBuilder odata = new StringBuilder(); incount = outcount = linelen = 0; while (incount < data.Length) { if ((data[incount] > 126) || (data[incount] == '=') || (header_ && data[incount] == '_') || ((data[incount] == '.') && (linelen == 0) && (data[incount + 1] == '\n' || data[incount + 1] == '\r' || data[incount + 1] == 0)) || (!istext_ && ((data[incount] == '\r') || (data[incount] == '\n'))) || ((data[incount] == '\t' || data[incount] == ' ') && (incount + 1 == data.Length)) || ((data[incount] < 33) && (data[incount] != '\r') && (data[incount] != '\n') && (quotetabs_ || (!quotetabs_ && ((data[incount] != '\t') && (data[incount] != ' ')))))) { if ((linelen + 3) >= MAXLINESIZE) { odata.Append('='); if (crlf) odata.Append('\r'); odata.Append('\n'); linelen = 0; } odata.Append('='); to_hex(data[incount], odata, outcount); outcount += 2; incount++; linelen += 3; } else { if (istext_ && ((data[incount] == '\n') || ((incount + 1 < data.Length) && (data[incount] == '\r') && (data[incount + 1] == '\n')))) { linelen = 0; /* Protect against whitespace on end of line */ if (outcount != 0 && ((odata[outcount - 1] == ' ') || (odata[outcount - 1] == '\t'))) { char ch = odata[outcount - 1]; odata[outcount - 1] = '='; to_hex(ch, odata, outcount); outcount += 2; } if (crlf) odata[outcount++] = '\r'; odata[outcount++] = '\n'; if (data[incount] == '\r') incount += 2; else incount++; } else { if ((incount +1 != data.Length) && (data[incount + 1] != '\n') && (linelen + 1) >= MAXLINESIZE) { odata[outcount++] = '='; if (crlf) odata[outcount++] = '\r'; odata[outcount++] = '\n'; linelen = 0; } linelen++; if (header_ && data[incount] == ' ') { odata[outcount++] = '_'; incount++; } else { odata[outcount++] = data[incount++]; } } } } return odata.ToString(); } public static object a2b_hqx(object data) { throw new NotImplementedException(); } public static object rledecode_hqx(object data) { throw new NotImplementedException(); } public static object rlecode_hqx(object data) { throw new NotImplementedException(); } public static object b2a_hqx(object data) { throw new NotImplementedException(); } private static ushort[] crctab_hqx = new ushort[] { 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, }; public static object crc_hqx([BytesConversion]IList<byte> data, int crc) { crc = crc & 0xffff; foreach (var b in data) { crc = ((crc << 8) & 0xff00) ^ crctab_hqx[(crc >> 8) ^ b]; } return crc; } [Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")] public static int crc32(string buffer, [DefaultParameterValue(0)] int baseValue) { byte[] data = buffer.MakeByteArray(); uint result = crc32(data, 0, data.Length, unchecked((uint)baseValue)); return unchecked((int)result); } [Documentation("crc32(string[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of string.")] public static int crc32(string buffer, uint baseValue) { byte[] data = buffer.MakeByteArray(); uint result = crc32(data, 0, data.Length, baseValue); return unchecked((int)result); } [Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")] public static int crc32(byte[] buffer, [DefaultParameterValue(0)] int baseValue) { uint result = crc32(buffer, 0, buffer.Length, unchecked((uint)baseValue)); return unchecked((int)result); } [Documentation("crc32(byte_array[, value]) -> string\n\nComputes a CRC (Cyclic Redundancy Check) checksum of byte_array.")] public static int crc32(byte[] buffer, uint baseValue) { uint result = crc32(buffer, 0, buffer.Length, baseValue); return unchecked((int)result); } internal static uint crc32(byte[] buffer, int offset, int count, uint baseValue) { uint remainder = (baseValue ^ 0xffffffff); for (int i = offset; i < offset + count; i++) { remainder = remainder ^ buffer[i]; for (int j = 0; j < 8; j++) { if ((remainder & 0x01) != 0) { remainder = (remainder >> 1) ^ 0xEDB88320; } else { remainder = (remainder >> 1); } } } return (remainder ^ 0xffffffff); } public static string b2a_hex(string data) { StringBuilder sb = new StringBuilder(data.Length * 2); for (int i = 0; i < data.Length; i++) { sb.AppendFormat("{0:x2}", (int)data[i]); } return sb.ToString(); } public static string hexlify(string data) { return b2a_hex(data); } public static Bytes hexlify(MemoryView data) { return hexlify(data.tobytes()); } public static Bytes hexlify(Bytes data) { byte[] res = new byte[data.Count * 2]; for (int i = 0; i < data.Count; i++) { res[i * 2] = ToHex(data._bytes[i] >> 4); res[(i * 2) + 1] = ToHex(data._bytes[i] & 0x0F); } return Bytes.Make(res); } public static Bytes hexlify(ByteArray data) { byte[] res = new byte[data.Count * 2]; for(int i =0; i < data.Count; i++) { res[i * 2] = ToHex(data._bytes[i] >> 4); res[(i * 2) + 1] = ToHex(data._bytes[i] & 0x0F); } return Bytes.Make(res); } private static byte ToHex(int p) { if (p >= 10) { return (byte)('a' + p - 10); } return (byte)('0' + p); } public static string hexlify([NotNull]PythonBuffer data) { return hexlify(data.ToString()); } public static object a2b_hex(CodeContext/*!*/ context, [BytesConversion] string data) { if (data == null) throw PythonOps.TypeError("expected string, got NoneType"); if ((data.Length & 0x01) != 0) throw PythonOps.TypeError("Odd-length string"); StringBuilder res = new StringBuilder(data.Length / 2); for (int i = 0; i < data.Length; i += 2) { byte b1, b2; if (Char.IsDigit(data[i])) b1 = (byte)(data[i] - '0'); else b1 = (byte)(Char.ToUpper(data[i]) - 'A' + 10); if (Char.IsDigit(data[i + 1])) b2 = (byte)(data[i + 1] - '0'); else b2 = (byte)(Char.ToUpper(data[i + 1]) - 'A' + 10); res.Append((char)(b1 * 16 + b2)); } return res.ToString(); } public static object unhexlify(CodeContext/*!*/ context, [BytesConversion] string hexstr) { return a2b_hex(context, hexstr); } #region Private implementation private delegate char EncodeChar(int val); private delegate int DecodeByte(char val); private static StringBuilder EncodeWorker(string data, char empty, EncodeChar encFunc) { StringBuilder res = new StringBuilder(); int bits; for (int i = 0; i < data.Length; i += 3) { switch (data.Length - i) { case 1: // only one char, emit 2 bytes & // padding bits = (data[i] & 0xff) << 16; res.Append(encFunc((bits >> 18) & 0x3f)); res.Append(encFunc((bits >> 12) & 0x3f)); res.Append(empty); res.Append(empty); break; case 2: // only two chars, emit 3 bytes & // padding bits = ((data[i] & 0xff) << 16) | ((data[i + 1] & 0xff) << 8); res.Append(encFunc((bits >> 18) & 0x3f)); res.Append(encFunc((bits >> 12) & 0x3f)); res.Append(encFunc((bits >> 6) & 0x3f)); res.Append(empty); break; default: // got all 3 bytes, just emit it. bits = ((data[i] & 0xff) << 16) | ((data[i + 1] & 0xff) << 8) | ((data[i + 2] & 0xff)); res.Append(encFunc((bits >> 18) & 0x3f)); res.Append(encFunc((bits >> 12) & 0x3f)); res.Append(encFunc((bits >> 6) & 0x3f)); res.Append(encFunc(bits & 0x3f)); break; } } return res; } private const int IgnoreByte = -1; // skip this byte private const int EmptyByte = -2; // byte evaluates to 0 and may appear off the end of the stream private const int PadByte = -3; // pad bytes signal the end of the stream, unless there are too few to properly align private const int InvalidByte = -4; // raise exception for illegal byte private const int NoMoreBytes = -5; // signals end of stream private static int NextVal(CodeContext/*!*/ context, string data, ref int index, DecodeByte decFunc) { int res; while (index < data.Length) { res = decFunc(data[index++]); switch (res) { case EmptyByte: return 0; case InvalidByte: throw Error(context, "Illegal char"); case IgnoreByte: break; default: return res; } } return NoMoreBytes; } private static int CountPadBytes(CodeContext/*!*/ context, string data, int bound, ref int index, DecodeByte decFunc) { int res = PadByte; int count = 0; while ((bound < 0 || count < bound) && (res = NextVal(context, data, ref index, decFunc)) == PadByte) { count++; } // we only want NextVal() to eat PadBytes - not real data if (res != PadByte && res != NoMoreBytes) index--; return count; } private static int GetVal(CodeContext/*!*/ context, string data, int align, bool bounded, ref int index, DecodeByte decFunc) { int res; while (true) { res = NextVal(context, data, ref index, decFunc); switch (res) { case PadByte: switch (align) { case 0: case 1: CountPadBytes(context, data, -1, ref index, decFunc); continue; case 2: if (CountPadBytes(context, data, 1, ref index, decFunc) > 0) { return NoMoreBytes; } else { continue; } default: return NoMoreBytes; } case NoMoreBytes: if (bounded || align == 0) { return NoMoreBytes; } else { throw Error(context, "Incorrect padding"); } case EmptyByte: return 0; default: return res; } } } private static StringBuilder DecodeWorker(CodeContext/*!*/ context, string data, bool bounded, DecodeByte decFunc) { StringBuilder res = new StringBuilder(); int i = 0; while (i < data.Length) { int intVal; int val0 = GetVal(context, data, 0, bounded, ref i, decFunc); if (val0 < 0) break; // no more bytes... int val1 = GetVal(context, data, 1, bounded, ref i, decFunc); if (val1 < 0) break; // no more bytes... int val2 = GetVal(context, data, 2, bounded, ref i, decFunc); if (val2 < 0) { // 2 byte partial intVal = (val0 << 18) | (val1 << 12); res.Append((char)((intVal >> 16) & 0xff)); break; } int val3 = GetVal(context, data, 3, bounded, ref i, decFunc); if (val3 < 0) { // 3 byte partial intVal = (val0 << 18) | (val1 << 12) | (val2 << 6); res.Append((char)((intVal >> 16) & 0xff)); res.Append((char)((intVal >> 8) & 0xff)); break; } // full 4-bytes intVal = (val0 << 18) | (val1 << 12) | (val2 << 6) | (val3); res.Append((char)((intVal >> 16) & 0xff)); res.Append((char)((intVal >> 8) & 0xff)); res.Append((char)(intVal & 0xff)); } return res; } private static string RemovePrefix(CodeContext/*!*/ context, string data, DecodeByte decFunc) { int count = 0; while (count < data.Length) { int current = decFunc(data[count]); if (current == InvalidByte) { throw Error(context, "Illegal char"); } if (current >= 0) break; count++; } return count == 0 ? data : data.Substring(count); } private static void ProcessSuffix(CodeContext/*!*/ context, string data, DecodeByte decFunc) { for (int i = 0; i < data.Length; i++) { int current = decFunc(data[i]); if (current >= 0 || current == InvalidByte) { throw Error(context, "Trailing garbage"); } } } #endregion } }
using System; using static OneOf.Functions; namespace OneOf { public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly int _index; protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8> input) { _index = input.Index; switch (_index) { case 0: _value0 = input.AsT0; break; case 1: _value1 = input.AsT1; break; case 2: _value2 = input.AsT2; break; case 3: _value3 = input.AsT3; break; case 4: _value4 = input.AsT4; break; case 5: _value5 = input.AsT5; break; case 6: _value6 = input.AsT6; break; case 7: _value7 = input.AsT7; break; case 8: _value8 = input.AsT8; break; default: throw new InvalidOperationException(); } } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } throw new InvalidOperationException(); } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, _ => throw new InvalidOperationException() }; return this.IsT8; } bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }
using System; using ForSerial.Objects; using NSubstitute; using NUnit.Framework; using IgnoreAttribute = ForSerial.Objects.IgnoreAttribute; namespace ForSerial.Tests.Objects { [TestFixture] public class IgnoreAttributeIgnoreAllTests : AttributeTests<IgnoreAttribute> { private static readonly string SomeScenario = Guid.NewGuid().ToString(); [Test] public void CanGet_CannotGet() { TestCanGetOverride(SomeScenario, true, false); } [Test] public void CanSet_CannotSet() { TestCanSetOverride(SomeScenario, true, false); } [Test] public void Read_InnerPropertyIsNotRead() { TestReadOverride(SomeScenario, sut => sut.InnerDefinition.DidNotReceive().Read(null, null, null)); } [Test] public void CanCreateValue_CannotCreateValue() { TestCanCreateValueOverride(SomeScenario, true, false); } [Test] public void CreateSequence_ReturnsNullSequence() { TestCreateSequenceOverride(SomeScenario, null, NullObjectSequence.Instance); } [Test] public void CreateDefaultStructure_ReturnsNullStructure() { TestCreateDefaultStructureOverride(SomeScenario, null, NullObjectStructure.Instance); } [Test] public void CreateTypedStructure_ReturnsNullStructure() { TestCreateTypedStructureOverride(SomeScenario, null, NullObjectStructure.Instance); } [Test] public void CreateValue_ReturnsNullValue() { TestCreateValueOverride(SomeScenario, null, NullObjectValue.Instance); } [Test] public void MatchesPropertyFilter_DoesNotMatch() { TestMatchesPropertyFilterOverride(SomeScenario, true, false); } protected override IgnoreAttribute CreateAttribute() { return new IgnoreAttribute(); } } [TestFixture] public class IgnoreAttributeSpecificScenarioTests : AttributeTests<IgnoreAttribute> { private const string IgnoreScenario1 = "TestScenario1"; private const string IgnoreScenario2 = "TestScenario2"; [Test] public void CanGet_WrongScenario_PassesThrough() { TestCanGetOverride(null, true, true); } [Test] public void CanGet_IgnoreScenario1_CannotGet() { TestCanGetOverride(IgnoreScenario1, true, false); } [Test] public void CanGet_IgnoreScenario2_CannotGet() { TestCanGetOverride(IgnoreScenario2, true, false); } [Test] public void CanSet_WrongScenario_PassesThrough() { TestCanSetOverride(null, true, true); } [Test] public void CanSet_IgnoreScenario1_CannotSet() { TestCanSetOverride(IgnoreScenario1, true, false); } [Test] public void CanSet_IgnoreScenario2_CannotSet() { TestCanSetOverride(IgnoreScenario2, true, false); } [Test] public void Read_WrongScenario_PassesThrough() { TestReadOverride(null, sut => sut.InnerDefinition.Received().Read(Arg.Any<object>(), Arg.Any<ObjectReader>(), Arg.Any<Writer>())); } [Test] public void Read_IgnoreScenario1_InnerPropertyIsNotRead() { TestReadOverride(IgnoreScenario1, sut => sut.InnerDefinition.DidNotReceive().Read(Arg.Any<object>(), Arg.Any<ObjectReader>(), Arg.Any<Writer>())); } [Test] public void Read_IgnoreScenario2_InnerPropertyIsNotRead() { TestReadOverride(IgnoreScenario2, sut => sut.InnerDefinition.DidNotReceive().Read(Arg.Any<object>(), Arg.Any<ObjectReader>(), Arg.Any<Writer>())); } [Test] public void CanCreateValue_WrongScenario_PassesThrough() { TestCanCreateValueOverride(null, true, true); } [Test] public void CanCreateValue_IgnoreScenario1_CannotCreateValue() { TestCanCreateValueOverride(IgnoreScenario1, true, false); } [Test] public void CanCreateValue_IgnoreScenario2_CannotCreateValue() { TestCanCreateValueOverride(IgnoreScenario2, true, false); } [Test] public void CreateSequence_WrongScenario_PassesThrough() { ObjectContainer expectedSequence = Substitute.For<ObjectContainer>(); TestCreateSequenceOverride(null, expectedSequence, expectedSequence); } [Test] public void CreateSequence_IgnoreScenario1_ReturnsNullSequence() { TestCreateSequenceOverride(IgnoreScenario1, null, NullObjectSequence.Instance); } [Test] public void CreateSequence_IgnoreScenario2_ReturnsNullSequence() { TestCreateSequenceOverride(IgnoreScenario2, null, NullObjectSequence.Instance); } [Test] public void CreateDefaultStructure_WrongScenario_PassesThrough() { ObjectContainer expectedStructure = Substitute.For<ObjectContainer>(); TestCreateDefaultStructureOverride(null, expectedStructure, expectedStructure); } [Test] public void CreateDefaultStructure_IgnoreScenario1_ReturnsNullStructure() { TestCreateDefaultStructureOverride(IgnoreScenario1, null, NullObjectStructure.Instance); } [Test] public void CreateDefaultStructure_IgnoreScenario2_ReturnsNullStructure() { TestCreateDefaultStructureOverride(IgnoreScenario2, null, NullObjectStructure.Instance); } [Test] public void CreateTypedStructure_WrongScenario_PassesThrough() { ObjectContainer expectedStructure = Substitute.For<ObjectContainer>(); TestCreateTypedStructureOverride(null, expectedStructure, expectedStructure); } [Test] public void CreateTypedStructure_IgnoreScenario1_ReturnsNullStructure() { TestCreateTypedStructureOverride(IgnoreScenario1, null, NullObjectStructure.Instance); } [Test] public void CreateTypedStructure_IgnoreScenario2_ReturnsNullStructure() { TestCreateTypedStructureOverride(IgnoreScenario2, null, NullObjectStructure.Instance); } [Test] public void CreateValue_WrongScenario_PassesThrough() { ObjectOutput expectedValue = Substitute.For<ObjectOutput>(); TestCreateValueOverride(null, expectedValue, expectedValue); } [Test] public void CreateValue_IgnoreScenario1_ReturnsNullValue() { TestCreateValueOverride(IgnoreScenario1, null, NullObjectValue.Instance); } [Test] public void CreateValue_IgnoreScenario2_ReturnsNullValue() { TestCreateValueOverride(IgnoreScenario2, null, NullObjectValue.Instance); } [Test] public void MatchesPropertyFilter_WrongScenario_PassesThrough() { TestMatchesPropertyFilterOverride(null, true, true); } [Test] public void MatchesPropertyFilter_IgnoreScenario1_DoesNotMatch() { TestMatchesPropertyFilterOverride(IgnoreScenario1, true, false); } [Test] public void MatchesPropertyFilter_IgnoreScenario2_DoesNotMatch() { TestMatchesPropertyFilterOverride(IgnoreScenario2, true, false); } protected override IgnoreAttribute CreateAttribute() { return new IgnoreAttribute(IgnoreScenario1, IgnoreScenario2); } } [TestFixture] public class CopyIgnoreAttributeTests : AttributeTests<CopyIgnoreAttribute> { [Test] public void CanGet_WrongScenario_PassesThrough() { TestCanGetOverride(null, true, true); } [Test] public void CanGet_ObjectCopy_CannotGet() { TestCanGetOverride(SerializationScenario.ObjectCopy, true, false); } protected override CopyIgnoreAttribute CreateAttribute() { return new CopyIgnoreAttribute(); } } [TestFixture] public class JsonIgnoreAttributeTests : AttributeTests<JsonIgnoreAttribute> { [Test] public void CanGet_WrongScenario_PassesThrough() { TestCanGetOverride(null, true, true); } [Test] public void CanGet_SerializeToJson_CannotGet() { TestCanGetOverride(SerializationScenario.SerializeToJson, true, false); } [Test] public void CanGet_DeserializeJson_CannotGet() { TestCanGetOverride(SerializationScenario.DeserializeJson, true, false); } protected override JsonIgnoreAttribute CreateAttribute() { return new JsonIgnoreAttribute(); } } }
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; using System.Windows.Media; using Microsoft.Msagl.Drawing; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using GeometryEdge = Microsoft.Msagl.Core.Layout.Edge; using MsaglPoint = Microsoft.Msagl.Core.Geometry.Point; namespace Microsoft.Msagl.GraphControlSilverlight { /// <summary> /// This class represents a rendering edge. It contains the Microsoft.Msagl.Drawing.Edge and Microsoft.Msagl.Edge. /// The rendering edge is a XAML user control. Its template is stored in Themes/generic.xaml. /// </summary> public sealed class DEdge : DObject, IViewerEdge, IHavingDLabel, IEditableObject { /// <summary> /// the corresponding drawing edge /// </summary> public DrawingEdge DrawingEdge { get; set; } public GeometryEdge GeometryEdge { get { return this.DrawingEdge.GeometryObject as GeometryEdge; } set { this.DrawingEdge.GeometryEdge = value; } } internal DEdge(DNode source, DNode target, DrawingEdge drawingEdgeParam, ConnectionToGraph connection) : base(source.ParentObject) { this.DrawingEdge = drawingEdgeParam; this.Source = source; this.Target = target; if (connection == ConnectionToGraph.Connected) { if (source == target) source.AddSelfEdge(this); else { source.AddOutEdge(this); target.AddInEdge(this); } } if (drawingEdgeParam.Label != null) this.Label = new DTextLabel(this, DrawingEdge.Label); } public DNode Source { get; set; } public DNode Target { get; set; } public override void MakeVisual() { if (DrawingEdge.GeometryEdge.Curve == null) return; SetValue(Canvas.LeftProperty, Edge.BoundingBox.Left); SetValue(Canvas.TopProperty, Edge.BoundingBox.Bottom); if (StrokeDashArray == null) { // Note that Draw.CreateGraphicsPath returns a curve with coordinates in graph space. var pathFigure = Draw.CreateGraphicsPath((DrawingEdge.GeometryObject as GeometryEdge).Curve); var pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); Draw.DrawEdgeArrows(pathGeometry, DrawingEdge, FillArrowheadAtSource, FillArrowheadAtTarget); // Apply a translation to bring the coordinates in node space (i.e. top left corner is 0,0). pathGeometry.Transform = new MatrixTransform() { Matrix = new Matrix(1.0, 0.0, 0.0, 1.0, -Edge.BoundingBox.Left, -Edge.BoundingBox.Bottom) }; if (SelectedForEditing && GeometryEdge.UnderlyingPolyline != null) Draw.DrawUnderlyingPolyline(pathGeometry, this); var path = new Path() { Data = pathGeometry, StrokeThickness = Math.Max(LineWidth, Edge.Attr.LineWidth), Stroke = EdgeBrush, Fill = EdgeBrush }; Content = path; } else { // A dash array has been specified. I don't want to apply it to both the edge and the arrowheads; for this reason, I'm going to split the drawing in two Path instances. // This is not done in the general case to keep the number of Paths down. var pathFigure = Draw.CreateGraphicsPath((DrawingEdge.GeometryObject as GeometryEdge).Curve); var pathGeometry = new PathGeometry(); pathGeometry.Figures.Add(pathFigure); pathGeometry.Transform = new MatrixTransform() { Matrix = new Matrix(1.0, 0.0, 0.0, 1.0, -Edge.BoundingBox.Left, -Edge.BoundingBox.Bottom) }; if (SelectedForEditing && GeometryEdge.UnderlyingPolyline != null) Draw.DrawUnderlyingPolyline(pathGeometry, this); DoubleCollection dc = new DoubleCollection(); foreach (double d in StrokeDashArray) dc.Add(d); var path1 = new Path() { Data = pathGeometry, StrokeThickness = Math.Max(LineWidth, Edge.Attr.LineWidth), Stroke = EdgeBrush, Fill = EdgeBrush, StrokeDashArray = dc }; pathGeometry = new PathGeometry(); pathGeometry.Transform = new MatrixTransform() { Matrix = new Matrix(1.0, 0.0, 0.0, 1.0, -Edge.BoundingBox.Left, -Edge.BoundingBox.Bottom) }; Draw.DrawEdgeArrows(pathGeometry, DrawingEdge, FillArrowheadAtSource, FillArrowheadAtTarget); var path2 = new Path() { Data = pathGeometry, StrokeThickness = Math.Max(LineWidth, Edge.Attr.LineWidth), Stroke = EdgeBrush, Fill = EdgeBrush }; var c = new Grid(); c.Children.Add(path1); c.Children.Add(path2); Content = c; } } public DoubleCollection StrokeDashArray { get; set; } // Workaround for MSAGL bug which causes Edge.Attr.LineWidth to be ignored public int LineWidth { get; set; } /// <summary> /// Gets or sets the edge brush. /// </summary> public Brush EdgeBrush { get { return (Brush)GetValue(EdgeBrushProperty); } set { SetValue(EdgeBrushProperty, value); } } public static readonly DependencyProperty EdgeBrushProperty = DependencyProperty.Register("EdgeBrush", typeof(Brush), typeof(DEdge), new PropertyMetadata(DGraph.BlackBrush)); public ArrowStyle ArrowheadAtSource { get { return DrawingEdge.Attr.ArrowheadAtSource; } set { DrawingEdge.Attr.ArrowheadAtSource = value; if (value == ArrowStyle.None) GeometryEdge.EdgeGeometry.SourceArrowhead = null; else GeometryEdge.EdgeGeometry.SourceArrowhead = new Core.Layout.Arrowhead(); //DrawingEdge.GeometryEdge.ArrowheadAtSource = value != ArrowStyle.None; } } public bool FillArrowheadAtSource { get; set; } public ArrowStyle ArrowheadAtTarget { get { return DrawingEdge.Attr.ArrowheadAtTarget; } set { DrawingEdge.Attr.ArrowheadAtTarget = value; if (value == ArrowStyle.None) GeometryEdge.EdgeGeometry.TargetArrowhead = null; else GeometryEdge.EdgeGeometry.TargetArrowhead = new Core.Layout.Arrowhead(); //DrawingEdge.GeometryEdge.ArrowheadAtTarget = value != ArrowStyle.None; } } public bool FillArrowheadAtTarget { get; set; } #region IDraggableEdge Members /// <summary> /// underlying Drawing edge /// </summary> public DrawingEdge Edge { get { return this.DrawingEdge; } } IViewerNode IViewerEdge.Source { get { return Source; } } IViewerNode IViewerEdge.Target { get { return Target; } } private DLabel _Label; /// <summary> /// Gets or sets the rendering label. /// </summary> public DLabel Label { get { return _Label; } set { _Label = value; // Also set the drawing label and geometry label. DrawingEdge.Label = value.DrawingLabel; DrawingEdge.GeometryEdge.Label = value.DrawingLabel.GeometryLabel; } } /// <summary> /// The underlying DrawingEdge /// </summary> override public DrawingObject DrawingObject { get { return this.DrawingEdge; } } /// <summary> ///the radius of circles drawin around polyline corners /// </summary> public double RadiusOfPolylineCorner { get; set; } #endregion #region IEditableObject Members /// <summary> /// is set to true then the edge should set up for editing /// </summary> public bool SelectedForEditing { get; set; } #endregion } }
// 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.ComponentModel; using System.Composition; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Completion; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Options.Providers; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.Internal.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; using Microsoft.VisualStudio.Settings; using Microsoft.VisualStudio.Shell; using Microsoft.Win32; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options { [ExportLanguageSpecificOptionSerializer( LanguageNames.CSharp, OrganizerOptions.FeatureName, CompletionOptions.FeatureName, CSharpCompletionOptions.FeatureName, CSharpCodeStyleOptions.FeatureName, SimplificationOptions.PerLanguageFeatureName, ExtractMethodOptions.FeatureName, CSharpFormattingOptions.IndentFeatureName, CSharpFormattingOptions.NewLineFormattingFeatureName, CSharpFormattingOptions.SpacingFeatureName, CSharpFormattingOptions.WrappingFeatureName, FormattingOptions.InternalTabFeatureName, FeatureOnOffOptions.OptionName, ServiceFeatureOnOffOptions.OptionName), Shared] internal sealed class CSharpSettingsManagerOptionSerializer : AbstractSettingsManagerOptionSerializer { [ImportingConstructor] public CSharpSettingsManagerOptionSerializer(SVsServiceProvider serviceProvider, IOptionService optionService) : base(serviceProvider, optionService) { } private const string WrappingIgnoreSpacesAroundBinaryOperator = nameof(AutomationObject.Wrapping_IgnoreSpacesAroundBinaryOperators); private const string SpaceAroundBinaryOperator = nameof(AutomationObject.Space_AroundBinaryOperator); private const string UnindentLabels = nameof(AutomationObject.Indent_UnindentLabels); private const string FlushLabelsLeft = nameof(AutomationObject.Indent_FlushLabelsLeft); private KeyValuePair<string, IOption> GetOptionInfoForOnOffOptions(FieldInfo fieldInfo) { var value = (IOption)fieldInfo.GetValue(obj: null); return new KeyValuePair<string, IOption>(GetStorageKeyForOption(value), value); } private bool ShouldIncludeOnOffOption(FieldInfo fieldInfo) { return SupportsOnOffOption((IOption)fieldInfo.GetValue(obj: null)); } protected override ImmutableDictionary<string, IOption> CreateStorageKeyToOptionMap() { var result = ImmutableDictionary.Create<string, IOption>(StringComparer.OrdinalIgnoreCase).ToBuilder(); result.AddRange(new[] { new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.IncludeKeywords), CompletionOptions.IncludeKeywords), new KeyValuePair<string, IOption>(GetStorageKeyForOption(CompletionOptions.TriggerOnTypingLetters), CompletionOptions.TriggerOnTypingLetters), }); Type[] types = new[] { typeof(OrganizerOptions), typeof(CSharpCompletionOptions), typeof(SimplificationOptions), typeof(CSharpCodeStyleOptions), typeof(ExtractMethodOptions), typeof(ServiceFeatureOnOffOptions), typeof(CSharpFormattingOptions) }; var bindingFlags = BindingFlags.Public | BindingFlags.Static; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfo)); types = new[] { typeof(FeatureOnOffOptions) }; result.AddRange(AbstractSettingsManagerOptionSerializer.GetOptionInfoFromTypeFields(types, bindingFlags, this.GetOptionInfoForOnOffOptions, this.ShouldIncludeOnOffOption)); return result.ToImmutable(); } protected override string LanguageName { get { return LanguageNames.CSharp; } } protected override string SettingStorageRoot { get { return "TextEditor.CSharp.Specific."; } } protected override string GetStorageKeyForOption(IOption option) { var name = option.Name; if (option == ServiceFeatureOnOffOptions.ClosedFileDiagnostic) { // ClosedFileDiagnostics has been deprecated in favor of CSharpClosedFileDiagnostics. // ClosedFileDiagnostics had a default value of 'true', while CSharpClosedFileDiagnostics has a default value of 'false'. // We want to ensure that we don't fetch the setting store value for the old flag, as that can cause the default value for this option to change. name = nameof(AutomationObject.CSharpClosedFileDiagnostics); } return SettingStorageRoot + name; } protected override bool SupportsOption(IOption option, string languageName) { if (option == OrganizerOptions.PlaceSystemNamespaceFirst || option == OrganizerOptions.WarnOnBuildErrors || option == CSharpCompletionOptions.AddNewLineOnEnterAfterFullyTypedWord || option == CSharpCompletionOptions.IncludeSnippets || option.Feature == CSharpCodeStyleOptions.FeatureName || option.Feature == CSharpFormattingOptions.WrappingFeatureName || option.Feature == CSharpFormattingOptions.IndentFeatureName || option.Feature == CSharpFormattingOptions.SpacingFeatureName || option.Feature == CSharpFormattingOptions.NewLineFormattingFeatureName) { return true; } else if (languageName == LanguageNames.CSharp) { if (option == CompletionOptions.IncludeKeywords || option == CompletionOptions.TriggerOnTypingLetters || option.Feature == SimplificationOptions.PerLanguageFeatureName || option.Feature == ExtractMethodOptions.FeatureName || option.Feature == ServiceFeatureOnOffOptions.OptionName || option.Feature == FormattingOptions.InternalTabFeatureName) { return true; } else if (option.Feature == FeatureOnOffOptions.OptionName) { return SupportsOnOffOption(option); } } return false; } private bool SupportsOnOffOption(IOption option) { return option == FeatureOnOffOptions.AutoFormattingOnCloseBrace || option == FeatureOnOffOptions.AutoFormattingOnSemicolon || option == FeatureOnOffOptions.LineSeparator || option == FeatureOnOffOptions.Outlining || option == FeatureOnOffOptions.ReferenceHighlighting || option == FeatureOnOffOptions.KeywordHighlighting || option == FeatureOnOffOptions.FormatOnPaste || option == FeatureOnOffOptions.AutoXmlDocCommentGeneration || option == FeatureOnOffOptions.RefactoringVerification || option == FeatureOnOffOptions.RenameTracking || option == FeatureOnOffOptions.RenameTrackingPreview; } public override bool TryFetch(OptionKey optionKey, out object value) { value = null; if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 object ignoreSpacesAroundBinaryObjectValue = this.Manager.GetValueOrDefault(WrappingIgnoreSpacesAroundBinaryOperator, defaultValue: 0); if (ignoreSpacesAroundBinaryObjectValue.Equals(1)) { value = BinaryOperatorSpacingOptions.Ignore; return true; } object spaceAroundBinaryOperatorObjectValue = this.Manager.GetValueOrDefault(SpaceAroundBinaryOperator, defaultValue: 1); if (spaceAroundBinaryOperatorObjectValue.Equals(0)) { value = BinaryOperatorSpacingOptions.Remove; return true; } value = BinaryOperatorSpacingOptions.Single; return true; } if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { object flushLabelLeftObjectValue = this.Manager.GetValueOrDefault(FlushLabelsLeft, defaultValue: 0); if (flushLabelLeftObjectValue.Equals(1)) { value = LabelPositionOptions.LeftMost; return true; } object unindentLabelsObjectValue = this.Manager.GetValueOrDefault(UnindentLabels, defaultValue: 1); if (unindentLabelsObjectValue.Equals(0)) { value = LabelPositionOptions.NoIndent; return true; } value = LabelPositionOptions.OneLess; return true; } return base.TryFetch(optionKey, out value); } public override bool TryPersist(OptionKey optionKey, object value) { if (this.Manager == null) { Debug.Fail("Manager field is unexpectedly null."); return false; } if (optionKey.Option == CSharpFormattingOptions.SpacingAroundBinaryOperator) { // Remove space -> Space_AroundBinaryOperator = 0 // Insert space -> Space_AroundBinaryOperator and Wrapping_IgnoreSpacesAroundBinaryOperator both missing // Ignore spacing -> Wrapping_IgnoreSpacesAroundBinaryOperator = 1 switch ((BinaryOperatorSpacingOptions)value) { case BinaryOperatorSpacingOptions.Remove: { this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(SpaceAroundBinaryOperator, 0, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Ignore: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, 1, isMachineLocal: false); return true; } case BinaryOperatorSpacingOptions.Single: { this.Manager.SetValueAsync(SpaceAroundBinaryOperator, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(WrappingIgnoreSpacesAroundBinaryOperator, value: 0, isMachineLocal: false); return true; } } } else if (optionKey.Option == CSharpFormattingOptions.LabelPositioning) { switch ((LabelPositionOptions)value) { case LabelPositionOptions.LeftMost: { this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); this.Manager.SetValueAsync(FlushLabelsLeft, 1, isMachineLocal: false); return true; } case LabelPositionOptions.NoIndent: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, 0, isMachineLocal: false); return true; } case LabelPositionOptions.OneLess: { this.Manager.SetValueAsync(FlushLabelsLeft, value: 0, isMachineLocal: false); this.Manager.SetValueAsync(UnindentLabels, value: 1, isMachineLocal: false); return true; } } } return base.TryPersist(optionKey, value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using System.Runtime.CompilerServices; using System.ServiceModel.Channels; using System.Threading.Tasks; using SessionIdleManager = System.ServiceModel.Channels.ServiceChannel.SessionIdleManager; namespace System.ServiceModel.Dispatcher { internal class ListenerHandler : CommunicationObject { private static Action<object> s_initiateChannelPump = new Action<object>(ListenerHandler.InitiateChannelPump); private static AsyncCallback s_waitCallback = Fx.ThunkCallback(new AsyncCallback(ListenerHandler.WaitCallback)); private readonly ChannelDispatcher _channelDispatcher; private ListenerChannel _channel; private SessionIdleManager _idleManager; private bool _acceptedNull; private bool _doneAccepting; private EndpointDispatcherTable _endpoints; private readonly IListenerBinder _listenerBinder; private IDefaultCommunicationTimeouts _timeouts; internal ListenerHandler(IListenerBinder listenerBinder, ChannelDispatcher channelDispatcher, IDefaultCommunicationTimeouts timeouts) { _listenerBinder = listenerBinder; if (!((_listenerBinder != null))) { Fx.Assert("ListenerHandler.ctor: (this.listenerBinder != null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("listenerBinder"); } _channelDispatcher = channelDispatcher; if (!((_channelDispatcher != null))) { Fx.Assert("ListenerHandler.ctor: (this.channelDispatcher != null)"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelDispatcher"); } _timeouts = timeouts; _endpoints = channelDispatcher.EndpointDispatcherTable; } internal ChannelDispatcher ChannelDispatcher { get { return _channelDispatcher; } } internal ListenerChannel Channel { get { return _channel; } } protected override TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } protected override TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } internal EndpointDispatcherTable Endpoints { get { return _endpoints; } set { _endpoints = value; } } new internal object ThisLock { get { return base.ThisLock; } } protected internal override Task OnCloseAsync(TimeSpan timeout) { this.OnClose(timeout); return TaskHelpers.CompletedTask(); } protected internal override Task OnOpenAsync(TimeSpan timeout) { this.OnOpen(timeout); return TaskHelpers.CompletedTask(); } protected override void OnOpen(TimeSpan timeout) { } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new CompletedAsyncResult(callback, state); } protected override void OnEndOpen(IAsyncResult result) { CompletedAsyncResult.End(result); } protected override void OnOpened() { base.OnOpened(); _channelDispatcher.Channels.IncrementActivityCount(); NewChannelPump(); } internal void NewChannelPump() { ActionItem.Schedule(ListenerHandler.s_initiateChannelPump, this); } private static void InitiateChannelPump(object state) { ListenerHandler listenerHandler = state as ListenerHandler; listenerHandler.ChannelPump(); } private void ChannelPump() { IChannelListener listener = _listenerBinder.Listener; for (; ; ) { if (_acceptedNull || (listener.State == CommunicationState.Faulted)) { this.DoneAccepting(); break; } this.Dispatch(); } } private static void WaitCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; }; ListenerHandler listenerHandler = (ListenerHandler)result.AsyncState; IChannelListener listener = listenerHandler._listenerBinder.Listener; listenerHandler.Dispatch(); } private void AbortChannels() { IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) { channels[index].Abort(); } } private void CloseChannel(IChannel channel, TimeSpan timeout) { try { if (channel.State != CommunicationState.Closing && channel.State != CommunicationState.Closed) { CloseChannelState state = new CloseChannelState(this, channel); if (channel is ISessionChannel<IDuplexSession>) { IDuplexSession duplexSession = ((ISessionChannel<IDuplexSession>)channel).Session; IAsyncResult result = duplexSession.BeginCloseOutputSession(timeout, Fx.ThunkCallback(new AsyncCallback(CloseOutputSessionCallback)), state); if (result.CompletedSynchronously) duplexSession.EndCloseOutputSession(result); } else { IAsyncResult result = channel.BeginClose(timeout, Fx.ThunkCallback(new AsyncCallback(CloseChannelCallback)), state); if (result.CompletedSynchronously) channel.EndClose(result); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); if (channel is ISessionChannel<IDuplexSession>) { channel.Abort(); } } } private static void CloseChannelCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CloseChannelState state = (CloseChannelState)result.AsyncState; try { state.Channel.EndClose(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ListenerHandler.HandleError(e); } } public void CloseInput(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // Close all datagram channels IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) { IChannel channel = channels[index]; if (!this.IsSessionChannel(channel)) { try { channel.Close(timeoutHelper.RemainingTime()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); } } } } private static void CloseOutputSessionCallback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } CloseChannelState state = (CloseChannelState)result.AsyncState; try { ((ISessionChannel<IDuplexSession>)state.Channel).Session.EndCloseOutputSession(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } state.ListenerHandler.HandleError(e); state.Channel.Abort(); } } private void CloseChannels(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); IChannel[] channels = _channelDispatcher.Channels.ToArray(); for (int index = 0; index < channels.Length; index++) CloseChannel(channels[index], timeoutHelper.RemainingTime()); } private void Dispatch() { ListenerChannel channel = _channel; SessionIdleManager idleManager = _idleManager; _channel = null; _idleManager = null; try { if (channel != null) { ChannelHandler handler = new ChannelHandler(_listenerBinder.MessageVersion, channel.Binder, this, idleManager); if (!channel.Binder.HasSession) { _channelDispatcher.Channels.Add(channel.Binder.Channel); } if (channel.Binder is DuplexChannelBinder) { DuplexChannelBinder duplexChannelBinder = channel.Binder as DuplexChannelBinder; duplexChannelBinder.ChannelHandler = handler; duplexChannelBinder.DefaultCloseTimeout = this.DefaultCloseTimeout; if (_timeouts == null) duplexChannelBinder.DefaultSendTimeout = ServiceDefaults.SendTimeout; else duplexChannelBinder.DefaultSendTimeout = _timeouts.SendTimeout; } ChannelHandler.Register(handler); channel = null; idleManager = null; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.HandleError(e); } finally { if (channel != null) { channel.Binder.Channel.Abort(); if (idleManager != null) { idleManager.CancelTimer(); } } } } private void AcceptedNull() { _acceptedNull = true; } private void DoneAccepting() { lock (this.ThisLock) { if (!_doneAccepting) { _doneAccepting = true; _channelDispatcher.Channels.DecrementActivityCount(); } } } private bool IsSessionChannel(IChannel channel) { return (channel is ISessionChannel<IDuplexSession> || channel is ISessionChannel<IInputSession> || channel is ISessionChannel<IOutputSession>); } private void CancelPendingIdleManager() { SessionIdleManager idleManager = _idleManager; if (idleManager != null) { idleManager.CancelTimer(); } } protected override void OnAbort() { // if there's an idle manager that has not been transferred to the channel handler, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Abort existing channels this.AbortChannels(); // Wait for channels to finish aborting _channelDispatcher.Channels.Abort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // if there's an idle manager that has not been cancelled, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Start closing existing channels this.CloseChannels(timeoutHelper.RemainingTime()); // Wait for channels to finish closing return _channelDispatcher.Channels.BeginClose(timeoutHelper.RemainingTime(), callback, state); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); // if there's an idle manager that has not been cancelled, cancel it CancelPendingIdleManager(); // Start aborting incoming channels _channelDispatcher.Channels.CloseInput(); // Start closing existing channels this.CloseChannels(timeoutHelper.RemainingTime()); // Wait for channels to finish closing _channelDispatcher.Channels.Close(timeoutHelper.RemainingTime()); } protected override void OnEndClose(IAsyncResult result) { _channelDispatcher.Channels.EndClose(result); } private bool HandleError(Exception e) { return _channelDispatcher.HandleError(e); } internal class CloseChannelState { private ListenerHandler _listenerHandler; private IChannel _channel; internal CloseChannelState(ListenerHandler listenerHandler, IChannel channel) { _listenerHandler = listenerHandler; _channel = channel; } internal ListenerHandler ListenerHandler { get { return _listenerHandler; } } internal IChannel Channel { get { return _channel; } } } } internal class ListenerChannel { private IChannelBinder _binder; public ListenerChannel(IChannelBinder binder) { _binder = binder; } public IChannelBinder Binder { get { return _binder; } } } }
using Hellang.Middleware.ProblemDetails; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; using OneBoxDeployment.Api.Filters; using OneBoxDeployment.Api.Logging; using OneBoxDeployment.Common; using OneBoxDeployment.GrainInterfaces; using OneBoxDeployment.OrleansUtilities; using Orleans; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Statistics; using Serilog; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection; using System.Security.Principal; using System.Text.Json; using System.Threading.Tasks; namespace OneBoxDeployment.Api { /// <summary> /// An API startup class with modifications. /// </summary> public class Startup { /// <summary> /// This is the root to Swagger documentation URL and to the /// generated content. /// </summary> private string SwaggerRoot { get; } = "api-docs"; /// <summary> /// The root for Swagger documentation URL. /// </summary> private string SwaggerDocumentationBasePath { get; } = "OneBoxDeployment"; /// <summary> /// The environment specific configuration object. /// </summary> public IConfiguration Configuration { get; } /// <summary> /// The environment specific logger. /// </summary> public Microsoft.Extensions.Logging.ILogger Logger { get; } /// <summary> /// The hosting environment. /// </summary> public IWebHostEnvironment Environment { get; set; } /// <summary> /// A default constructor. /// </summary> /// <param name="logger">The environment specific logger.</param> /// <param name="configuration">The environment specific configuration object.</param> /// <param name="env">The environment information to use in checking per deployment type configuration value validity.</param> public Startup(ILogger<Startup> logger, IConfiguration configuration, IWebHostEnvironment env) { Logger = logger ?? throw new ArgumentNullException(nameof(logger)); Configuration = configuration ?? throw new ArgumentNullException(nameof(configuration)); Environment = env ?? throw new ArgumentNullException(nameof(env)); if(Environment.IsProduction()) { foreach(var forbiddenKey in ConfigurationKeys.ConfigurationKeysForbiddenInProduction) { var forbiddenKeys = new List<string>(); if(configuration.GetValue<string>(forbiddenKey, null) != null) { forbiddenKeys.Add(forbiddenKey); } //Note: ConfigurationErrorsException could be thrown here, but it'd require taking //a dependency to System.Configuration. if(forbiddenKeys.Any()) { throw new ArgumentException($"The following keys are forbidden in production " + $"= {env.EnvironmentName}: {string.Join(',', forbiddenKeys)}", nameof(configuration)); } } } } /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">The ASP.NET services collection.</param> public void ConfigureServices(IServiceCollection services) { if(Environment.IsProduction()) { services.AddApplicationInsightsTelemetry(Configuration); services.AddCors(options => { var allowedOrigins = Configuration.GetSection("AllowedOrigins").Get<string[]>(); options.AddPolicy("CorsPolicy", builder => builder .WithOrigins(allowedOrigins) .AllowAnyMethod() .AllowAnyHeader()); }); } else { services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); }); } //See more about formatters at https://docs.microsoft.com/en-us/aspnet/core/mvc/models/formatting. services .AddProblemDetails(ConfigureProblemDetails) .AddMvcCore(options => { if(!Environment.IsDevelopment()) { options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build())); } options.Conventions.Add(new NotFoundResultFilterConvention()); //The Content-Security-Policy (CSP) is JSON, so it's added here to the known JSON serialized types. var jsonInputFormatter = options.InputFormatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault(); if(jsonInputFormatter != null) { jsonInputFormatter.SupportedMediaTypes.Add(MimeTypes.MimeTypeCspReport); } }) .AddApiExplorer() //.AddAuthorization() .AddDataAnnotations() .AddFormatterMappings(); //For further Swagger registration information: //https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger. services.AddSwaggerGen(openApiConfig => { openApiConfig.DescribeAllParametersInCamelCase(); //In the Swagger document this corresponds as follows: //http://localhost:4003/{SwaggerRoot}/{SwaggerDocumentationBasePath}/swagger.json openApiConfig.SwaggerDoc(SwaggerDocumentationBasePath, new OpenApiInfo { Title = "OneBoxDeployment APIs", //Note that this is information subject to change and with legal //consequences. In the future there needs to be a formal way to handle //these. //Also, for choosing licenses: //- https://go.developer.ebay.com/api-license-agreement //- https://www.zendesk.com/company/customers-partners/application-developer-api-license-agreement/ Contact = new OpenApiContact { Email = "contact@contact.com", Name = "OneBoxDeployment", Url = new Uri("https://contactinformationtobedefined.com") }, Description = "OneBoxDeployment application programming interface (API) descriptions.", License = new OpenApiLicense { Name = "The license name to be defined.", Url = new Uri("https://contactinformationtobedefined.com") }, TermsOfService = new Uri("https://choosealicense.com/licenses/") }); //The name of the comments file (see project properties). This is set automatically to the name //of the project unless explicitly changed. string commentsFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; string fullCommentsFilePath = Path.Combine(AppContext.BaseDirectory, commentsFilename); openApiConfig.IncludeXmlComments(fullCommentsFilePath, includeControllerXmlComments: true); }); services.AddHttpContextAccessor(); services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User); //A trick since the cluster configuration value from the in-memory provider is bound differently //to the JSON one. Here in-memory one takes presedence to the file one since in that case the values //come from the tests. Should be a flag or better yet, override properly... ClusterConfig clusterConfig = null; var clusterConfigValue = Configuration.GetSection(nameof(ClusterConfig)); if(clusterConfigValue?.Value != null) { var deserializeOptions = new JsonSerializerOptions(); deserializeOptions.Converters.Add(new IPAddressConverter()); clusterConfig = JsonSerializer.Deserialize<ClusterConfig>(clusterConfigValue.Value, deserializeOptions); } else { clusterConfig = Configuration.GetSection(nameof(ClusterConfig)).GetValid<ClusterConfig>(); } services.AddSingleton(Environment); services.AddSingleton(Configuration); var clientBuilder = new ClientBuilder() .ConfigureLogging(logging => logging.AddConsole()) .UsePerfCounterEnvironmentStatistics() .Configure<ClusterOptions>(options => { options.ClusterId = clusterConfig.ClusterOptions.ClusterId; options.ServiceId = clusterConfig.ClusterOptions.ServiceId; }) .UseAdoNetClustering(options => { options.Invariant = clusterConfig.ConnectionConfig.AdoNetConstant; options.ConnectionString = clusterConfig.ConnectionConfig.ConnectionString; }) .Configure<ClientMessagingOptions>(options => options.ResponseTimeout = TimeSpan.FromSeconds(30)) .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ITestStateGrain).Assembly).WithReferences()); var client = clientBuilder.Build(); client.Connect(async ex => { Logger.LogWarning("Could not connect to Orleans cluster: {exception}", ex); await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false); return true; }).GetAwaiter().GetResult(); services.AddSingleton(client); /*services.AddStartupTask<ClusterClientStartupTask>(); services .AddHealthChecks() .AddCheck<StartupTasksHealthCheck>("Startup tasks"); */ } /// <summary> /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. /// </summary> /// <param name="app">The application to configure.</param> /// <param name="env">The environment information to use in configuration phase.</param> /// <param name="applicationLifetime"></param> public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime) { app.UseProblemDetails(); if(!env.IsProduction()) { //This test middleware needs to be before developer exception pages. app.Use(TestMiddleware); app.UseDeveloperExceptionPage(); } //app.UseHealthChecks("/healthz"); //app.UseMiddleware<StartupTasksMiddleware>(); applicationLifetime.ApplicationStopping.Register(() => { }); //This ensures (or improves chances) to flush log buffers before (a graceful) shutdown. //It appears there isn't other way (e.g. in Program) than taking a reference to the global //static Serilog instance. applicationLifetime.ApplicationStopped.Register(Log.CloseAndFlush); //Security headers will always be added and by default the disallow everything. //The trimming is a robustness measure to make sure the URL has one trailing slash. //The listening address is needed for security headers. This is the public //API address. var appsettingsSection = Configuration.GetSection("AppSettings"); var listeningAddress = appsettingsSection["OneBoxDeploymentApiUrl"]; listeningAddress = (listeningAddress ?? app.ServerFeatures.Get<IServerAddressesFeature>().Addresses.FirstOrDefault()).EnsureTrailing('/'); //Note: the constructor checks ConfigurationKeys forbidden in production are not found. if(!env.IsProduction()) { //Creates a route to specifically throw and unhandled exception. This route is most likely injected only in testing. //This kind of testing middleware can be made to one code block guarded appropriately if there is more of it. var alwaysFaultyRoute = Configuration.GetValue<string>(ConfigurationKeys.AlwaysFaultyRoute, null); if(alwaysFaultyRoute != null) { app.Use((context, next) => { if(context.Request.Path.StartsWithSegments($"/{alwaysFaultyRoute}", out _, out _)) { throw new Exception($"Fault injected route for testing ({context.Request.PathBase}/{alwaysFaultyRoute})."); } return next(); }); } } Logger.LogInformation(Events.SwaggerDocumentation.Id, Events.SwaggerDocumentation.FormatString, listeningAddress + SwaggerRoot + "/"); var defaultSecurityPolicies = new HeaderPolicyCollection() .AddStrictTransportSecurityMaxAgeIncludeSubDomains(maxAgeInSeconds: 60 * 60 * 24 * 365) .RemoveServerHeader() .AddFrameOptionsDeny(); app.UseSecurityHeaders(defaultSecurityPolicies); app.UseWhen(ctx => ctx.Request.Path.StartsWithSegments("/" + SwaggerRoot), swaggerBranch => { //See configuration at https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders. const string GoogleStyles = "https://fonts.googleapis.com"; const string GoogleFontsUrl = "https://fonts.gstatic.com"; var clientUrl = Path.Combine(listeningAddress, SwaggerRoot).EnsureTrailing('/'); //Additional information for the many Feature-Policy none definitions: //https://github.com/w3c/webappsec-feature-policy/issues/189#issuecomment-452401661. swaggerBranch.UseSecurityHeaders(new HeaderPolicyCollection().AddFeaturePolicy(builder => { builder.AddAccelerometer().None(); builder.AddAmbientLightSensor().None(); builder.AddAutoplay().None(); builder.AddCamera().None(); builder.AddEncryptedMedia().None(); builder.AddFullscreen().None(); builder.AddGeolocation().None(); builder.AddGyroscope().None(); builder.AddMagnetometer().None(); builder.AddMicrophone().None(); builder.AddMidi().None(); builder.AddPayment().None(); builder.AddPictureInPicture().None(); builder.AddSpeaker().None(); builder.AddSyncXHR().None(); builder.AddUsb().None(); builder.AddVR().None(); }) .AddXssProtectionBlock() .AddContentTypeOptionsNoSniff() .AddReferrerPolicyStrictOriginWhenCrossOrigin() .AddContentSecurityPolicy(builder => { builder.AddReportUri().To("/cspreport"); builder.AddBlockAllMixedContent(); builder.AddConnectSrc().Self(); builder.AddStyleSrc().Self().UnsafeInline().Sources.Add(GoogleStyles); builder.AddFontSrc().Self().Sources.Add(GoogleFontsUrl); builder.AddImgSrc().Self().Sources.Add("data:"); builder.AddScriptSrc().Self().UnsafeInline(); builder.AddObjectSrc().None(); builder.AddFormAction().Self(); builder.AddFrameAncestors().None().Sources.Add(clientUrl); }, asReportOnly: false)); }); //For further Swagger related information, see at //https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger. app.UseSwagger(); app.UseSwagger(swagger => swagger.RouteTemplate = $"{SwaggerRoot}/{{documentName}}/swagger.json"); if(Configuration["HideSwaggerUi"]?.Equals("true") != true) { app.UseSwaggerUI(swaggerSetup => { swaggerSetup.SwaggerEndpoint($"/{SwaggerRoot}/{SwaggerDocumentationBasePath}/swagger.json", SwaggerDocumentationBasePath); swaggerSetup.RoutePrefix = SwaggerRoot; swaggerSetup.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream($"{Assembly.GetAssembly(typeof(Startup)).GetName().Name}.wwwroot.swagger.index.html"); }); } app.UseCors("CorsPolicy"); app.UseStaticFiles(); app.UseRouting(); //app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } private void ConfigureProblemDetails(ProblemDetailsOptions options) { // This is the default behavior; only include exception details in a development environment. options.IncludeExceptionDetails = (ctx, ex) => Environment.IsDevelopment(); options.OnBeforeWriteDetails = (ctx, details) => details.Instance = $"urn:oneboxdeployment:error:{ctx.TraceIdentifier}"; // You can configure the middleware to re-throw certain types of exceptions, all exceptions or based on a predicate. // This is useful if you have upstream middleware that needs to do additional handling of exceptions. options.Rethrow<NotSupportedException>(); // This will map NotImplementedException to the 501 Not Implemented status code. options.MapToStatusCode<NotImplementedException>(StatusCodes.Status501NotImplemented); // This will map HttpRequestException to the 503 Service Unavailable status code. options.MapToStatusCode<HttpRequestException>(StatusCodes.Status503ServiceUnavailable); // Because exceptions are handled polymorphically, this will act as a "catch all" mapping, which is why it's added last. // If an exception other than NotImplementedException and HttpRequestException is thrown, this will handle it. options.MapToStatusCode<Exception>(StatusCodes.Status500InternalServerError); } /// <summary> /// This middleware should be used only when testing. /// </summary> /// <param name="context">The call context.</param> /// <param name="next">Function to call next middlware in the pipeline.</param> private Task TestMiddleware(HttpContext context, Func<Task> next) { //Creates a route to specifically throw and unhandled exception. This route is most likely injected only in testing. var alwaysFaultyRoute = Configuration.GetValue<string>(ConfigurationKeys.AlwaysFaultyRoute, null); if(alwaysFaultyRoute != null && context.Request.Path.StartsWithSegments(alwaysFaultyRoute, out _, out _)) { throw new Exception("This is an exception thrown from middleware."); } return next(); } } }
// Session.cs // using System; using System.Collections.Generic; using KnockoutApi; using Xrm.Sdk; using System.Collections; using SparkleXrm; using System.Runtime.CompilerServices; namespace TimeSheet.Client.ViewModel { public class SessionVM { private bool _supressEvents = false; public Observable<Guid> dev1_sessionid = Knockout.Observable<Guid>(); public Observable<EntityReference> Activity = Knockout.Observable<EntityReference>(); public Observable<DateTime> dev1_starttime = Knockout.Observable<DateTime>(); public Observable<DateTime> dev1_endtime = Knockout.Observable<DateTime>(); public Observable<string> dev1_description = Knockout.Observable<string>(); public Observable<int?> dev1_duration = Knockout.Observable<int?>(); public Observable<string> StartTimeTime = Knockout.Observable<string>(); public Observable<string> EndTimeTime = Knockout.Observable<string>(); public Observable<string> TimeSoFar = Knockout.Observable<string>(); public Observable<string> test = Knockout.Observable<string>("test"); public SessionVM(StartStopSessionViewModel vm, dev1_session data) { if (data != null) { this.dev1_sessionid.SetValue(data.dev1_sessionId); this.dev1_description.SetValue(data.dev1_Description); this.dev1_duration.SetValue(data.dev1_Duration); this.dev1_endtime.SetValue(data.dev1_EndTime); this.dev1_starttime.SetValue(data.dev1_StartTime); // Calculate the time elements GetTime(dev1_starttime, StartTimeTime); GetTime(dev1_endtime, EndTimeTime); // Set activity if (data.dev1_LetterId != null) { this.Activity.SetValue(data.dev1_LetterId); } else if (data.dev1_TaskId != null) { this.Activity.SetValue(data.dev1_TaskId); } // TODO: Add more activity types } // Add events to calculate duration dev1_endtime.Subscribe(delegate(DateTime value) { OnStartEndDateChanged(); }); dev1_starttime.Subscribe(delegate(DateTime value) { OnStartEndDateChanged(); }); StartTimeTime.Subscribe(delegate(string value) { OnStartEndDateChanged(); }); EndTimeTime.Subscribe(delegate(string value) { OnStartEndDateChanged(); }); dev1_duration.Subscribe(delegate(int? value) { OnDurationChanged(); }); AddValidation(); } public void OnStartEndDateChanged() { if (_supressEvents) return; _supressEvents = true; DateTime startTime = dev1_starttime.GetValue(); DateTime endTime = dev1_endtime.GetValue(); int? duration = null; startTime = DateTimeEx.AddTimeToDate(startTime, StartTimeTime.GetValue()); endTime = DateTimeEx.AddTimeToDate(endTime, EndTimeTime.GetValue()); if (endTime != null && startTime != null) { endTime.SetDate(startTime.GetDate()); endTime.SetMonth(startTime.GetMonth()); endTime.SetFullYear(startTime.GetFullYear()); } duration= CalculateDuration(startTime, endTime); this.dev1_duration.SetValue(duration); _supressEvents = false; } public static int? CalculateDuration( DateTime startTime, DateTime endTime) { int? duration = null; if ((startTime != null) && (endTime != null)) { if ((startTime != null) && (endTime != null)) { duration = (endTime.GetTime() - startTime.GetTime()) / (1000 * 60); } } return duration; } public void OnDurationChanged() { if (_supressEvents) return; _supressEvents = true; DateTime startTime = dev1_starttime.GetValue(); string startTimeTime = StartTimeTime.GetValue(); if ((startTime != null) && (startTimeTime!=null)) { startTime = DateTimeEx.AddTimeToDate(startTime, startTimeTime); int? duration = dev1_duration.GetValue(); int? startTimeMilliSeconds = startTime.GetTime(); startTimeMilliSeconds = startTimeMilliSeconds + (duration * 1000 * 60); DateTime newEndDate = new DateTime((int)startTimeMilliSeconds); dev1_endtime.SetValue(newEndDate); GetTime(dev1_endtime, EndTimeTime); } _supressEvents = false; } public dev1_session GetUpdatedModel() { dev1_session session = new dev1_session(); SetTime(dev1_starttime, StartTimeTime); SetTime(dev1_endtime, EndTimeTime); KnockoutMappingSpecification mapping = new KnockoutMappingSpecification(); mapping.Ignore = new string[] { "dev1_letterid", "dev1_taskid", "dev1_emailid" }; if ( this.dev1_sessionid.GetValue()!=null) session.dev1_sessionId = this.dev1_sessionid.GetValue(); session.dev1_Description = this.dev1_description.GetValue(); session.dev1_StartTime = this.dev1_starttime.GetValue(); session.dev1_EndTime = this.dev1_endtime.GetValue(); session.dev1_Duration = this.dev1_duration.GetValue(); return session; } private void GetTime(Observable<DateTime> dateProperty,Observable<string> time) { DateTime dateValue = dateProperty.GetValue(); if (dateValue != null) { string timeFormatted = dateValue.Format("h:mm tt"); time.SetValue(timeFormatted); } } private void SetTime(Observable<DateTime> dateProperty, Observable<string> time) { DateTime currentDate = dateProperty.GetValue(); currentDate = DateTimeEx.AddTimeToDate(currentDate, time.GetValue()); dateProperty.SetValue(currentDate); } #region Methods public void AddValidation() { SessionVM self = this; ValidationRules.CreateRules() .AddRequiredMsg("Enter the activity you wish to stop") .Register(Activity); ValidationRules.CreateRules() .AddRequiredMsg("Enter the start date of the session") .AddRule("Start date must be before the end date",delegate(object value) { bool isValid = true; DateTime endTime = self.dev1_endtime.GetValue(); if ((endTime != null) && (value!=null)) isValid = endTime > (DateTime)value; return isValid; }) .Register(dev1_starttime); ValidationRules.CreateRules() .AddRequiredMsg("Enter the end time of the session") .Register(dev1_endtime); ValidationRules.CreateRules() .AddRequiredMsg("Enter the duration of the session") .Register(dev1_duration); } #endregion } }
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Daniel Kollmann // 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 Daniel Kollmann 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 Brainiac.Design { partial class EditWorkspaceDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.doneButton = new System.Windows.Forms.Button(); this.cancelButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.nameTextBox = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.checkedListBox = new System.Windows.Forms.CheckedListBox(); this.label3 = new System.Windows.Forms.Label(); this.behaviorFolderTextBox = new System.Windows.Forms.TextBox(); this.behaviorFolderButton = new System.Windows.Forms.Button(); this.folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog(); this.exportFolderButton = new System.Windows.Forms.Button(); this.exportFolderTextBox = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // doneButton // this.doneButton.Location = new System.Drawing.Point(15, 328); this.doneButton.Name = "doneButton"; this.doneButton.Size = new System.Drawing.Size(75, 21); this.doneButton.TabIndex = 6; this.doneButton.Text = "Done"; this.doneButton.UseVisualStyleBackColor = true; this.doneButton.Click += new System.EventHandler(this.doneButton_Click); // // cancelButton // this.cancelButton.Location = new System.Drawing.Point(197, 328); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 21); this.cancelButton.TabIndex = 7; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(43, 13); this.label1.TabIndex = 2; this.label1.Text = "Name:"; // // nameTextBox // this.nameTextBox.Location = new System.Drawing.Point(15, 23); this.nameTextBox.Name = "nameTextBox"; this.nameTextBox.Size = new System.Drawing.Size(257, 21); this.nameTextBox.TabIndex = 0; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 54); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(52, 13); this.label2.TabIndex = 4; this.label2.Text = "Plugins:"; // // checkedListBox // this.checkedListBox.FormattingEnabled = true; this.checkedListBox.Location = new System.Drawing.Point(15, 69); this.checkedListBox.Name = "checkedListBox"; this.checkedListBox.Size = new System.Drawing.Size(257, 84); this.checkedListBox.TabIndex = 1; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(12, 172); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(96, 13); this.label3.TabIndex = 5; this.label3.Text = "Behavior Folder"; // // behaviorFolderTextBox // this.behaviorFolderTextBox.Location = new System.Drawing.Point(15, 186); this.behaviorFolderTextBox.Name = "behaviorFolderTextBox"; this.behaviorFolderTextBox.Size = new System.Drawing.Size(176, 21); this.behaviorFolderTextBox.TabIndex = 2; // // behaviorFolderButton // this.behaviorFolderButton.Location = new System.Drawing.Point(197, 186); this.behaviorFolderButton.Name = "behaviorFolderButton"; this.behaviorFolderButton.Size = new System.Drawing.Size(75, 21); this.behaviorFolderButton.TabIndex = 3; this.behaviorFolderButton.Text = "Browse"; this.behaviorFolderButton.UseVisualStyleBackColor = true; this.behaviorFolderButton.Click += new System.EventHandler(this.browseButton_Click); // // folderBrowserDialog // this.folderBrowserDialog.Description = "Select Behavior Folder"; // // exportFolderButton // this.exportFolderButton.Location = new System.Drawing.Point(197, 226); this.exportFolderButton.Name = "exportFolderButton"; this.exportFolderButton.Size = new System.Drawing.Size(75, 21); this.exportFolderButton.TabIndex = 5; this.exportFolderButton.Text = "Browse"; this.exportFolderButton.UseVisualStyleBackColor = true; this.exportFolderButton.Click += new System.EventHandler(this.exportFolderButton_Click); // // exportFolderTextBox // this.exportFolderTextBox.Location = new System.Drawing.Point(15, 226); this.exportFolderTextBox.Name = "exportFolderTextBox"; this.exportFolderTextBox.Size = new System.Drawing.Size(176, 21); this.exportFolderTextBox.TabIndex = 4; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(12, 211); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(127, 13); this.label4.TabIndex = 8; this.label4.Text = "Default Export Folder"; // // EditWorkspaceDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 360); this.ControlBox = false; this.Controls.Add(this.exportFolderButton); this.Controls.Add(this.exportFolderTextBox); this.Controls.Add(this.label4); this.Controls.Add(this.behaviorFolderButton); this.Controls.Add(this.behaviorFolderTextBox); this.Controls.Add(this.label3); this.Controls.Add(this.checkedListBox); this.Controls.Add(this.label2); this.Controls.Add(this.nameTextBox); this.Controls.Add(this.label1); this.Controls.Add(this.cancelButton); this.Controls.Add(this.doneButton); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Name = "EditWorkspaceDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Create New Workspace"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button doneButton; private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox nameTextBox; private System.Windows.Forms.Label label2; private System.Windows.Forms.CheckedListBox checkedListBox; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox behaviorFolderTextBox; private System.Windows.Forms.Button behaviorFolderButton; private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog; private System.Windows.Forms.Button exportFolderButton; private System.Windows.Forms.TextBox exportFolderTextBox; private System.Windows.Forms.Label label4; } }
// 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.Reflection; using Gallio.Common.Collections; using Gallio.Properties; namespace Gallio.Runtime.ConsoleSupport { /// <summary> /// Allows control of command line parsing. /// </summary> /// <remarks> /// <para> /// Attach this attribute to instance fields of types used /// as the destination of command line argument parsing. /// </para> /// <para> /// Command line parsing code from /// <a href="http://www.gotdotnet.com/community/usersamples/details.aspx?sampleguid=62a0f27e-274e-4228-ba7f-bc0118ecc41e"> /// Peter Halam</a>. /// </para> /// </remarks> [AttributeUsage(AttributeTargets.Field,AllowMultiple=false,Inherited=true)] public class CommandLineArgumentAttribute : Attribute { private readonly CommandLineArgumentFlags flags; private string shortName; private string longName; private string description = @""; private string valueLabel; private string[] synonyms = EmptyArray<string>.Instance; private Type resourceType; /// <summary> /// Allows control of command line parsing. /// </summary> /// <param name="flags">Specifies the error checking to be done on the argument.</param> public CommandLineArgumentAttribute(CommandLineArgumentFlags flags) { this.flags = flags; } /// <summary> /// The error checking to be done on the argument. /// </summary> public CommandLineArgumentFlags Flags { get { return flags; } } /// <summary> /// Returns true if the argument did not have an explicit short name specified. /// </summary> public bool IsDefaultShortName { get { return null == shortName; } } /// <summary> /// The short name of the argument. /// </summary> public string ShortName { get { return shortName; } set { shortName = value; } } /// <summary> /// The localized short name of the argument. /// </summary> public string LocalizedShortName { get { return GetResourceLookup(shortName); } } /// <summary> /// Returns true if the argument did not have an explicit long name specified. /// </summary> public bool IsDefaultLongName { get { return null == longName; } } /// <summary> /// The long name of the argument. /// </summary> public string LongName { get { return longName; } set { longName = value; } } /// <summary> /// The localized long name of the argument. /// </summary> public string LocalizedLongName { get { return GetResourceLookup(longName); } } /// <summary> /// The description of the argument. /// </summary> public string Description { get { return description; } set { description = value; } } /// <summary> /// The localized description of the argument. /// </summary> public string LocalizedDescription { get { return GetResourceLookup(description); } } ///<summary> /// The description of the argument value. ///</summary> public string ValueLabel { get { return valueLabel; } set { valueLabel = value; } } ///<summary> /// The localized description of the argument value. ///</summary> public string LocalizedValueLabel { get { return GetResourceLookup(valueLabel); } } /// <summary> /// Gets or sets an array of additional synonyms that are silently accepted. /// </summary> public string[] Synonyms { get { return synonyms; } set { synonyms = value; } } /// <summary> /// Gets an array of localized additional synonyms that are silently accepted. /// </summary> public string[] LocalizedSynonyms { get { return GenericCollectionUtils.ConvertAllToArray<string, string>(synonyms, GetResourceLookup); } } /// <summary> /// Gets or sets a resource to use for internationalization of strings /// </summary> public Type ResourceType { get { return resourceType; } set { resourceType = value; } } /// <summary> /// Gets or sets a resource to use for localization of strings /// </summary> private string GetResourceLookup(string resourceName) { if (resourceName == null) { return null; } if (resourceName.StartsWith("#")) { if (resourceType == null) throw new InvalidOperationException(Resources.CommandLineArgumentAttribute_NoResourceException); PropertyInfo property = resourceType.GetProperty(resourceName.Substring(1), BindingFlags.NonPublic | BindingFlags.Static); if (property == null) { throw new InvalidOperationException(Resources.CommandLineArgumentAttribute_ResourceNotFoundException); } if (property.PropertyType != typeof(string)) { throw new InvalidOperationException(Resources.CommandLineArgumentAttribute_ResourceNotAStringException); } return (string)property.GetValue(null, null); } else { return resourceName; } } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="ASM.LoggingProfileBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonIPPortDefinition))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ASMLoggingProfileDefinition))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ASMLoggingRemoteStorageBase))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ASMLoggingRequestSearch))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(ASMLoggingStorageFormat))] public partial class ASMLoggingProfile : iControlInterface { public ASMLoggingProfile() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_remote_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void add_remote_server( string [] logprof_names, CommonIPPortDefinition [] [] ip_ports ) { this.Invoke("add_remote_server", new object [] { logprof_names, ip_ports}); } public System.IAsyncResult Beginadd_remote_server(string [] logprof_names,CommonIPPortDefinition [] [] ip_ports, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_remote_server", new object[] { logprof_names, ip_ports}, callback, asyncState); } public void Endadd_remote_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // apply_logprof //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void apply_logprof( string [] logprof_names ) { this.Invoke("apply_logprof", new object [] { logprof_names}); } public System.IAsyncResult Beginapply_logprof(string [] logprof_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("apply_logprof", new object[] { logprof_names}, callback, asyncState); } public void Endapply_logprof(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void create( string [] logprof_names ) { this.Invoke("create", new object [] { logprof_names}); } public System.IAsyncResult Begincreate(string [] logprof_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { logprof_names}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_logprof //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void delete_logprof( string [] logprof_names ) { this.Invoke("delete_logprof", new object [] { logprof_names}); } public System.IAsyncResult Begindelete_logprof(string [] logprof_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_logprof", new object[] { logprof_names}, callback, asyncState); } public void Enddelete_logprof(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_logprof //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public ASMLoggingProfileDefinition [] get_logprof( string [] logprof_names ) { object [] results = this.Invoke("get_logprof", new object [] { logprof_names}); return ((ASMLoggingProfileDefinition [])(results[0])); } public System.IAsyncResult Beginget_logprof(string [] logprof_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_logprof", new object[] { logprof_names}, callback, asyncState); } public ASMLoggingProfileDefinition [] Endget_logprof(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((ASMLoggingProfileDefinition [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_remote_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void remove_remote_server( string [] logprof_names, CommonIPPortDefinition [] [] ip_ports ) { this.Invoke("remove_remote_server", new object [] { logprof_names, ip_ports}); } public System.IAsyncResult Beginremove_remote_server(string [] logprof_names,CommonIPPortDefinition [] [] ip_ports, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_remote_server", new object[] { logprof_names, ip_ports}, callback, asyncState); } public void Endremove_remote_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // rename //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void rename( string [] logprof_names, string [] new_logprof_names ) { this.Invoke("rename", new object [] { logprof_names, new_logprof_names}); } public System.IAsyncResult Beginrename(string [] logprof_names,string [] new_logprof_names, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("rename", new object[] { logprof_names, new_logprof_names}, callback, asyncState); } public void Endrename(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // replace_http_method //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void replace_http_method( string [] logprof_names, string [] [] http_methods ) { this.Invoke("replace_http_method", new object [] { logprof_names, http_methods}); } public System.IAsyncResult Beginreplace_http_method(string [] logprof_names,string [] [] http_methods, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("replace_http_method", new object[] { logprof_names, http_methods}, callback, asyncState); } public void Endreplace_http_method(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // replace_response_code //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void replace_response_code( string [] logprof_names, long [] [] response_codes ) { this.Invoke("replace_response_code", new object [] { logprof_names, response_codes}); } public System.IAsyncResult Beginreplace_response_code(string [] logprof_names,long [] [] response_codes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("replace_response_code", new object[] { logprof_names, response_codes}, callback, asyncState); } public void Endreplace_response_code(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_description( string [] logprof_names, string [] descriptions ) { this.Invoke("set_description", new object [] { logprof_names, descriptions}); } public System.IAsyncResult Beginset_description(string [] logprof_names,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_description", new object[] { logprof_names, descriptions}, callback, asyncState); } public void Endset_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_filter_protocol //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_filter_protocol( string [] logprof_names, ASMProtocolType [] filter_protocols ) { this.Invoke("set_filter_protocol", new object [] { logprof_names, filter_protocols}); } public System.IAsyncResult Beginset_filter_protocol(string [] logprof_names,ASMProtocolType [] filter_protocols, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_filter_protocol", new object[] { logprof_names, filter_protocols}, callback, asyncState); } public void Endset_filter_protocol(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_guarantee_logging_flag //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_guarantee_logging_flag( string [] logprof_names, bool [] guarantee_logging_flags ) { this.Invoke("set_guarantee_logging_flag", new object [] { logprof_names, guarantee_logging_flags}); } public System.IAsyncResult Beginset_guarantee_logging_flag(string [] logprof_names,bool [] guarantee_logging_flags, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_guarantee_logging_flag", new object[] { logprof_names, guarantee_logging_flags}, callback, asyncState); } public void Endset_guarantee_logging_flag(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_local_storage_flag //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_local_storage_flag( string [] logprof_names, bool [] local_storage_flags ) { this.Invoke("set_local_storage_flag", new object [] { logprof_names, local_storage_flags}); } public System.IAsyncResult Beginset_local_storage_flag(string [] logprof_names,bool [] local_storage_flags, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_local_storage_flag", new object[] { logprof_names, local_storage_flags}, callback, asyncState); } public void Endset_local_storage_flag(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_logic_operation //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_logic_operation( string [] logprof_names, ASMLoggingLogicOperation [] logic_operations ) { this.Invoke("set_logic_operation", new object [] { logprof_names, logic_operations}); } public System.IAsyncResult Beginset_logic_operation(string [] logprof_names,ASMLoggingLogicOperation [] logic_operations, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_logic_operation", new object[] { logprof_names, logic_operations}, callback, asyncState); } public void Endset_logic_operation(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_entry_length //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_maximum_entry_length( string [] logprof_names, long [] maximum_entry_lengths ) { this.Invoke("set_maximum_entry_length", new object [] { logprof_names, maximum_entry_lengths}); } public System.IAsyncResult Beginset_maximum_entry_length(string [] logprof_names,long [] maximum_entry_lengths, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_entry_length", new object[] { logprof_names, maximum_entry_lengths}, callback, asyncState); } public void Endset_maximum_entry_length(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_header_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_maximum_header_size( string [] logprof_names, long [] maximum_header_sizes ) { this.Invoke("set_maximum_header_size", new object [] { logprof_names, maximum_header_sizes}); } public System.IAsyncResult Beginset_maximum_header_size(string [] logprof_names,long [] maximum_header_sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_header_size", new object[] { logprof_names, maximum_header_sizes}, callback, asyncState); } public void Endset_maximum_header_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_query_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_maximum_query_size( string [] logprof_names, long [] maximum_query_sizes ) { this.Invoke("set_maximum_query_size", new object [] { logprof_names, maximum_query_sizes}); } public System.IAsyncResult Beginset_maximum_query_size(string [] logprof_names,long [] maximum_query_sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_query_size", new object[] { logprof_names, maximum_query_sizes}, callback, asyncState); } public void Endset_maximum_query_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_maximum_request_size //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_maximum_request_size( string [] logprof_names, long [] maximum_request_sizes ) { this.Invoke("set_maximum_request_size", new object [] { logprof_names, maximum_request_sizes}); } public System.IAsyncResult Beginset_maximum_request_size(string [] logprof_names,long [] maximum_request_sizes, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_maximum_request_size", new object[] { logprof_names, maximum_request_sizes}, callback, asyncState); } public void Endset_maximum_request_size(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_remote_log_facility //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_remote_log_facility( string [] logprof_names, ASMLoggingRemoteFacility [] remote_log_facilities ) { this.Invoke("set_remote_log_facility", new object [] { logprof_names, remote_log_facilities}); } public System.IAsyncResult Beginset_remote_log_facility(string [] logprof_names,ASMLoggingRemoteFacility [] remote_log_facilities, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_remote_log_facility", new object[] { logprof_names, remote_log_facilities}, callback, asyncState); } public void Endset_remote_log_facility(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_remote_protocol //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_remote_protocol( string [] logprof_names, ASMLoggingRemoteProtocol [] remote_protocols ) { this.Invoke("set_remote_protocol", new object [] { logprof_names, remote_protocols}); } public System.IAsyncResult Beginset_remote_protocol(string [] logprof_names,ASMLoggingRemoteProtocol [] remote_protocols, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_remote_protocol", new object[] { logprof_names, remote_protocols}, callback, asyncState); } public void Endset_remote_protocol(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_remote_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_remote_server( string [] logprof_names, CommonIPPortDefinition [] ip_ports ) { this.Invoke("set_remote_server", new object [] { logprof_names, ip_ports}); } public System.IAsyncResult Beginset_remote_server(string [] logprof_names,CommonIPPortDefinition [] ip_ports, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_remote_server", new object[] { logprof_names, ip_ports}, callback, asyncState); } public void Endset_remote_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_remote_storage_base //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_remote_storage_base( string [] logprof_names, ASMLoggingRemoteStorageBase [] remote_storage_bases ) { this.Invoke("set_remote_storage_base", new object [] { logprof_names, remote_storage_bases}); } public System.IAsyncResult Beginset_remote_storage_base(string [] logprof_names,ASMLoggingRemoteStorageBase [] remote_storage_bases, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_remote_storage_base", new object[] { logprof_names, remote_storage_bases}, callback, asyncState); } public void Endset_remote_storage_base(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_report_anomalies_flag //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_report_anomalies_flag( string [] logprof_names, bool [] report_anomalies_flags ) { this.Invoke("set_report_anomalies_flag", new object [] { logprof_names, report_anomalies_flags}); } public System.IAsyncResult Beginset_report_anomalies_flag(string [] logprof_names,bool [] report_anomalies_flags, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_report_anomalies_flag", new object[] { logprof_names, report_anomalies_flags}, callback, asyncState); } public void Endset_report_anomalies_flag(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_request_search //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_request_search( string [] logprof_names, ASMLoggingRequestSearch [] request_searches ) { this.Invoke("set_request_search", new object [] { logprof_names, request_searches}); } public System.IAsyncResult Beginset_request_search(string [] logprof_names,ASMLoggingRequestSearch [] request_searches, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_request_search", new object[] { logprof_names, request_searches}, callback, asyncState); } public void Endset_request_search(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_request_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_request_type( string [] logprof_names, ASMLoggingRequestType [] request_types ) { this.Invoke("set_request_type", new object [] { logprof_names, request_types}); } public System.IAsyncResult Beginset_request_type(string [] logprof_names,ASMLoggingRequestType [] request_types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_request_type", new object[] { logprof_names, request_types}, callback, asyncState); } public void Endset_request_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_search_pattern //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_search_pattern( string [] logprof_names, string [] search_patterns ) { this.Invoke("set_search_pattern", new object [] { logprof_names, search_patterns}); } public System.IAsyncResult Beginset_search_pattern(string [] logprof_names,string [] search_patterns, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_search_pattern", new object[] { logprof_names, search_patterns}, callback, asyncState); } public void Endset_search_pattern(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_storage_format //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:ASM/LoggingProfile", RequestNamespace="urn:iControl:ASM/LoggingProfile", ResponseNamespace="urn:iControl:ASM/LoggingProfile")] public void set_storage_format( string [] logprof_names, ASMLoggingStorageFormat [] storage_formats ) { this.Invoke("set_storage_format", new object [] { logprof_names, storage_formats}); } public System.IAsyncResult Beginset_storage_format(string [] logprof_names,ASMLoggingStorageFormat [] storage_formats, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_storage_format", new object[] { logprof_names, storage_formats}, callback, asyncState); } public void Endset_storage_format(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= //======================================================================= // Structs //======================================================================= }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Runtime.Serialization { internal class SchemaExporter { private XmlSchemaSet _schemas; private XmlDocument _xmlDoc; private DataContractSet _dataContractSet; internal SchemaExporter(XmlSchemaSet schemas, DataContractSet dataContractSet) { _schemas = schemas; _dataContractSet = dataContractSet; } private XmlSchemaSet Schemas { get { return _schemas; } } private XmlDocument XmlDoc { get { if (_xmlDoc == null) _xmlDoc = new XmlDocument(); return _xmlDoc; } } internal void Export() { try { // Remove this if we decide to publish serialization schema at well-known location ExportSerializationSchema(); foreach (KeyValuePair<XmlQualifiedName, DataContract> pair in _dataContractSet) { DataContract dataContract = pair.Value; if (!_dataContractSet.IsContractProcessed(dataContract)) { ExportDataContract(dataContract); _dataContractSet.SetContractProcessed(dataContract); } } } finally { _xmlDoc = null; _dataContractSet = null; } } private void ExportSerializationSchema() { if (!Schemas.Contains(Globals.SerializationNamespace)) { StringReader reader = new StringReader(Globals.SerializationSchema); XmlSchema schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null); if (schema == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace))); Schemas.Add(schema); } } private void ExportDataContract(DataContract dataContract) { if (dataContract.IsBuiltInDataContract) return; else if (dataContract is XmlDataContract) ExportXmlDataContract((XmlDataContract)dataContract); else { XmlSchema schema = GetSchema(dataContract.StableName.Namespace); if (dataContract is ClassDataContract) { ClassDataContract classDataContract = (ClassDataContract)dataContract; if (classDataContract.IsISerializable) ExportISerializableDataContract(classDataContract, schema); else ExportClassDataContract(classDataContract, schema); } else if (dataContract is CollectionDataContract) ExportCollectionDataContract((CollectionDataContract)dataContract, schema); else if (dataContract is EnumDataContract) ExportEnumDataContract((EnumDataContract)dataContract, schema); ExportTopLevelElement(dataContract, schema); Schemas.Reprocess(schema); } } private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema schema) { if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace.Value) schema = GetSchema(dataContract.TopLevelElementNamespace.Value); XmlSchemaElement topLevelElement = new XmlSchemaElement(); topLevelElement.Name = dataContract.TopLevelElementName.Value; SetElementType(topLevelElement, dataContract, schema); topLevelElement.IsNillable = true; schema.Items.Add(topLevelElement); return topLevelElement; } private void ExportClassDataContract(ClassDataContract classDataContract, XmlSchema schema) { XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = classDataContract.StableName.Name; schema.Items.Add(type); XmlElement genericInfoElement = null; if (classDataContract.UnderlyingType.IsGenericType) genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); XmlSchemaSequence rootSequence = new XmlSchemaSequence(); for (int i = 0; i < classDataContract.Members.Count; i++) { DataMember dataMember = classDataContract.Members[i]; XmlSchemaElement element = new XmlSchemaElement(); element.Name = dataMember.Name; XmlElement actualTypeElement = null; DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember); if (CheckIfMemberHasConflict(dataMember)) { element.SchemaTypeName = AnytypeQualifiedName; actualTypeElement = ExportActualType(memberTypeContract.StableName); SchemaHelper.AddSchemaImport(memberTypeContract.StableName.Namespace, schema); } else SetElementType(element, memberTypeContract, schema); SchemaHelper.AddElementForm(element, schema); if (dataMember.IsNullable) element.IsNillable = true; if (!dataMember.IsRequired) element.MinOccurs = 0; element.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(dataMember), ExportEmitDefaultValue(dataMember)); rootSequence.Items.Add(element); } XmlElement isValueTypeElement = null; if (classDataContract.BaseContract != null) { XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema); extension.Particle = rootSequence; if (classDataContract.IsReference && !classDataContract.BaseContract.IsReference) { AddReferenceAttributes(extension.Attributes, schema); } } else { type.Particle = rootSequence; if (classDataContract.IsValueType) isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(classDataContract.IsValueType), schema); if (classDataContract.IsReference) AddReferenceAttributes(type.Attributes, schema); } type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(classDataContract), isValueTypeElement); } private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSchema schema) { SchemaHelper.AddSchemaImport(Globals.SerializationNamespace, schema); schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace); attributes.Add(IdAttribute); attributes.Add(RefAttribute); } private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) { XmlDataContract xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) { element.SchemaType = xmlDataContract.XsdType; } else { element.SchemaTypeName = dataContract.StableName; if (element.SchemaTypeName.Namespace.Equals(Globals.SerializationNamespace)) schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace); SchemaHelper.AddSchemaImport(dataContract.StableName.Namespace, schema); } } private bool CheckIfMemberHasConflict(DataMember dataMember) { if (dataMember.HasConflictingNameAndType) return true; DataMember conflictingMember = dataMember.ConflictingMember; while (conflictingMember != null) { if (conflictingMember.HasConflictingNameAndType) return true; conflictingMember = conflictingMember.ConflictingMember; } return false; } private XmlElement ExportEmitDefaultValue(DataMember dataMember) { if (dataMember.EmitDefaultValue) return null; XmlElement defaultValueElement = XmlDoc.CreateElement(DefaultValueAnnotation.Name, DefaultValueAnnotation.Namespace); XmlAttribute emitDefaultValueAttribute = XmlDoc.CreateAttribute(Globals.EmitDefaultValueAttribute); emitDefaultValueAttribute.Value = Globals.False; defaultValueElement.Attributes.Append(emitDefaultValueAttribute); return defaultValueElement; } private XmlElement ExportActualType(XmlQualifiedName typeName) { return ExportActualType(typeName, XmlDoc); } private static XmlElement ExportActualType(XmlQualifiedName typeName, XmlDocument xmlDoc) { XmlElement actualTypeElement = xmlDoc.CreateElement(ActualTypeAnnotationName.Name, ActualTypeAnnotationName.Namespace); XmlAttribute nameAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNameAttribute); nameAttribute.Value = typeName.Name; actualTypeElement.Attributes.Append(nameAttribute); XmlAttribute nsAttribute = xmlDoc.CreateAttribute(Globals.ActualTypeNamespaceAttribute); nsAttribute.Value = typeName.Namespace; actualTypeElement.Attributes.Append(nsAttribute); return actualTypeElement; } private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs) { Type itemType; int nestedCollectionLevel = 0; while (CollectionDataContract.IsCollection(clrType, out itemType)) { if (DataContract.GetBuiltInDataContract(clrType) != null || CollectionDataContract.IsCollectionDataContract(clrType)) { break; } clrType = itemType; nestedCollectionLevel++; } Type[] genericArguments = null; IList<int> genericArgumentCounts = null; if (clrType.IsGenericType) { genericArguments = clrType.GetGenericArguments(); string typeName; if (clrType.DeclaringType == null) typeName = clrType.Name; else { int nsLen = (clrType.Namespace == null) ? 0 : clrType.Namespace.Length; if (nsLen > 0) nsLen++; //include the . following namespace typeName = DataContract.GetClrTypeFullName(clrType).Substring(nsLen).Replace('+', '.'); } int iParam = typeName.IndexOf('['); if (iParam >= 0) typeName = typeName.Substring(0, iParam); genericArgumentCounts = DataContract.GetDataContractNameForGenericName(typeName, null); clrType = clrType.GetGenericTypeDefinition(); } XmlQualifiedName dcqname = DataContract.GetStableName(clrType); if (nestedCollectionLevel > 0) { string collectionName = dcqname.Name; for (int n = 0; n < nestedCollectionLevel; n++) collectionName = Globals.ArrayPrefix + collectionName; dcqname = new XmlQualifiedName(collectionName, DataContract.GetCollectionNamespace(dcqname.Namespace)); } XmlElement typeElement = XmlDoc.CreateElement(elementName, elementNs); XmlAttribute nameAttribute = XmlDoc.CreateAttribute(Globals.GenericNameAttribute); nameAttribute.Value = genericArguments != null ? XmlConvert.DecodeName(dcqname.Name) : dcqname.Name; //nameAttribute.Value = dcqname.Name; typeElement.Attributes.Append(nameAttribute); XmlAttribute nsAttribute = XmlDoc.CreateAttribute(Globals.GenericNamespaceAttribute); nsAttribute.Value = dcqname.Namespace; typeElement.Attributes.Append(nsAttribute); if (genericArguments != null) { int argIndex = 0; int nestedLevel = 0; foreach (int genericArgumentCount in genericArgumentCounts) { for (int i = 0; i < genericArgumentCount; i++, argIndex++) { XmlElement argumentElement = ExportGenericInfo(genericArguments[argIndex], Globals.GenericParameterLocalName, Globals.SerializationNamespace); if (nestedLevel > 0) { XmlAttribute nestedLevelAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute); nestedLevelAttribute.Value = nestedLevel.ToString(CultureInfo.InvariantCulture); argumentElement.Attributes.Append(nestedLevelAttribute); } typeElement.AppendChild(argumentElement); } nestedLevel++; } if (genericArgumentCounts[nestedLevel - 1] == 0) { XmlAttribute typeNestedLevelsAttribute = XmlDoc.CreateAttribute(Globals.GenericParameterNestedLevelAttribute); typeNestedLevelsAttribute.Value = genericArgumentCounts.Count.ToString(CultureInfo.InvariantCulture); typeElement.Attributes.Append(typeNestedLevelsAttribute); } } return typeElement; } private XmlElement ExportSurrogateData(object key) { // IDataContractSurrogate is not available on NetCore. return null; } private void ExportCollectionDataContract(CollectionDataContract collectionDataContract, XmlSchema schema) { XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = collectionDataContract.StableName.Name; schema.Items.Add(type); XmlElement genericInfoElement = null, isDictionaryElement = null; if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType)) genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); if (collectionDataContract.IsDictionary) isDictionaryElement = ExportIsDictionary(); type.Annotation = GetSchemaAnnotation(isDictionaryElement, genericInfoElement, ExportSurrogateData(collectionDataContract)); XmlSchemaSequence rootSequence = new XmlSchemaSequence(); XmlSchemaElement element = new XmlSchemaElement(); element.Name = collectionDataContract.ItemName; element.MinOccurs = 0; element.MaxOccursString = Globals.OccursUnbounded; if (collectionDataContract.IsDictionary) { ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract; XmlSchemaComplexType keyValueType = new XmlSchemaComplexType(); XmlSchemaSequence keyValueSequence = new XmlSchemaSequence(); foreach (DataMember dataMember in keyValueContract.Members) { XmlSchemaElement keyValueElement = new XmlSchemaElement(); keyValueElement.Name = dataMember.Name; SetElementType(keyValueElement, _dataContractSet.GetMemberTypeDataContract(dataMember), schema); SchemaHelper.AddElementForm(keyValueElement, schema); if (dataMember.IsNullable) keyValueElement.IsNillable = true; keyValueElement.Annotation = GetSchemaAnnotation(ExportSurrogateData(dataMember)); keyValueSequence.Items.Add(keyValueElement); } keyValueType.Particle = keyValueSequence; element.SchemaType = keyValueType; } else { if (collectionDataContract.IsItemTypeNullable) element.IsNillable = true; DataContract itemContract = _dataContractSet.GetItemTypeDataContract(collectionDataContract); SetElementType(element, itemContract, schema); } SchemaHelper.AddElementForm(element, schema); rootSequence.Items.Add(element); type.Particle = rootSequence; if (collectionDataContract.IsReference) AddReferenceAttributes(type.Attributes, schema); } private XmlElement ExportIsDictionary() { XmlElement isDictionaryElement = XmlDoc.CreateElement(IsDictionaryAnnotationName.Name, IsDictionaryAnnotationName.Namespace); isDictionaryElement.InnerText = Globals.True; return isDictionaryElement; } private void ExportEnumDataContract(EnumDataContract enumDataContract, XmlSchema schema) { XmlSchemaSimpleType type = new XmlSchemaSimpleType(); type.Name = enumDataContract.StableName.Name; XmlElement actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName); type.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(enumDataContract)); schema.Items.Add(type); XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = StringQualifiedName; SchemaHelper.AddSchemaImport(enumDataContract.BaseContractName.Namespace, schema); if (enumDataContract.Values != null) { for (int i = 0; i < enumDataContract.Values.Count; i++) { XmlSchemaEnumerationFacet facet = new XmlSchemaEnumerationFacet(); facet.Value = enumDataContract.Members[i].Name; if (enumDataContract.Values[i] != GetDefaultEnumValue(enumDataContract.IsFlags, i)) facet.Annotation = GetSchemaAnnotation(EnumerationValueAnnotationName, enumDataContract.GetStringFromEnumValue(enumDataContract.Values[i]), schema); restriction.Facets.Add(facet); } } if (enumDataContract.IsFlags) { XmlSchemaSimpleTypeList list = new XmlSchemaSimpleTypeList(); XmlSchemaSimpleType anonymousType = new XmlSchemaSimpleType(); anonymousType.Content = restriction; list.ItemType = anonymousType; type.Content = list; } else type.Content = restriction; } internal static long GetDefaultEnumValue(bool isFlags, int index) { return isFlags ? (long)Math.Pow(2, index) : index; } private void ExportISerializableDataContract(ClassDataContract dataContract, XmlSchema schema) { XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = dataContract.StableName.Name; schema.Items.Add(type); XmlElement genericInfoElement = null; if (dataContract.UnderlyingType.IsGenericType) genericInfoElement = ExportGenericInfo(dataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); XmlElement isValueTypeElement = null; if (dataContract.BaseContract != null) { XmlSchemaComplexContentExtension extension = CreateTypeContent(type, dataContract.BaseContract.StableName, schema); } else { schema.Namespaces.Add(Globals.SerPrefixForSchema, Globals.SerializationNamespace); type.Particle = ISerializableSequence; XmlSchemaAttribute iSerializableFactoryTypeAttribute = ISerializableFactoryTypeAttribute; type.Attributes.Add(iSerializableFactoryTypeAttribute); SchemaHelper.AddSchemaImport(ISerializableFactoryTypeAttribute.RefName.Namespace, schema); if (dataContract.IsValueType) isValueTypeElement = GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema); } type.Annotation = GetSchemaAnnotation(genericInfoElement, ExportSurrogateData(dataContract), isValueTypeElement); } private XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType type, XmlQualifiedName baseTypeName, XmlSchema schema) { SchemaHelper.AddSchemaImport(baseTypeName.Namespace, schema); XmlSchemaComplexContentExtension extension = new XmlSchemaComplexContentExtension(); extension.BaseTypeName = baseTypeName; type.ContentModel = new XmlSchemaComplexContent(); type.ContentModel.Content = extension; return extension; } private void ExportXmlDataContract(XmlDataContract dataContract) { XmlQualifiedName typeQName; bool hasRoot; XmlSchemaType xsdType; Type clrType = dataContract.UnderlyingType; if (!IsSpecialXmlType(clrType, out typeQName, out xsdType, out hasRoot)) if (!InvokeSchemaProviderMethod(clrType, _schemas, out typeQName, out xsdType, out hasRoot)) InvokeGetSchemaMethod(clrType, _schemas, typeQName); if (hasRoot) { if (!(typeQName.Equals(dataContract.StableName))) { Fx.Assert("XML data contract type name does not match schema name"); } XmlSchema schema; if (SchemaHelper.GetSchemaElement(Schemas, new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value), out schema) == null) { XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema); topLevelElement.IsNillable = dataContract.IsTopLevelElementNullable; ReprocessAll(_schemas); } XmlSchemaType anonymousType = xsdType; xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema); if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeQName, DataContract.GetClrTypeFullName(clrType)))); } if (xsdType != null) { xsdType.Annotation = GetSchemaAnnotation( ExportSurrogateData(dataContract), dataContract.IsValueType ? GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema) : null ); } } } private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate items { Hashtable elements = new Hashtable(); Hashtable types = new Hashtable(); XmlSchema[] schemaArray = new XmlSchema[schemas.Count]; schemas.CopyTo(schemaArray, 0); for (int i = 0; i < schemaArray.Length; i++) { XmlSchema schema = schemaArray[i]; XmlSchemaObject[] itemArray = new XmlSchemaObject[schema.Items.Count]; schema.Items.CopyTo(itemArray, 0); for (int j = 0; j < itemArray.Length; j++) { XmlSchemaObject item = itemArray[j]; Hashtable items; XmlQualifiedName qname; if (item is XmlSchemaElement) { items = elements; qname = new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace); } else if (item is XmlSchemaType) { items = types; qname = new XmlQualifiedName(((XmlSchemaType)item).Name, schema.TargetNamespace); } else continue; object otherItem = items[qname]; if (otherItem != null) { schema.Items.Remove(item); } else items.Add(qname, item); } schemas.Reprocess(schema); } } internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) { if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot)) return; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = null; InvokeSchemaProviderMethod(type, schemas, out stableName, out xsdType, out hasRoot); if (stableName.Name == null || stableName.Name.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type)))); } private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; object[] attrs = clrType.GetCustomAttributes(Globals.TypeOfXmlSchemaProviderAttribute, false); if (attrs == null || attrs.Length == 0) { stableName = DataContract.GetDefaultStableName(clrType); return false; } XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0]; if (provider.IsAny) { xsdType = CreateAnyElementType(); hasRoot = false; } string methodName = provider.MethodName; if (methodName == null || methodName.Length == 0) { if (!provider.IsAny) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidGetSchemaMethod, DataContract.GetClrTypeFullName(clrType)))); stableName = DataContract.GetDefaultStableName(clrType); } else { MethodInfo getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null); if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName))); if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType))) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType)))); object typeInfo = getMethod.Invoke(null, new object[] { schemas }); if (provider.IsAny) { if (typeInfo != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidNonNullReturnValueByIsAny, DataContract.GetClrTypeFullName(clrType), methodName))); stableName = DataContract.GetDefaultStableName(clrType); } else if (typeInfo == null) { xsdType = CreateAnyElementType(); hasRoot = false; stableName = DataContract.GetDefaultStableName(clrType); } else { XmlSchemaType providerXsdType = typeInfo as XmlSchemaType; if (providerXsdType != null) { string typeName = providerXsdType.Name; string typeNs = null; if (typeName == null || typeName.Length == 0) { DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs); stableName = new XmlQualifiedName(typeName, typeNs); providerXsdType.Annotation = GetSchemaAnnotation(ExportActualType(stableName, new XmlDocument())); xsdType = providerXsdType; } else { foreach (XmlSchema schema in schemas.Schemas()) { foreach (XmlSchemaObject schemaItem in schema.Items) { if ((object)schemaItem == (object)providerXsdType) { typeNs = schema.TargetNamespace; if (typeNs == null) typeNs = String.Empty; break; } } if (typeNs != null) break; } if (typeNs == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingSchemaType, typeName, DataContract.GetClrTypeFullName(clrType)))); stableName = new XmlQualifiedName(typeName, typeNs); } } else stableName = (XmlQualifiedName)typeInfo; } } return true; } private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName) { IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType); XmlSchema schema = ixmlSerializable.GetSchema(); if (schema == null) { AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace); } else { if (schema.Id == null || schema.Id.Length == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnSchemaOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType)))); AddDefaultTypedDatasetType(schemas, schema, stableName.Name, stableName.Namespace); } } internal static void AddDefaultXmlType(XmlSchemaSet schemas, string localName, string ns) { XmlSchemaComplexType defaultXmlType = CreateAnyType(); defaultXmlType.Name = localName; XmlSchema schema = SchemaHelper.GetSchema(ns, schemas); schema.Items.Add(defaultXmlType); schemas.Reprocess(schema); } private static XmlSchemaComplexType CreateAnyType() { XmlSchemaComplexType anyType = new XmlSchemaComplexType(); anyType.IsMixed = true; anyType.Particle = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny(); any.MinOccurs = 0; any.MaxOccurs = Decimal.MaxValue; any.ProcessContents = XmlSchemaContentProcessing.Lax; ((XmlSchemaSequence)anyType.Particle).Items.Add(any); anyType.AnyAttribute = new XmlSchemaAnyAttribute(); return anyType; } private static XmlSchemaComplexType CreateAnyElementType() { XmlSchemaComplexType anyElementType = new XmlSchemaComplexType(); anyElementType.IsMixed = false; anyElementType.Particle = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny(); any.MinOccurs = 0; any.ProcessContents = XmlSchemaContentProcessing.Lax; ((XmlSchemaSequence)anyElementType.Particle).Items.Add(any); return anyElementType; } internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray) { string name = null; if (type == Globals.TypeOfXmlElement) { xsdType = CreateAnyElementType(); name = "XmlElement"; hasRoot = false; } else { xsdType = CreateAnyType(); name = "ArrayOfXmlNode"; hasRoot = true; } typeName = new XmlQualifiedName(name, DataContract.GetDefaultStableNamespace(type)); return true; } typeName = null; return false; } private static void AddDefaultDatasetType(XmlSchemaSet schemas, string localName, string ns) { XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = localName; type.Particle = new XmlSchemaSequence(); XmlSchemaElement schemaRefElement = new XmlSchemaElement(); schemaRefElement.RefName = new XmlQualifiedName(Globals.SchemaLocalName, XmlSchema.Namespace); ((XmlSchemaSequence)type.Particle).Items.Add(schemaRefElement); XmlSchemaAny any = new XmlSchemaAny(); ((XmlSchemaSequence)type.Particle).Items.Add(any); XmlSchema schema = SchemaHelper.GetSchema(ns, schemas); schema.Items.Add(type); schemas.Reprocess(schema); } private static void AddDefaultTypedDatasetType(XmlSchemaSet schemas, XmlSchema datasetSchema, string localName, string ns) { XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = localName; type.Particle = new XmlSchemaSequence(); XmlSchemaAny any = new XmlSchemaAny(); any.Namespace = (datasetSchema.TargetNamespace == null) ? String.Empty : datasetSchema.TargetNamespace; ((XmlSchemaSequence)type.Particle).Items.Add(any); schemas.Add(datasetSchema); XmlSchema schema = SchemaHelper.GetSchema(ns, schemas); schema.Items.Add(type); schemas.Reprocess(datasetSchema); schemas.Reprocess(schema); } private XmlSchemaAnnotation GetSchemaAnnotation(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema) { XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo(); XmlElement annotationElement = GetAnnotationMarkup(annotationQualifiedName, innerText, schema); appInfo.Markup = new XmlNode[1] { annotationElement }; annotation.Items.Add(appInfo); return annotation; } private static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes) { if (nodes == null || nodes.Length == 0) return null; bool hasAnnotation = false; for (int i = 0; i < nodes.Length; i++) if (nodes[i] != null) { hasAnnotation = true; break; } if (!hasAnnotation) return null; XmlSchemaAnnotation annotation = new XmlSchemaAnnotation(); XmlSchemaAppInfo appInfo = new XmlSchemaAppInfo(); annotation.Items.Add(appInfo); appInfo.Markup = nodes; return annotation; } private XmlElement GetAnnotationMarkup(XmlQualifiedName annotationQualifiedName, string innerText, XmlSchema schema) { XmlElement annotationElement = XmlDoc.CreateElement(annotationQualifiedName.Name, annotationQualifiedName.Namespace); SchemaHelper.AddSchemaImport(annotationQualifiedName.Namespace, schema); annotationElement.InnerText = innerText; return annotationElement; } private XmlSchema GetSchema(string ns) { return SchemaHelper.GetSchema(ns, Schemas); } // Property is not stored in a local because XmlSchemaSequence is mutable. // The schema export process should not expose objects that may be modified later. internal static XmlSchemaSequence ISerializableSequence { get { XmlSchemaSequence iSerializableSequence = new XmlSchemaSequence(); iSerializableSequence.Items.Add(ISerializableWildcardElement); return iSerializableSequence; } } // Property is not stored in a local because XmlSchemaAny is mutable. // The schema export process should not expose objects that may be modified later. internal static XmlSchemaAny ISerializableWildcardElement { get { XmlSchemaAny iSerializableWildcardElement = new XmlSchemaAny(); iSerializableWildcardElement.MinOccurs = 0; iSerializableWildcardElement.MaxOccursString = Globals.OccursUnbounded; iSerializableWildcardElement.Namespace = "##local"; iSerializableWildcardElement.ProcessContents = XmlSchemaContentProcessing.Skip; return iSerializableWildcardElement; } } private static XmlQualifiedName s_anytypeQualifiedName; internal static XmlQualifiedName AnytypeQualifiedName { get { if (s_anytypeQualifiedName == null) s_anytypeQualifiedName = new XmlQualifiedName(Globals.AnyTypeLocalName, Globals.SchemaNamespace); return s_anytypeQualifiedName; } } private static XmlQualifiedName s_stringQualifiedName; internal static XmlQualifiedName StringQualifiedName { get { if (s_stringQualifiedName == null) s_stringQualifiedName = new XmlQualifiedName(Globals.StringLocalName, Globals.SchemaNamespace); return s_stringQualifiedName; } } private static XmlQualifiedName s_defaultEnumBaseTypeName; internal static XmlQualifiedName DefaultEnumBaseTypeName { get { if (s_defaultEnumBaseTypeName == null) s_defaultEnumBaseTypeName = new XmlQualifiedName(Globals.IntLocalName, Globals.SchemaNamespace); return s_defaultEnumBaseTypeName; } } private static XmlQualifiedName s_enumerationValueAnnotationName; internal static XmlQualifiedName EnumerationValueAnnotationName { get { if (s_enumerationValueAnnotationName == null) s_enumerationValueAnnotationName = new XmlQualifiedName(Globals.EnumerationValueLocalName, Globals.SerializationNamespace); return s_enumerationValueAnnotationName; } } private static XmlQualifiedName s_surrogateDataAnnotationName; internal static XmlQualifiedName SurrogateDataAnnotationName { get { if (s_surrogateDataAnnotationName == null) s_surrogateDataAnnotationName = new XmlQualifiedName(Globals.SurrogateDataLocalName, Globals.SerializationNamespace); return s_surrogateDataAnnotationName; } } private static XmlQualifiedName s_defaultValueAnnotation; internal static XmlQualifiedName DefaultValueAnnotation { get { if (s_defaultValueAnnotation == null) s_defaultValueAnnotation = new XmlQualifiedName(Globals.DefaultValueLocalName, Globals.SerializationNamespace); return s_defaultValueAnnotation; } } private static XmlQualifiedName s_actualTypeAnnotationName; internal static XmlQualifiedName ActualTypeAnnotationName { get { if (s_actualTypeAnnotationName == null) s_actualTypeAnnotationName = new XmlQualifiedName(Globals.ActualTypeLocalName, Globals.SerializationNamespace); return s_actualTypeAnnotationName; } } private static XmlQualifiedName s_isDictionaryAnnotationName; internal static XmlQualifiedName IsDictionaryAnnotationName { get { if (s_isDictionaryAnnotationName == null) s_isDictionaryAnnotationName = new XmlQualifiedName(Globals.IsDictionaryLocalName, Globals.SerializationNamespace); return s_isDictionaryAnnotationName; } } private static XmlQualifiedName s_isValueTypeName; internal static XmlQualifiedName IsValueTypeName { get { if (s_isValueTypeName == null) s_isValueTypeName = new XmlQualifiedName(Globals.IsValueTypeLocalName, Globals.SerializationNamespace); return s_isValueTypeName; } } // Property is not stored in a local because XmlSchemaAttribute is mutable. // The schema export process should not expose objects that may be modified later. internal static XmlSchemaAttribute ISerializableFactoryTypeAttribute { get { XmlSchemaAttribute iSerializableFactoryTypeAttribute = new XmlSchemaAttribute(); iSerializableFactoryTypeAttribute.RefName = new XmlQualifiedName(Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace); return iSerializableFactoryTypeAttribute; } } // Property is not stored in a local because XmlSchemaAttribute is mutable. // The schema export process should not expose objects that may be modified later. internal static XmlSchemaAttribute RefAttribute { get { XmlSchemaAttribute refAttribute = new XmlSchemaAttribute(); refAttribute.RefName = Globals.RefQualifiedName; return refAttribute; } } // Property is not stored in a local because XmlSchemaAttribute is mutable. // The schema export process should not expose objects that may be modified later. internal static XmlSchemaAttribute IdAttribute { get { XmlSchemaAttribute idAttribute = new XmlSchemaAttribute(); idAttribute.RefName = Globals.IdQualifiedName; return idAttribute; } } } }
// // SCSharp.Mpq.Smk // // Authors: // Chris Toshok (toshok@gmail.com) // // Copyright 2006-2010 Chris Toshok // // // 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. // /* written using http://wiki.multimedia.cx/index.php?title=Smacker as a guide */ #if notyet using System; using System.IO; using System.Text; namespace SCSharp { public class Smk : MpqResource { [Flags] enum ARFlags { Compressed = 0x80, DataPresent = 0x40, Is16Bit = 0x20, Stereo = 0x10, CompressionMask = 0x0c } const int V2_COMPRESSION = 0x00; Stream stream; /* Smk header info */ uint width; uint height; uint frames; uint frameRate; uint flags; uint[/*7*/] audioSize; uint treesSize; uint mmap_Size; uint mclr_Size; uint full_Size; uint type_Size; uint[/*7*/] audioRate; uint[/*7*/] audioFlags; uint[] frameSizes; byte[] frameFlags; Dynamic16HuffmanTree mmap_Tree; Dynamic16HuffmanTree mclr_Tree; Dynamic16HuffmanTree full_Tree; Dynamic16HuffmanTree type_Tree; public Smk () { palette = new byte[256 * 3]; } public uint Width { get { return width; } } public uint PaddedWidth { get { return width + (width % 4); } } public uint Height { get { return height; } } public uint PaddedHeight { get { return height + (height % 4); } } public uint[] AudioRate { get { return audioRate; } } void ReadHeader () { int i; uint signature; audioSize = new uint[7]; audioRate = new uint[7]; audioFlags = new uint[7]; signature = Util.ReadDWord (stream); if (signature != 0x324b4d53 /* SMK2 */ && signature != 0x344b4d53 /* SMK4 */) throw new Exception ("invalid file"); width = Util.ReadDWord (stream); height = Util.ReadDWord (stream); frames = Util.ReadDWord (stream); frameRate = Util.ReadDWord (stream); flags = Util.ReadDWord (stream); for (i = 0; i < audioSize.Length; i ++) audioSize[i] = Util.ReadDWord (stream); treesSize = Util.ReadDWord (stream); mmap_Size = Util.ReadDWord (stream); mclr_Size = Util.ReadDWord (stream); full_Size = Util.ReadDWord (stream); type_Size = Util.ReadDWord (stream); for (i = 0; i < audioRate.Length; i ++) { audioRate[i] = Util.ReadDWord (stream); audioFlags[i] = audioRate[i] >> 24; audioRate[i] &= 0x00ffffff; } /* dummy = */ Util.ReadDWord (stream); } double CalcFps () { if ((int)frameRate > 0) return 1000.0 / (int)frameRate; else if ((int)frameRate < 0) return 100000.0 / (-(int)frameRate); else return 10.0; } void ReadFrameSizes () { int i; frameSizes = new uint[frames]; for (i = 0; i < frames; i ++) { frameSizes[i] = Util.ReadDWord (stream); if ((frameSizes[i] & 0x03) == 0x03) Console.WriteLine (" frame {0} has some weird flags", i); } } void ReadFrameFlags () { frameFlags = new byte[frames]; stream.Read (frameFlags, 0, (int)frames); } void ReadTrees () { Console.WriteLine ("Building huffman trees (from position {0:x}, length {1:x}):", stream.Position, treesSize); byte[] tree_buf = new byte[treesSize]; stream.Read (tree_buf, 0, (int)treesSize); BitStream bs = new BitStream (tree_buf); int tag; BitStream.debug = true; #if false tag = bs.ReadBit (); if (tag == 1) { #endif Console.WriteLine (" + MMap"); mmap_Tree = new Dynamic16HuffmanTree (); mmap_Tree.Build (bs); Console.WriteLine (" + After MMap tree, read {0} bytes", bs.ReadCount); #if false } #endif BitStream.debug = false; bs.ZeroReadCount (); #if false tag = bs.ReadBit (); if (tag == 1) { #endif Console.WriteLine (" + MClr"); mclr_Tree = new Dynamic16HuffmanTree (); mclr_Tree.Build (bs); Console.WriteLine (" + After MClr tree, read {0} bytes", bs.ReadCount); #if false } bs.ZeroReadCount (); tag = bs.ReadBit (); if (tag == 1) { #endif Console.WriteLine (" + Full"); full_Tree = new Dynamic16HuffmanTree (); full_Tree.Build (bs); Console.WriteLine (" + After Full tree, read {0} bytes", bs.ReadCount); #if false } bs.ZeroReadCount (); tag = bs.ReadBit (); if (tag == 1) { #endif Console.WriteLine (" + Type"); type_Tree = new Dynamic16HuffmanTree (); type_Tree.Build (bs); Console.WriteLine (" + After Type tree, read {0} bytes", bs.ReadCount); #if false } #endif Console.WriteLine ("done (read {0} out of {1} bytes).", bs.ReadCount, treesSize); } byte[] palmap = { 0x00, 0x04, 0x08, 0x0C, 0x10, 0x14, 0x18, 0x1C, 0x20, 0x24, 0x28, 0x2C, 0x30, 0x34, 0x38, 0x3C, 0x41, 0x45, 0x49, 0x4D, 0x51, 0x55, 0x59, 0x5D, 0x61, 0x65, 0x69, 0x6D, 0x71, 0x75, 0x79, 0x7D, 0x82, 0x86, 0x8A, 0x8E, 0x92, 0x96, 0x9A, 0x9E, 0xA2, 0xA6, 0xAA, 0xAE, 0xB2, 0xB6, 0xBA, 0xBE, 0xC3, 0xC7, 0xCB, 0xCF, 0xD3, 0xD7, 0xDB, 0xDF, 0xE3, 0xE7, 0xEB, 0xEF, 0xF3, 0xF7, 0xFB, 0xFF }; void ReadPaletteChunk (BitStream bs) { byte[] new_palette = new byte[256 * 3]; bs.AssertAtByteBoundary (); bs.ZeroReadCount (); int paletteLength = bs.ReadByte(); Console.WriteLine ("palette chunk is {0} bytes long", paletteLength * 4); // byte[] palBuf = new byte[paletteLength * 4 - 1]; // bs.Read (palBuf, 0, palBuf.Length); // MemoryStream palStream = new MemoryStream (palBuf, false); BitStream palStream = bs; int new_index = 0, index = 0; while (new_index < 256) { byte p = (byte)palStream.ReadByte(); if ((p & 0x80) == 0x80) { int count = (p & 0x7f) + 1; // Console.WriteLine ("copy1 {0} entries, from {1} to {2}", count, index, new_index); Array.Copy (palette, index * 3, new_palette, new_index * 3, count * 3); index += count; new_index += count; } else if ((p & 0x40) == 0x40) { int count = (p & 0x3f) + 1; int tmp_index = palStream.ReadByte(); // Console.WriteLine ("copy2 {0} entries, from {1} to {2}", count, tmp_index, new_index); Array.Copy (palette, tmp_index * 3, new_palette, new_index * 3, count * 3); new_index += count; } else if ((p & 0xc0) == 0x00) { int b = p & 0x3f; int g = palStream.ReadByte() & 0x3f; int r = palStream.ReadByte() & 0x3f; new_palette [new_index * 3] = palmap[r]; new_palette [new_index * 3 + 1] = palmap[g]; new_palette [new_index * 3 + 2] = palmap[b]; // Console.WriteLine ("Assign palette[{0}] = {1},{2},{3}", new_index, // palmap[r], palmap[g], palmap[b]); new_index ++; } } palette = new_palette; // Console.WriteLine ("read {0} bytes toward filling the palette", palBuf.Length + 1); } uint[] block_chain_size_table = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 128, 256, 512, 1024, 2048 }; enum BlockType { Mono = 0x00, Full = 0x01, Void = 0x02, Solid = 0x03 } void ReadVideoChunk (BitStream bs) { int current_block_x = 0, current_block_y = 0; int block_rez_x = (int)PaddedWidth / 4; int block_rez_y = (int)PaddedHeight / 4; Console.WriteLine ("reading video chunk"); bs.DebugFirst (); while (true) { ushort type_descriptor = 0; if (type_Tree != null) type_descriptor = (ushort)type_Tree.Decode (bs); BlockType type = (BlockType)(type_descriptor & 0x3); uint chain_length = block_chain_size_table [(type_descriptor & 0xfc) >> 2]; Console.WriteLine ("rendering {0} blocks of type {1}", chain_length, type); for (int i = 0; i < chain_length; i ++) { switch (type) { case BlockType.Mono: ushort pixel = (ushort) mclr_Tree.Decode (bs); byte color1 = (byte)((pixel >> 8) & 0xff); byte color0 = (byte)(pixel & 0xff); ushort map = (ushort) mmap_Tree.Decode (bs); int mask = 1; int bx, by; bx = current_block_x * 4; by = current_block_y * 4; for (int bi = 0; bi < 16;) { if ((map & mask) == 0) frameData[by * PaddedWidth + bx] = color0; else frameData[by * PaddedWidth + bx] = color1; mask <<= 1; bx ++; bi++; if ((bi % 4) == 0) { bx = current_block_x * 4; by ++; } } break; case BlockType.Full: break; case BlockType.Void: break; case BlockType.Solid: break; } current_block_x ++; if (current_block_x == block_rez_x) { current_block_x = 0; current_block_y ++; if (current_block_y == block_rez_y) return; } } } } byte[][] audioOut = new byte[7][]; void OutputSample (Stream outputStream, byte[] left, byte[] right) { OutputSample (outputStream, left); OutputSample (outputStream, right); } void OutputSample (Stream outputStream, byte[] sample) { outputStream.Write (sample, 0, sample.Length); } void OutputSample (Stream outputStream, byte left, byte right) { outputStream.WriteByte (left); outputStream.WriteByte (right); } void OutputSample (Stream outputStream, byte sample) { outputStream.WriteByte (sample); } void OutputSample (Stream outputStream, short left, short right) { #if true byte[] lb = BitConverter.GetBytes (left); byte[] rb = BitConverter.GetBytes (right); OutputSample (outputStream, lb); OutputSample (outputStream, rb); #else Util.WriteWord (outputStream, (ushort)left); Util.WriteWord (outputStream, (ushort)right); #endif } void OutputAudio (Stream outputStream, byte[] buf, int index, int length) { outputStream.Write (buf, index, length); } void OutputAudio (Stream outputStream, byte[] buf) { outputStream.Write (buf, 0, buf.Length); } void Decompress16Stereo (BitStream bs, Stream outputStream) { int flag; flag = bs.ReadBit(); /* DataPresent */ Console.WriteLine (flag == 1 ? "data present" : "data not present"); flag = bs.ReadBit(); /* IsStereo */ Console.WriteLine (flag == 1 ? "stereo" : "mono"); flag = bs.ReadBit(); /* Is16Bits */ Console.WriteLine (flag == 1 ? "16 bits" : "8 bits"); HuffmanTree ll = new HuffmanTree(); HuffmanTree lh = new HuffmanTree(); HuffmanTree rl = new HuffmanTree(); HuffmanTree rh = new HuffmanTree(); ll.Build (bs); lh.Build (bs); rl.Build (bs); rh.Build (bs); byte[] tmp = new byte[2]; short rightbase; short leftbase; tmp[1] = (byte)bs.ReadByte(); tmp[0] = (byte)bs.ReadByte(); rightbase = BitConverter.ToInt16 (tmp, 0); tmp[1] = (byte)bs.ReadByte(); tmp[0] = (byte)bs.ReadByte(); leftbase = BitConverter.ToInt16 (tmp, 0); Console.WriteLine ("initial bases = {0}, {1}", leftbase, rightbase); OutputSample (outputStream, leftbase, rightbase); while (bs.ReadCount < bs.Length) { /* read the huffman encoded deltas */ tmp[0] = (byte)(ll == null ? 0 : ll.Decode (bs)); tmp[1] = (byte)(lh == null ? 0 : lh.Decode (bs)); short leftdelta = BitConverter.ToInt16 (tmp, 0); tmp[0] = (byte)(rl == null ? 0 : rl.Decode (bs)); tmp[1] = (byte)(rh == null ? 0 : rh.Decode (bs)); short rightdelta = BitConverter.ToInt16 (tmp, 0); rightbase += rightdelta; leftbase += leftdelta; OutputSample (outputStream, leftbase, rightbase); } Console.WriteLine ("outputted {0} bytes in samples for this frame.", outputStream.Position); } void Decompress16Mono (BitStream bs, Stream outputStream) { int flag; flag = bs.ReadBit(); /* DataPresent */ Console.WriteLine (flag == 1 ? "data present" : "data not present"); flag = bs.ReadBit(); /* Is16Bits */ Console.WriteLine (flag == 1 ? "16 bits" : "8 bits"); flag = bs.ReadBit(); /* IsStereo */ Console.WriteLine (flag == 1 ? "stereo" : "mono"); HuffmanTree h = new HuffmanTree(); HuffmanTree l = new HuffmanTree(); byte[] _base = new byte[2]; l.Build (bs); h.Build (bs); _base[1] = (byte)bs.ReadByte(); _base[0] = (byte)bs.ReadByte(); OutputSample (outputStream, _base); while (bs.ReadCount < bs.Length) { /* read the huffman encoded deltas */ int ld = (int)l.Decode (bs); int hd = (int)h.Decode (bs); if (ld + _base[0] > 255) { _base[1] += 1; _base[0] = (byte)(ld + _base[0] - 255); } else _base[0] = (byte)(hd + _base[0]); _base[1] = (byte)(hd + _base[1]); OutputSample (outputStream, _base); } Console.WriteLine ("outputted {0} bytes in samples for this frame.", outputStream.Position); } void Decompress8Stereo (BitStream bs, Stream outputStream) { int flag; flag = bs.ReadBit(); /* DataPresent */ Console.WriteLine (flag == 1 ? "data present" : "data not present"); flag = bs.ReadBit(); /* Is16Bits */ Console.WriteLine (flag == 1 ? "16 bits" : "8 bits"); flag = bs.ReadBit(); /* IsStereo */ Console.WriteLine (flag == 1 ? "stereo" : "mono"); HuffmanTree r = new HuffmanTree(); HuffmanTree l = new HuffmanTree(); byte leftbase; byte rightbase; l.Build (bs); r.Build (bs); rightbase = (byte)bs.ReadByte(); leftbase = (byte)bs.ReadByte(); OutputSample (outputStream, leftbase, rightbase); while (bs.ReadCount < bs.Length) { /* read the huffman encoded deltas */ int rd = (int)r.Decode (bs); int ld = (int)l.Decode (bs); rightbase = (byte)(rightbase + rd); leftbase = (byte)(leftbase + ld); OutputSample (outputStream, leftbase, rightbase); } Console.WriteLine ("outputted {0} bytes in samples for this frame.", outputStream.Position); } void Decompress8Mono (BitStream bs, Stream outputStream) { int flag; flag = bs.ReadBit(); /* DataPresent */ Console.WriteLine (flag == 1 ? "data present" : "data not present"); flag = bs.ReadBit(); /* Is16Bits */ Console.WriteLine (flag == 1 ? "16 bits" : "8 bits"); flag = bs.ReadBit(); /* IsStereo */ Console.WriteLine (flag == 1 ? "stereo" : "mono"); HuffmanTree t = new HuffmanTree(); byte _base; t.Build (bs); _base = (byte)bs.ReadByte(); OutputSample (outputStream, _base); while (bs.ReadCount < bs.Length) { /* read the huffman encoded deltas */ int d = (int)t.Decode (bs); _base = (byte)(_base + d); OutputSample (outputStream, _base); } Console.WriteLine ("outputted {0} bytes in samples for this frame.", outputStream.Position); } void ReadAudioChunk (BitStream bs, int channel) { uint frameAudioLength = 0; uint audioDecompressedLength = 0; bool compressed = ((audioFlags[channel] & (int)ARFlags.Compressed) == (int)ARFlags.Compressed); bool is16 = ((audioFlags[channel] & (int)ARFlags.Is16Bit) == (int)ARFlags.Is16Bit); bool stereo = ((audioFlags[channel] & (int)ARFlags.Stereo) == (int)ARFlags.Stereo); bs.AssertAtByteBoundary (); bs.DebugFirst (); Console.WriteLine ("reading audio chunk length"); frameAudioLength = bs.ReadDWord (); Console.WriteLine ("audio chunk length = {0}", frameAudioLength); if (compressed) { audioDecompressedLength = bs.ReadDWord (); Console.WriteLine ("decompressed audio length = {0}", audioDecompressedLength); byte[] streamBuf = new byte[frameAudioLength]; bs.Read (streamBuf, 0, streamBuf.Length); audioOut[channel] = new byte[audioDecompressedLength]; if (is16) if (stereo) Decompress16Stereo (new BitStream (streamBuf), new MemoryStream (audioOut[channel])); else Decompress16Mono (new BitStream (streamBuf), new MemoryStream (audioOut[channel])); else if (stereo) Decompress8Stereo (new BitStream (streamBuf), new MemoryStream (audioOut[channel])); else Decompress8Mono (new BitStream (streamBuf), new MemoryStream (audioOut[channel])); } else { audioOut[channel] = new byte[frameAudioLength]; bs.Read (audioOut[channel], 0, (int)frameAudioLength); } } void ReadFrame (BitStream bs) { if ((frameFlags [curFrame] & 0x01) == 0x01) { ReadPaletteChunk (bs); // DumpPalette (); } for (int i = 1; i < 8; i ++) if ((frameFlags [curFrame] & (1<<i)) == (1<<i)) ReadAudioChunk (bs, i-1); if (bs.Position == bs.Length) return; ReadVideoChunk(bs); } public void ReadFromStream (Stream stream) { this.stream = stream; ReadHeader (); ReadFrameSizes (); ReadFrameFlags (); ReadTrees (); DumpHeader (); DumpFrameInfo (); frameDataPosition = stream.Position; Console.WriteLine ("frames start at 0x{0:x}", frameDataPosition); Console.WriteLine ("allocating video data buffer at {0} x {1} ({2} x {3} = {4} blocks)", PaddedWidth, PaddedHeight, PaddedWidth / 4, PaddedHeight / 4, PaddedWidth * PaddedHeight / 4); frameData = new byte[PaddedWidth * PaddedHeight]; } long frameDataPosition; int curFrame; byte[] palette; byte[] frameData; public void Play () { stream.Position = frameDataPosition; curFrame = 0; NextFrame (); } public void NextFrame () { if (curFrame >= frames) { Console.WriteLine ("ending stream position = {0}", stream.Position); if (AnimationDone != null) AnimationDone (); return; } uint frameSize = frameSizes[curFrame]; Console.WriteLine ("reading frame {0}, position = {1}, size = {2}", curFrame, stream.Position, frameSize); if ((frameSize & 0x1) == 0x1) Console.WriteLine (" + frame is a key frame"); if ((frameSize & 0x2) == 0x2) Console.WriteLine (" + frame is <something>"); frameSize &= 0xfffffffc; Console.WriteLine (" + frame size = {0}", frameSize); byte[] frame_buf = new byte[frameSize]; stream.Read (frame_buf, 0, (int)frameSize); ReadFrame (new BitStream (frame_buf)); if (FrameReady != null) FrameReady (frameData, palette, audioOut); curFrame++; } public event SmkFrameReady FrameReady; public event SmkAnimationDone AnimationDone; void DumpHeader () { Console.WriteLine ("width: {0}", width); Console.WriteLine ("height: {0}", height); Console.WriteLine ("frame count: {0}", frames); Console.WriteLine ("frame rate: {0} {1}", frameRate, CalcFps ()); Console.WriteLine ("flags: {0}", flags); Console.WriteLine ("TreesSize: {0}", treesSize); Console.WriteLine ("MMap_Size: {0}", mmap_Size); Console.WriteLine ("MClr_Size: {0}", mclr_Size); Console.WriteLine ("Full_Size: {0}", full_Size); Console.WriteLine ("Type_Size: {0}", type_Size); for (int i = 0; i < 7; i ++) { Console.Write ("Channel {0}: ", i); if ((audioFlags[i] & (int)ARFlags.DataPresent) == (int)ARFlags.DataPresent) { Console.Write ("Size = {0}, ", audioSize[i]); Console.Write ("Freq = {0} ", audioRate[i]); Console.Write ("Flags = {0} [", audioFlags[i]); if ((audioFlags[i] & (int)ARFlags.Compressed) == (int)ARFlags.Compressed) Console.Write ("compressed "); if ((audioFlags[i] & (int)ARFlags.CompressionMask) == V2_COMPRESSION) Console.Write ("(hdpcm)"); else Console.Write ("(unknown)"); if ((audioFlags[i] & (int)ARFlags.DataPresent) == (int)ARFlags.DataPresent) Console.Write (" data present"); if ((audioFlags[i] & (int)ARFlags.Is16Bit) == (int)ARFlags.Is16Bit) Console.Write (" 16 bit"); if ((audioFlags[i] & (int)ARFlags.Stereo) == (int)ARFlags.Stereo) Console.Write (" stereo"); Console.WriteLine ("]"); } else { Console.WriteLine ("(no data)"); } } } void DumpFrameInfo () { for (int i = 0; i < frames; i ++) { Console.Write ("Frame {0}: ", i); if ((frameFlags[i] & 0x01) != 0) Console.Write ("(palette)"); for (int ch = 0; ch <= 7; ch++) if ((frameFlags[i] & (1 << (ch + 1))) != 0) Console.Write ("(channel {0})", ch); Console.WriteLine (); } } void DumpPalette () { Console.WriteLine ("GIMP Palette"); Console.WriteLine ("Name: palette"); Console.WriteLine ("Columns: 0"); Console.WriteLine ("#"); for (int i = 0; i < 256; i ++) { Console.WriteLine ("{0} {1} {2} palette", palette [i*3 + 2], /*r*/ palette [i*3 + 1], /*g*/ palette [i*3 + 0] /*b*/); } } } public delegate void SmkFrameReady (byte[] pixelData, byte[] palette, byte[][] audioBuffers); public delegate void SmkAnimationDone (); public class BitStream { public static bool debug; public void DebugFirst () { int num_bytes = 12; if (num_bytes >= buf.Length - current_byte_index) num_bytes = buf.Length - current_byte_index - 1; for (int i = 0; i < num_bytes; i ++) Console.Write ("0x{0:x} ", buf[current_byte_index + i]); Console.WriteLine ("\ncurrent byte = 0x{0:x}", current_byte); } int current_byte; int current_byte_index; int current_bit; byte [] buf; public BitStream (byte[] buf) { this.buf = buf; this.current_byte_index = 0; this.current_byte = buf[current_byte_index]; this.current_bit = 8; } int nshift; int nibble; int nc = 0; int GetBit () { int rv = current_byte & 0x1; current_bit --; current_byte >>= 1; if (debug) { nibble |= rv << nshift; nshift++; if (nshift == 4) { Console.Write ("{0:x}", nibble); nibble = 0; nshift = 0; nc++; if (nc == 2) { Console.Write (" "); nc = 0; } } } if (current_bit == 0) { current_bit = 8; if (current_byte_index + 1 > buf.Length) throw new Exception (String.Format ("about to read off end of {0} byte buffer", buf.Length)); current_byte_index++; current_byte = buf[current_byte_index]; } return rv; } public int ReadBit () { int rv = GetBit (); return rv; } public int ReadByte () { int rv; if (current_bit == 8) { rv = current_byte; current_byte_index++; current_byte = buf[current_byte_index]; if (debug) Console.Write ("{0:x}{1:x} ", rv & 0x0f, (rv & 0xf0) >> 4); } else { rv = 0; for (int i = 0; i < 8; i ++) rv |= ReadBit () << i; } return rv; } public ushort ReadWord () { return ((ushort)(ReadByte () | (ReadByte() << 8))); } public uint ReadDWord () { return (uint)(ReadByte () | (ReadByte() << 8) | (ReadByte() << 16) | (ReadByte() << 24)); } public void Read (byte[] dest, int index, int length) { AssertAtByteBoundary(); if (current_byte_index + length > buf.Length) throw new Exception (); Array.Copy (buf, current_byte_index, dest, index, length); current_byte_index += length; if (current_byte_index < buf.Length) { current_byte = buf[current_byte_index]; current_bit = 8; } } public void AssertAtByteBoundary () { if (current_bit != 8) throw new Exception ("this operation only works on byte boundaries"); } int saved_start; public void ZeroReadCount () { saved_start = current_byte_index; } public int ReadCount { get { return current_byte_index - saved_start; } } public int Position { get { return current_byte_index; } set { current_byte_index = value; } } public int Length { get { return buf.Length; } } } class HuffmanNode { public long value; public HuffmanNode branch_0; public HuffmanNode branch_1; } class HuffmanTree { class HuffIter { HuffmanTree tree; HuffmanNode currentNode; public HuffIter (HuffmanTree tree) { this.tree = tree; this.currentNode = tree.Root; } public void ProcessBit (BitStream bs) { currentNode = bs.ReadBit() == 0 ? currentNode.branch_0 : currentNode.branch_1; if (currentNode == null) throw new Exception ("can't advance to child nodes from a leaf node"); } public void Reset () { currentNode = tree.Root; } public uint Value { get { if (!IsLeaf) throw new Exception ("this node is not a leaf"); return tree.ReturnNodeValue (currentNode); } } public bool IsLeaf { get { return (currentNode.branch_0 == null && currentNode.branch_1 == null); } } } HuffmanNode root; public HuffmanTree () { iter = new HuffIter (this); } public virtual void Build (BitStream bs) { Read (bs); } protected virtual void ReadValue (BitStream bs, HuffmanNode node) { node.value = (uint)bs.ReadByte(); } protected void Read (BitStream bs) { root = new HuffmanNode (); ReadNode (bs, Root); } protected void ReadNode (BitStream bs, HuffmanNode node) { int flag = bs.ReadBit(); if (flag == 0) { /* it's a leaf */ ReadValue (bs, node); } else { /* it's a node */ node.branch_0 = new HuffmanNode (); ReadNode (bs, node.branch_0); node.branch_1 = new HuffmanNode (); ReadNode (bs, node.branch_1); } } public HuffmanNode Root { get { return root; } } protected HuffIter iter; public uint Decode (BitStream bs) { iter.Reset (); while (!iter.IsLeaf) iter.ProcessBit (bs); return iter.Value; } public virtual uint ReturnNodeValue (HuffmanNode node) { return (uint)node.value; } } class Dynamic16HuffmanTree : HuffmanTree { HuffmanTree highTree; HuffmanTree lowTree; ushort[] markers = new ushort[3]; HuffmanNode[] shortest = new HuffmanNode[3]; public Dynamic16HuffmanTree () { } uint DecodeValue (BitStream bs) { uint lowValue, highValue; lowValue = 0; if (lowTree != null) { lowValue = lowTree.Decode (bs); } highValue = 0; if (highTree != null) { highValue = highTree.Decode (bs); } return (lowValue | (highValue << 8)); } protected override void ReadValue (BitStream bs, HuffmanNode node) { uint value = DecodeValue (bs); Console.WriteLine ("Read Value {0:x}", value); if (value == markers[0]) { Console.WriteLine ("found marker1"); shortest[0] = node; node.value = -1; } else if (value == markers[1]) { Console.WriteLine ("found marker2"); shortest[1] = node; node.value = -1; } else if (value == markers[2]) { Console.WriteLine ("found marker3"); shortest[2] = node; node.value = -1; } else node.value = value; } public override uint ReturnNodeValue (HuffmanNode node) { if (node.value == -1) { /* it's a marker */ throw new Exception (); } else return (uint)node.value; } public override void Build (BitStream bs) { bs.ZeroReadCount (); #if false int tag = bs.ReadBit(); if (tag == 1) { #endif lowTree = new HuffmanTree (); Console.WriteLine ("building low tree"); lowTree.Build (bs); Console.WriteLine ("low tree ends at {0:x}", bs.ReadCount); #if false } tag = bs.ReadBit (); if (tag == 1) { #endif highTree = new HuffmanTree (); Console.WriteLine ("building high tree"); highTree.Build (bs); Console.WriteLine ("high tree ends at {0:x}", bs.ReadCount); #if false } #endif markers[0] = bs.ReadWord (); markers[1] = bs.ReadWord (); markers[2] = bs.ReadWord (); Console.WriteLine ("markers = {0:x}, {1:x}, {2:x}", markers[0], markers[1], markers[2]); Read (bs); Console.WriteLine ("shortest1 = {0}", shortest[0]); Console.WriteLine ("shortest2 = {0}", shortest[1]); Console.WriteLine ("shortest3 = {0}", shortest[2]); } } } #endif
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #region using System; using System.Collections.Generic; using System.Linq; using NLog.Config; using NLog.Targets; using Xunit; #endregion namespace NLog.UnitTests.Config { public class ConfigApiTests { [Fact] public void AddTarget_testname() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget {Name = "File"}); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Equal(1, allTargets.Count); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); config.RemoveTarget("name1"); allTargets = config.AllTargets; Assert.Equal(0, allTargets.Count); } [Fact] public void AddTarget_testname_param() { var config = new LoggingConfiguration(); config.AddTarget("name1", new FileTarget {Name = "name2"}); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Equal(1, allTargets.Count); //maybe confusing, but the name of the target is not changed, only the one of the key. Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name1")); } [Fact] public void AddTarget_testname_fromtarget() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget {Name = "name2"}); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Equal(1, allTargets.Count); Assert.Equal("name2", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("name2")); } [Fact] public void AddRule_min_max() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget {Name = "File"}); config.AddRule(LogLevel.Info, LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.Equal(false, rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_all() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget {Name = "File"}); config.AddRuleForAllLevels("File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.Equal(false, rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_onelevel() { var config = new LoggingConfiguration(); config.AddTarget(new FileTarget {Name = "File"}); config.AddRuleForOneLevel(LogLevel.Error, "File", "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); var rule1 = config.LoggingRules.FirstOrDefault(); Assert.NotNull(rule1); Assert.Equal(false, rule1.Final); Assert.Equal("*a", rule1.LoggerNamePattern); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Fatal)); Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Error)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Warn)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Info)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Debug)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Trace)); Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Off)); } [Fact] public void AddRule_with_target() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget {Name = "File"}; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); Assert.NotNull(config.LoggingRules); Assert.Equal(1, config.LoggingRules.Count); config.AddTarget(new FileTarget {Name = "File"}); var allTargets = config.AllTargets; Assert.NotNull(allTargets); Assert.Equal(1, allTargets.Count); Assert.Equal("File", allTargets.First().Name); Assert.NotNull(config.FindTargetByName<FileTarget>("File")); } [Fact] public void AddRule_missingtarget() { var config = new LoggingConfiguration(); Assert.Throws<NLogConfigurationException>(() => config.AddRuleForOneLevel(LogLevel.Error, "File", "*a")); } [Fact] public void CheckAllTargets() { var config = new LoggingConfiguration(); var fileTarget = new FileTarget {Name = "File", FileName = "file"}; config.AddRuleForOneLevel(LogLevel.Error, fileTarget, "*a"); config.AddTarget(fileTarget); Assert.Equal(1, config.AllTargets.Count); Assert.Equal(fileTarget, config.AllTargets[0]); config.InitializeAll(); Assert.Equal(1, config.AllTargets.Count); Assert.Equal(fileTarget, config.AllTargets[0]); } [Fact] public void LogRuleToStringTest_min() { var target = new FileTarget {Name = "file1"}; var loggingRule = new LoggingRule("*", LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Error Fatal ] appendTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_minAndMax() { var target = new FileTarget {Name = "file1"}; var loggingRule = new LoggingRule("*", LogLevel.Debug, LogLevel.Error, target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ Debug Info Warn Error ] appendTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_none() { var target = new FileTarget {Name = "file1"}; var loggingRule = new LoggingRule("*", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (:All) levels: [ ] appendTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_filter() { var target = new FileTarget {Name = "file1"}; var loggingRule = new LoggingRule("namespace.comp1", target); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] appendTo: [ file1 ]", s); } [Fact] public void LogRuleToStringTest_multiple_targets() { var target = new FileTarget {Name = "file1"}; var target2 = new FileTarget {Name = "file2"}; var loggingRule = new LoggingRule("namespace.comp1", target); loggingRule.Targets.Add(target2); var s = loggingRule.ToString(); Assert.Equal("logNamePattern: (namespace.comp1:Equals) levels: [ ] appendTo: [ file1 file2 ]", s); } } }
namespace Nancy { using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading; using System.Threading.Tasks; using Nancy.ModelBinding; using Nancy.Responses.Negotiation; using Nancy.Routing; using Nancy.Session; using Nancy.Validation; using Nancy.ViewEngines; /// <summary> /// Basic class containing the functionality for defining routes and actions in Nancy. /// </summary> public abstract class NancyModule : INancyModule, IHideObjectMembers { private readonly List<Route> routes; /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> protected NancyModule() : this(String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="NancyModule"/> class. /// </summary> /// <param name="modulePath">A <see cref="string"/> containing the root relative path that all paths in the module will be a subset of.</param> protected NancyModule(string modulePath) { this.After = new AfterPipeline(); this.Before = new BeforePipeline(); this.OnError = new ErrorPipeline(); this.ModulePath = modulePath; this.routes = new List<Route>(); } /// <summary> /// Non-model specific data for rendering in the response /// </summary> public dynamic ViewBag { get { return this.Context == null ? null : this.Context.ViewBag; } } public dynamic Text { get { return this.Context.Text; } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for DELETE requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Delete { get { return new RouteBuilder("DELETE", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for GET requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Get { get { return new RouteBuilder("GET", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for HEAD requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Head { get { if (!StaticConfiguration.EnableHeadRouting) { throw new InvalidOperationException("Explicit HEAD routing is disabled. Set StaticConfiguration.EnableHeadRouting to enable."); } return new RouteBuilder("HEAD", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for OPTIONS requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Options { get { return new RouteBuilder("OPTIONS", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PATCH requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Patch { get { return new RouteBuilder("PATCH", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for POST requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Post { get { return new RouteBuilder("POST", this); } } /// <summary> /// Gets <see cref="RouteBuilder"/> for declaring actions for PUT requests. /// </summary> /// <value>A <see cref="RouteBuilder"/> instance.</value> public RouteBuilder Put { get { return new RouteBuilder("PUT", this); } } /// <summary> /// Get the root path of the routes in the current module. /// </summary> /// <value> /// A <see cref="T:System.String" /> containing the root path of the module or <see langword="null" /> /// if no root path should be used.</value><remarks>All routes will be relative to this root path. /// </remarks> public string ModulePath { get; protected set; } /// <summary> /// Gets all declared routes by the module. /// </summary> /// <value>A <see cref="IEnumerable{T}"/> instance, containing all <see cref="Route"/> instances declared by the module.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public virtual IEnumerable<Route> Routes { get { return this.routes.AsReadOnly(); } } /// <summary> /// Gets the current session. /// </summary> public ISession Session { get { return this.Request.Session; } } /// <summary> /// Renders a view from inside a route handler. /// </summary> /// <value>A <see cref="ViewRenderer"/> instance that is used to determine which view that should be rendered.</value> public ViewRenderer View { get { return new ViewRenderer(this); } } /// <summary> /// Used to negotiate the content returned based on Accepts header. /// </summary> /// <value>A <see cref="Negotiator"/> instance that is used to negotiate the content returned.</value> public Negotiator Negotiate { get { return new Negotiator(this.Context); } } /// <summary> /// Gets or sets the validator locator. /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelValidatorLocator ValidatorLocator { get; set; } /// <summary> /// Gets or sets an <see cref="Request"/> instance that represents the current request. /// </summary> /// <value>An <see cref="Request"/> instance.</value> public virtual Request Request { get { return this.Context.Request; } set { this.Context.Request = value; } } /// <summary> /// The extension point for accessing the view engines in Nancy. /// </summary><value>An <see cref="IViewFactory" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IViewFactory ViewFactory { get; set; } /// <summary><para> /// The post-request hook /// </para><para> /// The post-request hook is called after the response is created by the route execution. /// It can be used to rewrite the response or add/remove items from the context. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public AfterPipeline After { get; set; } /// <summary> /// <para> /// The pre-request hook /// </para> /// <para> /// The PreRequest hook is called prior to executing a route. If any item in the /// pre-request pipeline returns a response then the route is not executed and the /// response is returned. /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public BeforePipeline Before { get; set; } /// <summary> /// <para> /// The error hook /// </para> /// <para> /// The error hook is called if an exception is thrown at any time during executing /// the PreRequest hook, a route and the PostRequest hook. It can be used to set /// the response and/or finish any ongoing tasks (close database session, etc). /// </para> /// <remarks>This is automatically set by Nancy at runtime.</remarks> /// </summary> public ErrorPipeline OnError { get; set; } /// <summary> /// Gets or sets the current Nancy context /// </summary> /// <value>A <see cref="NancyContext" /> instance.</value> /// <remarks>This is automatically set by Nancy at runtime.</remarks> public NancyContext Context { get; set; } /// <summary> /// An extension point for adding support for formatting response contents. /// </summary><value>This property will always return <see langword="null" /> because it acts as an extension point.</value><remarks>Extension methods to this property should always return <see cref="P:Nancy.NancyModuleBase.Response" /> or one of the types that can implicitly be types into a <see cref="P:Nancy.NancyModuleBase.Response" />.</remarks> public IResponseFormatter Response { get; set; } /// <summary> /// Gets or sets the model binder locator /// </summary> /// <remarks>This is automatically set by Nancy at runtime.</remarks> [EditorBrowsable(EditorBrowsableState.Never)] public IModelBinderLocator ModelBinderLocator { get; set; } /// <summary> /// Gets or sets the model validation result /// </summary> /// <remarks>This is automatically set by Nancy at runtime when you run validation.</remarks> public virtual ModelValidationResult ModelValidationResult { get { return this.Context == null ? null : this.Context.ModelValidationResult; } set { if (this.Context != null) { this.Context.ModelValidationResult = value; } } } /// <summary> /// Helper class for configuring a route handler in a module. /// </summary> public class RouteBuilder : IHideObjectMembers { private readonly string method; private readonly NancyModule parentModule; /// <summary> /// Initializes a new instance of the <see cref="RouteBuilder"/> class. /// </summary> /// <param name="method">The HTTP request method that the route should be available for.</param> /// <param name="parentModule">The <see cref="INancyModule"/> that the route is being configured for.</param> public RouteBuilder(string method, NancyModule parentModule) { this.method = method; this.parentModule = parentModule; } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path] { set { this.AddRoute(string.Empty, path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string path, Func<NancyContext, bool> condition] { set { this.AddRoute(string.Empty, path, condition, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, bool runAsync] { set { this.AddRoute(string.Empty, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="condition"/>. /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string path, Func<NancyContext, bool> condition, bool runAsync] { set { this.AddRoute(string.Empty, path, condition, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/> and <paramref name="name"/> /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string name, string path] { set { this.AddRoute(name, path, null, value); } } /// <summary> /// Defines a Nancy route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/> /// </summary> /// <value>A delegate that is used to invoke the route.</value> public Func<dynamic, dynamic> this[string name, string path, Func<NancyContext, bool> condition] { set { this.AddRoute(name, path, condition, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, bool runAsync] { set { this.AddRoute(name, path, null, value); } } /// <summary> /// Defines an async route for the specified <paramref name="path"/>, <paramref name="condition"/> and <paramref name="name"/> /// </summary> public Func<dynamic, CancellationToken, Task<dynamic>> this[string name, string path, Func<NancyContext, bool> condition, bool runAsync] { set { this.AddRoute(name, path, condition, value); } } protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, dynamic> value) { var fullPath = GetFullPath(path); this.parentModule.routes.Add(Route.FromSync(name, this.method, fullPath, condition, value)); } protected void AddRoute(string name, string path, Func<NancyContext, bool> condition, Func<dynamic, CancellationToken, Task<dynamic>> value) { var fullPath = GetFullPath(path); this.parentModule.routes.Add(new Route(name, this.method, fullPath, condition, value)); } private string GetFullPath(string path) { var relativePath = (path ?? string.Empty).Trim('/'); var parentPath = (this.parentModule.ModulePath ?? string.Empty).Trim('/'); if (string.IsNullOrEmpty(parentPath)) { return string.Concat("/", relativePath); } if (string.IsNullOrEmpty(relativePath)) { return string.Concat("/", parentPath); } return string.Concat("/", parentPath, "/", relativePath); } } } }
namespace Fixtures.SwaggerBatHttp { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class HttpRetryExtensions { /// <summary> /// Return 408 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static void Head408(this IHttpRetry operations) { Task.Factory.StartNew(s => ((IHttpRetry)s).Head408Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 408 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Head408Async( this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Head408WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put500(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Put500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Put500Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch500(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Patch500Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 500 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Patch500Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch500WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 502 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static void Get502(this IHttpRetry operations) { Task.Factory.StartNew(s => ((IHttpRetry)s).Get502Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 502 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Get502Async( this IHttpRetry operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.Get502WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Post503(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Post503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Post503Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Post503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Delete503(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Delete503Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 503 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Delete503Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Delete503WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Put504(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Put504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Put504Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Put504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> public static void Patch504(this IHttpRetry operations, bool? booleanValue = default(bool?)) { Task.Factory.StartNew(s => ((IHttpRetry)s).Patch504Async(booleanValue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Return 504 status code, then 200 after retry /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task Patch504Async( this IHttpRetry operations, bool? booleanValue = default(bool?), CancellationToken cancellationToken = default(CancellationToken)) { await operations.Patch504WithHttpMessagesAsync(booleanValue, null, cancellationToken).ConfigureAwait(false); } } }
//----------------------------------------------------------------------- // <copyright file="MultiplayerCubeStackerUIController.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> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; using Tango; using UnityEngine; using UnityEngine.UI; /// <summary> /// UIController for the MultiplayerCubeStacker scene. /// /// This controller does the following three things: /// 1. When the scene starts, the controller either creates a NetworkGameRoom if hosting or joins an existing room if /// not hosting. /// 2. When another player joins the room and the local player is hosting, the controller sends over an Area /// Description to localize to. /// 3. While connected and localized, the gameplay of adding and removing cubes to the world using RPCs to synchronize /// over the network. /// </summary> public class MultiplayerCubeStackerUIController : Photon.PunBehaviour, ITangoAreaDescriptionEvent, ITangoLifecycle { /// <summary> /// The list of cube prefabs. /// /// These are the cubes that are going to be added to the scene. /// </summary> public GameObject[] m_cubePrefab; /// <summary> /// Reference to a DeltaPoseController with a PhotonView so the poses get synced over the network. /// /// The sole purpose for this field is to get the name of the prefab, so that Photon can instantiate it over /// network. /// </summary> public GameObject m_networkDeltaPoseControllerPrefab; /// <summary> /// UI background before local player is initialized. /// </summary> public GameObject m_uiBackgroundOverlay; /// <summary> /// Progress text UI for downloading an Area Description. /// </summary> public GameObject m_progressPanel; /// <summary> /// Maximum size of the world. /// </summary> private const int WORLD_SIZE = 100; /// <summary> /// Maximum raycast distance when adding or removing cubes. /// </summary> private const float RAYCAST_MAX_DISTANCE = 10.0f; /// <summary> /// The temp file location, used for storing downloaded Area Description and exported Area Description. /// </summary> private const string TEMP_FILE_PATH = "/sdcard/tango_multiplayer_example/temp/"; /// <summary> /// The local player's Tango Delta Controller. /// /// Used for raycasting. This object is instantiated by PhotonNetwork. /// </summary> private GameObject m_localPlayer; /// <summary> /// Dictionary of currently placed cubes. /// /// The key is the position of the cube, the value is the cube GameObject. /// </summary> private Dictionary<Vector3, GameObject> m_cubeList = new Dictionary<Vector3, GameObject>(); /// <summary> /// Size of the cube objects. /// </summary> private float m_cubeSize; /// <summary> /// Currently selected cube type to place. /// </summary> private int m_currentCubeIndex = 0; /// <summary> /// A reference to TangoApplication object. /// </summary> private TangoApplication m_tangoApplication; /// <summary> /// The Area Description localized to. When hosting, this is the Area Description picked in the UI. When joining, /// this is the Area Description sent over the network. /// </summary> private AreaDescription m_loadedAreaDescription; /// <summary> /// RPCFileSender object for sending and receiving Area Descriptions over the network. /// </summary> private RPCFileSender m_fileSender; /// <summary> /// Unity Start function. /// /// This function is responsible for initialization, including setting up m_fileSender and joining or creating a /// Photon room. /// </summary> public void Start() { m_cubeSize = m_cubePrefab[0].transform.lossyScale.x; m_progressPanel.SetActive(false); m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication == null) { _QuitGame(); } m_tangoApplication.Register(this); m_tangoApplication.RequestPermissions(); m_fileSender = GetComponent<RPCFileSender>(); m_fileSender.OnPackageReceived += _OnAreaDescriptionTransferReceived; m_fileSender.OnPackageTransferFinished += _OnAreaDescriptionTransferFinished; m_fileSender.OnPackageTransferStarted += _OnAreaDescriptionTransferStarted; m_fileSender.OnPackageTransferError += _OnAreaDescriptionTransferError; if (!PhotonNetwork.insideLobby) { AndroidHelper.ShowAndroidToastMessage("Please wait to join the room until you are in lobby."); return; } if (Globals.m_curAreaDescription == null) { PhotonNetwork.JoinRandomRoom(); } else { PhotonNetwork.CreateRoom("Random Room"); } } /// <summary> /// Unity Update function. /// /// Used for getting mouse input for desktop debugging. /// </summary> public void Update() { #if UNITY_EDITOR if(Input.GetMouseButtonDown(0) || Input.GetKeyDown(KeyCode.Alpha1)) { AddCube(); } if(Input.GetMouseButtonDown(1) || Input.GetKeyDown(KeyCode.Alpha2)) { RemoveCube(); } #endif if (Input.GetKey(KeyCode.Escape)) { _QuitGame(); } } /// <summary> /// This is called when the Area Description export operation completes. /// </summary> /// <param name="isSuccessful">If the export operation completed successfully.</param> public void OnAreaDescriptionExported(bool isSuccessful) { if (!isSuccessful) { AndroidHelper.ShowAndroidToastMessage("Area Description export failed," + "other players will be unable to join game."); _QuitGame(); return; } m_tangoApplication.Startup(Globals.m_curAreaDescription); _StartPlayer(); } /// <summary> /// This is called when the Area Description import operation completes. /// /// Please note that the Tango Service can only load Area Description file from internal storage. /// </summary> /// <param name="isSuccessful">If the import operation completed successfully.</param> /// <param name="areaDescription">The imported Area Description.</param> public void OnAreaDescriptionImported(bool isSuccessful, AreaDescription areaDescription) { if (!isSuccessful) { AndroidHelper.ShowAndroidToastMessage("Area Description import failed, unable to join game."); _QuitGame(); return; } // Only non-master client will run this part of code. m_loadedAreaDescription = areaDescription; m_tangoApplication.Startup(m_loadedAreaDescription); _StartPlayer(); } /// <summary> /// This is called when the permission granting process is finished. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public void OnTangoPermissions(bool permissionsGranted) { if (!permissionsGranted) { AndroidHelper.ShowAndroidToastMessage("Tango permission needed"); _QuitGame(); return; } } /// <summary> /// This is called when succesfully connected to the Tango service. /// </summary> public void OnTangoServiceConnected() { } /// <summary> /// This is called when disconnected from the Tango service. /// /// We do clean up the Area Description File that was imported from download. /// </summary> public void OnTangoServiceDisconnected() { #if !UNITY_EDITOR if (Globals.m_curAreaDescription == null && m_loadedAreaDescription != null) { // This indicates that we joined a room and imported a valid temporary Area Description. m_loadedAreaDescription.Delete(); } try { Directory.Delete(TEMP_FILE_PATH, true); } catch (DirectoryNotFoundException e) { Debug.Log("Temp file directory does not exsit."); } #endif } /// <summary> /// Called when entering a room (by creating or joining it). Called on all clients (including the Master Client). /// </summary> /// <remarks>This method is commonly used to instantiate player characters. /// If a match has to be started "actively", you can call an [PunRPC](@ref PhotonView.RPC) triggered by a user's /// button-press or a timer. /// /// When this is called, you can usually already access the existing players in the room via /// PhotonNetwork.playerList. Also, all custom properties should be already available as Room.customProperties. /// Check Room.playerCount to find out if enough players are in the room to start playing.</remarks> public override void OnJoinedRoom() { #if UNITY_EDITOR m_tangoApplication.Startup(null); _StartPlayer(); #else if (Globals.m_curAreaDescription != null) { Directory.CreateDirectory(TEMP_FILE_PATH); Globals.m_curAreaDescription.ExportToFile(TEMP_FILE_PATH); } #endif m_loadedAreaDescription = Globals.m_curAreaDescription; } /// <summary> /// Called when a CreateRoom() call failed. The parameter provides ErrorCode and message (as array). /// </summary> /// <remarks> /// Most likely because the room name is already in use (some other client was faster than you). /// PUN logs some info if the PhotonNetwork.logLevel is >= PhotonLogLevel.Informational. /// </remarks> /// <param name="codeAndMsg">CodeAndMsg[0] is a short ErrorCode and codeAndMsg[1] is a string debug msg.</param> public override void OnPhotonCreateRoomFailed(object[] codeAndMsg) { AndroidHelper.ShowAndroidToastMessage("Create room failed"); Debug.Log("Create room failed" + Environment.StackTrace); _QuitGame(); } /// <summary> /// Called when a JoinRoom() call failed. The parameter provides ErrorCode and message (as array). /// </summary> /// <remarks> /// Most likely error is that the room does not exist or the room is full (some other client was faster than you). /// PUN logs some info if the PhotonNetwork.logLevel is >= PhotonLogLevel.Informational. /// </remarks> /// <param name="codeAndMsg">CodeAndMsg[0] is short ErrorCode. codeAndMsg[1] is string debug msg.</param> public override void OnPhotonJoinRoomFailed(object[] codeAndMsg) { AndroidHelper.ShowAndroidToastMessage("Join room failed"); Debug.Log("Join room failed" + Environment.StackTrace); _QuitGame(); } /// <summary> /// Called after switching to a new MasterClient when the current one leaves. /// </summary> /// <remarks> /// This is not called when this client enters a room. /// The former MasterClient is still in the player list when this method get called. /// </remarks> /// <param name="newMasterClient">New master client.</param> public override void OnMasterClientSwitched(PhotonPlayer newMasterClient) { // In the case of master client leave the room, we lost host that sharing Area Description. So, all client // should quit the room too. _QuitGame(); } /// <summary> /// Photon networking callback. Called when a new player is joined the room. /// /// We use this callback to notify master client to send over the Area Description File. /// </summary> /// <param name="newPlayer">New player that joined the room.</param> public override void OnPhotonPlayerConnected(PhotonPlayer newPlayer) { if (newPlayer == null) { Debug.LogError("newPlayer is null\n" + Environment.StackTrace); return; } byte[] dataArr; #if UNITY_EDITOR // 1mb data for testing. dataArr = new byte[1000000]; dataArr[0] = 0; dataArr[1] = 1; dataArr[2] = 2; dataArr[3] = 3; #else string path = TEMP_FILE_PATH + Globals.m_curAreaDescription.m_uuid; dataArr = File.ReadAllBytes(path); #endif // Send out the Area Description File. m_fileSender.SendPackage(newPlayer, dataArr); foreach (KeyValuePair<Vector3, GameObject> entry in m_cubeList) { Vector3 key = entry.Key; GameObject value = entry.Value; GetComponent<PhotonView>().RPC("_AddCubeAt", PhotonTargets.AllViaServer, value.transform.position, value.GetComponent<CubeType>().m_cubeType, key); } } /// <summary> /// Called after disconnecting from the Photon server. /// </summary> /// <remarks>In some cases, other callbacks are called before OnDisconnectedFromPhoton is called. /// Examples: OnConnectionFail() and OnFailedToConnectToPhoton().</remarks> public override void OnDisconnectedFromPhoton() { _QuitGame(); } /// <summary> /// Called if a connect call to the Photon server failed before the connection was established, followed by a call /// to OnDisconnectedFromPhoton(). /// </summary> /// <remarks>This is called when no connection could be established at all. /// It differs from OnConnectionFail, which is called when an existing connection fails.</remarks> /// <param name="cause">Cause of disconnect.</param> public override void OnFailedToConnectToPhoton(DisconnectCause cause) { _QuitGame(); } /// <summary> /// Change current cube type. /// </summary> /// <param name="index">The cube's index in the prefab list.</param> public void SetCubeIndex(int index) { m_currentCubeIndex = index; } /// <summary> /// Add a cube to the scene. /// </summary> public void AddCube() { if (m_localPlayer == null) { Debug.LogError("m_localPlayer is not available." + Environment.StackTrace); return; } RaycastHit hitInfo; if (Physics.Raycast(m_localPlayer.transform.position, m_localPlayer.transform.forward, out hitInfo, RAYCAST_MAX_DISTANCE)) { Vector3 center = (hitInfo.point / m_cubeSize) + (hitInfo.normal * m_cubeSize); float x = Mathf.Floor(center.x + m_cubeSize); float y = Mathf.Floor(center.y + m_cubeSize); float z = Mathf.Floor(center.z + m_cubeSize); center.x = x; center.y = y; center.z = z; int xIndex = (int)x + (WORLD_SIZE / 2); int yIndex = (int)y + (WORLD_SIZE / 2); int zIndex = (int)z + (WORLD_SIZE / 2); if (xIndex >= WORLD_SIZE || yIndex >= WORLD_SIZE || zIndex >= WORLD_SIZE || xIndex < 0 || yIndex < 0 || zIndex < 0) { Debug.Log("Index out of bound\n" + Environment.StackTrace); } Vector3 p = (center * m_cubeSize) - new Vector3(0.0f, m_cubeSize / 2.0f, 0.0f); GetComponent<PhotonView>().RPC("_AddCubeAt", PhotonTargets.AllViaServer, p, m_currentCubeIndex, new Vector3(xIndex, yIndex, zIndex)); } } /// <summary> /// Remove a cube from the scene. /// </summary> public void RemoveCube() { if (m_localPlayer == null) { Debug.LogError("m_localPlayer is not available." + Environment.StackTrace); return; } RaycastHit hitInfo; if (Physics.Raycast(m_localPlayer.transform.position, m_localPlayer.transform.forward, out hitInfo, RAYCAST_MAX_DISTANCE)) { Vector3 p = (hitInfo.collider.gameObject.transform.position + new Vector3(0.0f, m_cubeSize / 2.0f, 0.0f)) / m_cubeSize; int xIndex = (int)p.x + (WORLD_SIZE / 2); int yIndex = (int)p.y + (WORLD_SIZE / 2); int zIndex = (int)p.z + (WORLD_SIZE / 2); if (xIndex >= WORLD_SIZE || yIndex >= WORLD_SIZE || zIndex >= WORLD_SIZE || xIndex < 0 || yIndex < 0 || zIndex < 0) { Debug.Log("Index out of bound\n" + Environment.StackTrace); } GetComponent<PhotonView>().RPC("_RemoveCubeAt", PhotonTargets.AllViaServer, new Vector3(xIndex, yIndex, zIndex)); } } /// <summary> /// Callback from FileSender. Called when the m_fileSender started transfer Area Description File. /// </summary> /// <param name="size">Total size of the buffer that is going to be transferred.</param> private void _OnAreaDescriptionTransferStarted(int size) { m_progressPanel.SetActive(true); } /// <summary> /// Callback from FileSender. Called when the m_fileSender received a package. /// </summary> /// <param name="finishedPercentage">The percentage of packages have been transferred.</param> private void _OnAreaDescriptionTransferReceived(float finishedPercentage) { m_progressPanel.GetComponentInChildren<Text>().text = string.Format("Receiving Area Description:\n{0}% completed", (int)(finishedPercentage * 100)); } /// <summary> /// Callback from FileSender. Called when the m_fileSender finished transfering the full package. /// </summary> /// <param name="fullAreaDescription">The full buffer that has been transferred.</param> private void _OnAreaDescriptionTransferFinished(byte[] fullAreaDescription) { m_progressPanel.SetActive(false); #if !UNITY_EDITOR if (fullAreaDescription[0] == 0 && fullAreaDescription[1] == 1 && fullAreaDescription[2] == 2 && fullAreaDescription[3] == 3) { // If first 4 values of full Area Description is 0, we consider the file sender is a debugging host. // In that case, we will start play in motion tracking mode. m_tangoApplication.GetComponent<RelocalizingOverlay>().m_relocalizationOverlay.SetActive(false); m_tangoApplication.m_enableAreaDescriptions = false; m_tangoApplication.Startup(null); _StartPlayer(); m_localPlayer.GetComponent<TangoDeltaPoseController>().m_useAreaDescriptionPose = false; } else { Directory.CreateDirectory(TEMP_FILE_PATH); string path = TEMP_FILE_PATH + "received_area_description"; File.WriteAllBytes(path, fullAreaDescription); AreaDescription.ImportFromFile(path); } #endif } /// <summary> /// Callback from FileSender. Called when encountered error during transfer. /// </summary> private void _OnAreaDescriptionTransferError() { _QuitGame(); } /// <summary> /// Photon RPC call notifying the local client to add a cube at a specific position. /// </summary> /// <param name="cubePosition">The position of cube.</param> /// <param name="type">The type of cube.</param> /// <param name="key">Key hash key of the cube object.</param> [PunRPC] private void _AddCubeAt(Vector3 cubePosition, int type, Vector3 key) { if (m_cubeList.ContainsKey(key)) { Debug.Log("Cube index exsited"); return; } GameObject obj = Instantiate(m_cubePrefab[type], cubePosition, Quaternion.identity) as GameObject; m_cubeList.Add(key, obj); } /// <summary> /// Photon RPC call notifying the local client to remove a cube at a specific position. /// </summary> /// <param name="key">Key hash key of the cube object.</param> [PunRPC] private void _RemoveCubeAt(Vector3 key) { if (!m_cubeList.ContainsKey(key)) { Debug.LogError("Cube index doesn't exsited"); return; } Destroy(m_cubeList[key]); m_cubeList.Remove(key); } /// <summary> /// Enable the local player's camera to track the local Tango pose. /// </summary> private void _StartPlayer() { m_localPlayer = PhotonNetwork.Instantiate(m_networkDeltaPoseControllerPrefab.name, Vector3.zero, Quaternion.identity, 0); m_uiBackgroundOverlay.SetActive(false); m_localPlayer.GetComponent<TangoDeltaPoseController>().enabled = true; m_localPlayer.GetComponentInChildren<Camera>().enabled = true; } /// <summary> /// Quit the room properly. /// </summary> private void _QuitGame() { if (PhotonNetwork.inRoom) { PhotonNetwork.LeaveRoom(); } m_tangoApplication.Shutdown(); Application.LoadLevel("AreaDescriptionPicker"); } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; namespace DNXServer.Action { public class CardAction : BaseAction { public CardAction () { } public string RegisterCard(SessionData so, string qrid) { /* -1 General Error - error yang client ga perlu tau / error di aplikasi server (try-catch) ato error database (koneksi/query) -2 Upgrade Card - upgrade card di-register lewat monster detail page -3 Owned by other User -4 Owned by this User -5 Invalid QRID - qrid kartu ga ada ato owner kartu nya userID -1 (Davy Jones) -6 User Locked - too many random scan */ List<string> cardType = new List<string>(); StringDictionary checkCardType; string getUserID = "" ; string getCardTypeID = "" ; string response = ""; string getRemainingAttemp = ""; string userID = Convert.ToString(so.UserId); using (Command(@"server_check_card_type")) { AddParameter ("qrid", qrid); AddParameter ("uid", so.UserId); checkCardType = ExecuteSpRow(); if (checkCardType != null && checkCardType.Count > 0) { getCardTypeID = checkCardType["_card_type_id"]; getUserID = checkCardType["_user_id"]; getRemainingAttemp = checkCardType["_remaining_attempts"]; } else { response = "-5`0" ; } } if (string.IsNullOrEmpty (response)) { if(getCardTypeID == "-1") { response = "-6"; // lock user from scanning qrid } else if (getCardTypeID == "0" && string.IsNullOrEmpty (getUserID)) { response = "1`0"; //update monster cards using (Command(@"server_register_monster_card")) { AddParameter ("qrid", qrid); AddParameter ("userID", so.UserId); ExecuteSpWrite (); } } else if (getCardTypeID == "1" && string.IsNullOrEmpty(getUserID)) { response = "1`1"; //update item cards using (Command(@"server_register_item_card")) { AddParameter ("qrid", qrid); AddParameter ("userID", so.UserId); ExecuteSpWrite (); } } else if (getCardTypeID == "2") { response = "-2`" + getRemainingAttemp; // trying to register an upgrade cards } else if (getUserID == userID) { response = "-4`" + getRemainingAttemp; // already register by this user } else if (getUserID != userID) { response = "-3`" + getRemainingAttemp; // trying to register another person cards } } if (response == "1`0") { string newCard = GetMonsterStat(qrid); return (int)CommandResponseEnum.RegisterCardResult + "`" + response + "`" + newCard + "`"; } else if (response == "1`1") { string newCard = GetItemStat(qrid); return (int)CommandResponseEnum.RegisterCardResult + "`" + response + "`" + newCard + "`"; } else { return (int)CommandResponseEnum.RegisterCardResult + "`" + response + "`"; } } public string UnregisterCard(SessionData so, string qrid) { /* -1 General Error - error yang client ga perlu tau / error di aplikasi server (try-catch) ato error database (koneksi/query) -2 Upgrade Card - upgrade card di-unregister lewat monster detail page -3 Owned by other User -4 Invalid QRID - qrid kartu ga ada ato owner kartu nya userID -1 (Davy Jones) -5 User Locked - too many random scan */ List<string> cardType = new List<string>(); StringDictionary checkCardType; string getNewQRID = ""; string getUserID = "" ; string getCardTypeID = "" ; string response = ""; string getRemainingAttemp = ""; string userID = Convert.ToString(so.UserId); using (Command(@"server_check_card_type")) { AddParameter ("qrid", qrid); AddParameter ("uid", so.UserId); checkCardType = ExecuteSpRow(); if (checkCardType != null && checkCardType.Count > 0) { getCardTypeID = checkCardType["_card_type_id"]; getUserID = checkCardType["_user_id"]; getRemainingAttemp = checkCardType["_remaining_attempts"]; //Console.WriteLine(getCardTypeID + "~" + getUserID); } else { response = "-4`0"; } } if (string.IsNullOrEmpty (response)) { if(getCardTypeID == "-1") { response = "-5"; // lock user from scanning qrid } else if (getCardTypeID == "0" && getUserID == userID) { response = "1`0"; //update monster cards using (Command(@"server_unregister_monster_card")) { AddParameter ("qrid", qrid); AddParameter ("userID", so.UserId); ExecuteSpWrite (); } } else if (getCardTypeID == "1" || getCardTypeID == "2") { response = "-2`" + getRemainingAttemp; // unregister selain monster cards } else if (getUserID != userID) { response = "-3`" + getRemainingAttemp; // not owned by user } } if (response == "1`0") { // tambahin balikin url buat di kasih ke user baru // flow: user A unregister-> di unregister oleh server -> send request ke web dnx buat generate qrid // -> website kirim url qrid -> server terima response -> server kirim ke user A using (Command (@"server_update_monster_qrid")) { AddParameter ("qrid", qrid); getNewQRID = ExecuteSpRow()["_qrid"]; } string url = new WebsiteRequest().WebRequestQRID(getNewQRID); return (int)CommandResponseEnum.UnregisterCardResult + "`" + response + "`" + qrid + "`" + url + "`"; } else { return (int)CommandResponseEnum.UnregisterCardResult + "`" + response + "`"; } //return (int)CommandResponseEnum.UnregisterCardResult; } public string RegisterUpgradeCard(SessionData so, string upqrid, string qrid) { /* UPGRADE ERROR CODES -1 = GENERAL ERROR -2 = CARD IS NOT UPGRADE CARD -3 = ALREADY REGISTERED TO OTHER MONSTER -4 = ALREADY REGISTERED TO THIS MONSTER -5 = INCOMPATIBLE -6 = INVALID QRID -7 = FEATURE LOCKED */ StringDictionary checkUpgradeCard; StringDictionary ownerUpgradeCard; StringDictionary checkCompatible; string getUserID = "" ; string getOwner = ""; string getCardTypeID = "" ; string response = ""; string getRemainingAttemp = ""; string userID = Convert.ToString(so.UserId); bool isAvailable = false; using (Command(@"server_check_card_type")) { AddParameter ("qrid", upqrid); AddParameter ("uid", so.UserId); checkUpgradeCard = ExecuteSpRow(); if (checkUpgradeCard != null && checkUpgradeCard.Count > 0) { getCardTypeID = checkUpgradeCard["_card_type_id"]; getUserID = checkUpgradeCard["_user_id"]; getRemainingAttemp = checkUpgradeCard["_remaining_attempts"]; Console.WriteLine(getCardTypeID + "~" + getUserID); } else { response = "-6`0"; // invalid qrid } } if (string.IsNullOrEmpty(response)) { if (getCardTypeID == "0" || getCardTypeID == "1") { response = "-2`" + getRemainingAttemp; // not upgrade card } else if (getCardTypeID == "-1") { response = "-7"; // lock user from scanning qrid } else { using (Command (@"server_check_upgrade_card_owner")) { AddParameter ("qrid", upqrid); ownerUpgradeCard = ExecuteSpRow (); if (ownerUpgradeCard != null && ownerUpgradeCard.Count > 0) { getOwner = ownerUpgradeCard["_mons_card_qrid"]; } else { isAvailable = true; } } if (getOwner == qrid) { // registered to this user response = "-4`" + getRemainingAttemp; } else { //registered to other user response = "-3`" + getRemainingAttemp; } if (isAvailable == true) { // check compatible using (Command (@"server_check_compatible_upgrade_card")) { AddParameter ("qrid", qrid); AddParameter ("up_qrid", upqrid); checkCompatible = ExecuteSpRow (); if (checkCompatible != null && checkCompatible.Count > 0) { response = "1"; } else { // null response: incompatible response = "-5`" + getRemainingAttemp; } } //if null incompatible else registered } } } //do query to check upgrade card registered or not if (response == "1") { //kalo success register using (Command (@"server_register_upgrade_card")) { AddParameter ("qrid", qrid); AddParameter ("up_qrid", upqrid); AddParameter ("userid", so.UserId); ExecuteSpWrite(); } string success = new InventoryAction ().GetInventory (so, qrid); return success; } else { return (int)CommandResponseEnum.UpgradeMonsterResult + "`" + response + "`"; } } public string GetMonsterStat(string MonsterQRID) { Command (@"server_get_monster_card"); { AddParameter ("monster_qrid", MonsterQRID); List<string> monsters = new List<string> (); StringDictionary result = ExecuteSpRow (); List<string> mons = new List<string> (); mons.Add (result ["_mons_card_qrid"]); mons.Add ("0"); // monster card type mons.Add (result ["_mons_tmplt_id"]); mons.Add (result ["_mons_tmplt_name"]); mons.Add (result ["_version"]); mons.Add (result ["_subversion"]); mons.Add (result ["_hp"]); mons.Add (result ["_hp_regen"]); mons.Add (result ["_hp_regen_pm"]); mons.Add (result ["_mp"]); mons.Add (result ["_mp_regen"]); mons.Add (result ["_mp_regen_pm"]); mons.Add (result ["_spd"]); mons.Add (result ["_spd_pm"]); mons.Add (result ["_p_atk"]); mons.Add (result ["_p_atk_pm"]); mons.Add (result ["_m_atk"]); mons.Add (result ["_m_atk_pm"]); mons.Add (result ["_p_def"]); mons.Add (result ["_p_def_pm"]); mons.Add (result ["_m_def"]); mons.Add (result ["_m_def_pm"]); mons.Add (result ["_acc"]); mons.Add (result ["_acc_pm"]); mons.Add (result ["_eva"]); mons.Add (result ["_eva_pm"]); mons.Add (result ["_cri"]); mons.Add (result ["_cri_pm"]); mons.Add (result ["_f_legs"]); mons.Add (result ["_r_legs"]); mons.Add (result ["_tail"]); mons.Add (result ["_w_slot"]); mons.Add (result ["_l_slot"]); mons.Add (result ["_r_slot"]); mons.Add (result ["_wins"]); mons.Add (result ["_loses"]); mons.Add (result ["_hunger"]); mons.Add (result ["_happiness"]); mons.Add (result ["_clean"]); mons.Add (result ["_discipline"]); mons.Add (result ["_sick"]); mons.Add (result ["_exp"]); mons.Add (result ["_exp_needed"]); mons.Add (result["_expired_date"]); mons.Add (result["_is_printed"]); string monsString = String.Join ("~", mons); monsters.Add (monsString); string monsterData = String.Join ("`", monsters); return monsterData; } } public string GetItemStat(string itemQRID) { Command (@"server_get_item_card"); { AddParameter ("item_qrid", itemQRID); List<string> itemList = new List<string> (); foreach (StringDictionary result in ExecuteSpRead()) { List<string> item = new List<string> (); item.Add (result ["_item_card_qrid"]); item.Add ("1"); // monster card type item.Add (result ["_item_tmplt_id"]); item.Add (result ["_qty"]); string itemString = String.Join ("~", item); itemList.Add (itemString); } string itemData = String.Join ("`", itemList); return itemData; } } public string GetUserMonsterCards(SessionData so) { string userID = Convert.ToString(so.UserId); StringBuilder builder = new StringBuilder (); string monsterString = new MonsterAction ().GetMonsterData (so); string itemString = new ItemAction().GetItems(so); if (string.IsNullOrEmpty(monsterString) && string.IsNullOrEmpty(itemString)) { return ((int)CommandResponseEnum.LoadCard).ToString() + "``" ; } builder.Append ((int)CommandResponseEnum.LoadCard); if (monsterString.Length != 0) { builder.Append ("`"); builder.Append (monsterString); } if (itemString.Length != 0) { builder.Append ("`"); builder.Append (itemString); } builder.Append ("`"); return builder.ToString(); } } }
/** * Copyright (c) 2014-present, 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. */ // @Generated by gentest/gentest.rb from gentest/fixtures/YGAlignItemsTest.html using System; using NUnit.Framework; namespace Facebook.Yoga { [TestFixture] public class YGAlignItemsTest { [Test] public void Test_align_items_stretch() { YogaNode root = new YogaNode(); root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(100f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_center() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.Center; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_flex_start() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.FlexStart; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_items_flex_end() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.FlexEnd; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 10; root_child0.Height = 10; root.Insert(0, root_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(90f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(10f, root_child0.LayoutWidth); Assert.AreEqual(10f, root_child0.LayoutHeight); } [Test] public void Test_align_baseline() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(30f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); } [Test] public void Test_align_baseline_child() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(); root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(); root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline_override() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(); root_child1_child1.AlignSelf = YogaAlign.Baseline; root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(); root_child1_child3.AlignSelf = YogaAlign.Baseline; root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_multiline_no_override_on_secondline() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 60; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.FlexDirection = YogaFlexDirection.Row; root_child1.Wrap = YogaWrap.Wrap; root_child1.Width = 50; root_child1.Height = 25; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 25; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child1_child1 = new YogaNode(); root_child1_child1.Width = 25; root_child1_child1.Height = 10; root_child1.Insert(1, root_child1_child1); YogaNode root_child1_child2 = new YogaNode(); root_child1_child2.Width = 25; root_child1_child2.Height = 20; root_child1.Insert(2, root_child1_child2); YogaNode root_child1_child3 = new YogaNode(); root_child1_child3.AlignSelf = YogaAlign.Baseline; root_child1_child3.Width = 25; root_child1_child3.Height = 10; root_child1.Insert(3, root_child1_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(25f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(25f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(60f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(25f, root_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(25f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child1_child1.LayoutX); Assert.AreEqual(0f, root_child1_child1.LayoutY); Assert.AreEqual(25f, root_child1_child1.LayoutWidth); Assert.AreEqual(10f, root_child1_child1.LayoutHeight); Assert.AreEqual(25f, root_child1_child2.LayoutX); Assert.AreEqual(20f, root_child1_child2.LayoutY); Assert.AreEqual(25f, root_child1_child2.LayoutWidth); Assert.AreEqual(20f, root_child1_child2.LayoutHeight); Assert.AreEqual(0f, root_child1_child3.LayoutX); Assert.AreEqual(20f, root_child1_child3.LayoutY); Assert.AreEqual(25f, root_child1_child3.LayoutWidth); Assert.AreEqual(10f, root_child1_child3.LayoutHeight); } [Test] public void Test_align_baseline_child_top() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Top = 10; root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(10f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_top2() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Top = 5; root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(45f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(45f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_double_nested_child() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child0_child0 = new YogaNode(); root_child0_child0.Width = 50; root_child0_child0.Height = 20; root_child0.Insert(0, root_child0_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 15; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(15f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child0_child0.LayoutX); Assert.AreEqual(0f, root_child0_child0.LayoutY); Assert.AreEqual(50f, root_child0_child0.LayoutWidth); Assert.AreEqual(20f, root_child0_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(5f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(15f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_column() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); } [Test] public void Test_align_baseline_child_margin() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.MarginLeft = 5; root_child0.MarginTop = 5; root_child0.MarginRight = 5; root_child0.MarginBottom = 5; root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.MarginLeft = 1; root_child1_child0.MarginTop = 1; root_child1_child0.MarginRight = 1; root_child1_child0.MarginBottom = 1; root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(60f, root_child1.LayoutX); Assert.AreEqual(44f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(1f, root_child1_child0.LayoutX); Assert.AreEqual(1f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(-10f, root_child1.LayoutX); Assert.AreEqual(44f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(-1f, root_child1_child0.LayoutX); Assert.AreEqual(1f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_child_padding() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.PaddingLeft = 5; root.PaddingTop = 5; root.PaddingRight = 5; root.PaddingBottom = 5; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.PaddingLeft = 5; root_child1.PaddingTop = 5; root_child1.PaddingRight = 5; root_child1.PaddingBottom = 5; root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(5f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(55f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(5f, root_child1_child0.LayoutX); Assert.AreEqual(5f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(45f, root_child0.LayoutX); Assert.AreEqual(5f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(-5f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(-5f, root_child1_child0.LayoutX); Assert.AreEqual(5f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); } [Test] public void Test_align_baseline_multiline() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 20; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(); root_child2.Width = 50; root_child2.Height = 20; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(); root_child2_child0.Width = 50; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(); root_child3.Width = 50; root_child3.Height = 50; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(50f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(20f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(60f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(50f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_column() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 30; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 20; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(); root_child2.Width = 40; root_child2.Height = 70; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(); root_child2_child0.Width = 10; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(70f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_column2() { YogaNode root = new YogaNode(); root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 30; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 20; root_child1_child0.Height = 20; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(); root_child2.Width = 40; root_child2.Height = 70; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(); root_child2_child0.Width = 10; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(70f, root_child1.LayoutX); Assert.AreEqual(50f, root_child1.LayoutY); Assert.AreEqual(30f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(10f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(20f, root_child1_child0.LayoutWidth); Assert.AreEqual(20f, root_child1_child0.LayoutHeight); Assert.AreEqual(10f, root_child2.LayoutX); Assert.AreEqual(0f, root_child2.LayoutY); Assert.AreEqual(40f, root_child2.LayoutWidth); Assert.AreEqual(70f, root_child2.LayoutHeight); Assert.AreEqual(30f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(10f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(70f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } [Test] public void Test_align_baseline_multiline_row_and_column() { YogaNode root = new YogaNode(); root.FlexDirection = YogaFlexDirection.Row; root.AlignItems = YogaAlign.Baseline; root.Wrap = YogaWrap.Wrap; root.Width = 100; root.Height = 100; YogaNode root_child0 = new YogaNode(); root_child0.Width = 50; root_child0.Height = 50; root.Insert(0, root_child0); YogaNode root_child1 = new YogaNode(); root_child1.Width = 50; root_child1.Height = 50; root.Insert(1, root_child1); YogaNode root_child1_child0 = new YogaNode(); root_child1_child0.Width = 50; root_child1_child0.Height = 10; root_child1.Insert(0, root_child1_child0); YogaNode root_child2 = new YogaNode(); root_child2.Width = 50; root_child2.Height = 20; root.Insert(2, root_child2); YogaNode root_child2_child0 = new YogaNode(); root_child2_child0.Width = 50; root_child2_child0.Height = 10; root_child2.Insert(0, root_child2_child0); YogaNode root_child3 = new YogaNode(); root_child3.Width = 50; root_child3.Height = 20; root.Insert(3, root_child3); root.StyleDirection = YogaDirection.LTR; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(0f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(50f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(0f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(50f, root_child3.LayoutX); Assert.AreEqual(90f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); root.StyleDirection = YogaDirection.RTL; root.CalculateLayout(); Assert.AreEqual(0f, root.LayoutX); Assert.AreEqual(0f, root.LayoutY); Assert.AreEqual(100f, root.LayoutWidth); Assert.AreEqual(100f, root.LayoutHeight); Assert.AreEqual(50f, root_child0.LayoutX); Assert.AreEqual(0f, root_child0.LayoutY); Assert.AreEqual(50f, root_child0.LayoutWidth); Assert.AreEqual(50f, root_child0.LayoutHeight); Assert.AreEqual(0f, root_child1.LayoutX); Assert.AreEqual(40f, root_child1.LayoutY); Assert.AreEqual(50f, root_child1.LayoutWidth); Assert.AreEqual(50f, root_child1.LayoutHeight); Assert.AreEqual(0f, root_child1_child0.LayoutX); Assert.AreEqual(0f, root_child1_child0.LayoutY); Assert.AreEqual(50f, root_child1_child0.LayoutWidth); Assert.AreEqual(10f, root_child1_child0.LayoutHeight); Assert.AreEqual(50f, root_child2.LayoutX); Assert.AreEqual(100f, root_child2.LayoutY); Assert.AreEqual(50f, root_child2.LayoutWidth); Assert.AreEqual(20f, root_child2.LayoutHeight); Assert.AreEqual(0f, root_child2_child0.LayoutX); Assert.AreEqual(0f, root_child2_child0.LayoutY); Assert.AreEqual(50f, root_child2_child0.LayoutWidth); Assert.AreEqual(10f, root_child2_child0.LayoutHeight); Assert.AreEqual(0f, root_child3.LayoutX); Assert.AreEqual(90f, root_child3.LayoutY); Assert.AreEqual(50f, root_child3.LayoutWidth); Assert.AreEqual(20f, root_child3.LayoutHeight); } } }
// 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. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Logging.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Logging.V2.Snippets { public class GeneratedMetricsServiceV2ClientSnippets { public async Task ListLogMetricsAsync() { // Snippet: ListLogMetricsAsync(string,string,int?,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedParent = MetricsServiceV2Client.FormatParentName("[PROJECT]"); // Make the request IPagedAsyncEnumerable<ListLogMetricsResponse,LogMetric> response = metricsServiceV2Client.ListLogMetricsAsync(formattedParent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((LogMetric item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over fixed-sized pages, lazily performing RPCs as required int pageSize = 10; IAsyncEnumerable<FixedSizePage<LogMetric>> fixedSizePages = response.AsPages().WithFixedSize(pageSize); await fixedSizePages.ForEachAsync((FixedSizePage<LogMetric> page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { Console.WriteLine(item); } }); // End snippet } public void ListLogMetrics() { // Snippet: ListLogMetrics(string,string,int?,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedParent = MetricsServiceV2Client.FormatParentName("[PROJECT]"); // Make the request IPagedEnumerable<ListLogMetricsResponse,LogMetric> response = metricsServiceV2Client.ListLogMetrics(formattedParent); // Iterate over all response items, lazily performing RPCs as required foreach (LogMetric item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over fixed-sized pages, lazily performing RPCs as required int pageSize = 10; foreach (FixedSizePage<LogMetric> page in response.AsPages().WithFixedSize(pageSize)) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (LogMetric item in page) { Console.WriteLine(item); } } // End snippet } public async Task GetLogMetricAsync() { // Snippet: GetLogMetricAsync(string,CallSettings) // Additional: GetLogMetricAsync(string,CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); // Make the request LogMetric response = await metricsServiceV2Client.GetLogMetricAsync(formattedMetricName); // End snippet } public void GetLogMetric() { // Snippet: GetLogMetric(string,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); // Make the request LogMetric response = metricsServiceV2Client.GetLogMetric(formattedMetricName); // End snippet } public async Task CreateLogMetricAsync() { // Snippet: CreateLogMetricAsync(string,LogMetric,CallSettings) // Additional: CreateLogMetricAsync(string,LogMetric,CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedParent = MetricsServiceV2Client.FormatParentName("[PROJECT]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.CreateLogMetricAsync(formattedParent, metric); // End snippet } public void CreateLogMetric() { // Snippet: CreateLogMetric(string,LogMetric,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedParent = MetricsServiceV2Client.FormatParentName("[PROJECT]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.CreateLogMetric(formattedParent, metric); // End snippet } public async Task UpdateLogMetricAsync() { // Snippet: UpdateLogMetricAsync(string,LogMetric,CallSettings) // Additional: UpdateLogMetricAsync(string,LogMetric,CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = await metricsServiceV2Client.UpdateLogMetricAsync(formattedMetricName, metric); // End snippet } public void UpdateLogMetric() { // Snippet: UpdateLogMetric(string,LogMetric,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); LogMetric metric = new LogMetric(); // Make the request LogMetric response = metricsServiceV2Client.UpdateLogMetric(formattedMetricName, metric); // End snippet } public async Task DeleteLogMetricAsync() { // Snippet: DeleteLogMetricAsync(string,CallSettings) // Additional: DeleteLogMetricAsync(string,CancellationToken) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); // Make the request await metricsServiceV2Client.DeleteLogMetricAsync(formattedMetricName); // End snippet } public void DeleteLogMetric() { // Snippet: DeleteLogMetric(string,CallSettings) // Create client MetricsServiceV2Client metricsServiceV2Client = MetricsServiceV2Client.Create(); // Initialize request argument(s) string formattedMetricName = MetricsServiceV2Client.FormatMetricName("[PROJECT]", "[METRIC]"); // Make the request metricsServiceV2Client.DeleteLogMetric(formattedMetricName); // End snippet } } }
#if UNITY_WINRT && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using Newtonsoft.Json.Utilities; using System.Globalization; using System.Linq; namespace Newtonsoft.Json.Linq { /// <summary> /// Contains the LINQ to JSON extension methods. /// </summary> public static class Extensions { /// <summary> /// Returns a collection of tokens that contains the ancestors of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns> public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Ancestors()).AsJEnumerable(); } /// <summary> /// Returns a collection of tokens that contains the descendants of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns> public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Descendants()).AsJEnumerable(); } /// <summary> /// Returns a collection of child properties of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns> public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source) { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(d => d.Properties()).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection with the given key. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection with the given key.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key) { return Values<JToken, JToken>(source, key).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source) { return source.Values(null); } /// <summary> /// Returns a collection of converted child values of every object in the source collection with the given key. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection with the given key.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key) { return Values<JToken, U>(source, key); } /// <summary> /// Returns a collection of converted child values of every object in the source collection. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source) { return Values<JToken, U>(source, null); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<U>(this IEnumerable<JToken> value) { return value.Value<JToken, U>(); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<T, U>(this IEnumerable<T> value) where T : JToken { ValidationUtils.ArgumentNotNull(value, "source"); JToken token = value as JToken; if (token == null) throw new ArgumentException("Source value must be a JToken."); return token.Convert<JToken, U>(); } internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (JToken token in source) { if (key == null) { if (token is JValue) { yield return Convert<JValue, U>((JValue)token); } else { foreach (JToken t in token.Children()) { yield return t.Convert<JToken, U>(); } } } else { JToken value = token[key]; if (value != null) yield return value.Convert<JToken, U>(); } } yield break; } /// <summary> /// Returns a collection of child tokens of every array in the source collection. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken { return Children<T, JToken>(source).AsJEnumerable(); } /// <summary> /// Returns a collection of converted child tokens of every array in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <typeparam name="T">The source collection type.</typeparam> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(c => c.Children()).Convert<JToken, U>(); } internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (T token in source) { yield return Convert<JToken, U>(token); } } internal static U Convert<T, U>(this T token) where T : JToken { if (token == null) return default(U); if (token is U // don't want to cast JValue to its interfaces, want to get the internal value && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable)) { // HACK return (U)(object)token; } else { JValue value = token as JValue; if (value == null) throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T))); if (value.Value is U) return (U)value.Value; Type targetType = typeof(U); if (ReflectionUtils.IsNullableType(targetType)) { if (value.Value == null) return default(U); targetType = Nullable.GetUnderlyingType(targetType); } return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); } } /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source) { return source.AsJEnumerable<JToken>(); } /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T : JToken { if (source == null) return null; else if (source is IJEnumerable<T>) return (IJEnumerable<T>)source; else return new JEnumerable<T>(source); } } } #endif
// 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.Text.Utf8; namespace Json.Net.Tests { public struct JsonParser : IDisposable { private byte[] _buffer; private int _index; private int _end; private int _dbIndex; private int _insideObject; private int _insideArray; public JsonTokenType TokenType; private bool _jsonStartIsObject; private const int RowSize = 9; // Do not change, unless you also change FindLocation public enum JsonTokenType { // Start = 0 state reserved for internal use ObjectStart = 1, ObjectEnd = 2, ArrayStart = 3, ArrayEnd = 4, Property = 5, Value = 6 }; public enum JsonValueType { String, Number, Object, Array, True, False, Null } public JsonParser(byte[] buffer, int lengthOfJson) { _buffer = buffer; _insideObject = 0; _insideArray = 0; TokenType = 0; _index = 0; _end = lengthOfJson; var nextByte = _buffer[_index]; while (Utf8String.IsWhiteSpace(nextByte) || nextByte == 0) { _index++; nextByte = _buffer[_index]; } _dbIndex = _end + 1; _jsonStartIsObject = _buffer[_index] == '{'; } public void Dispose() { } public JsonParseObject Parse() { int numValues = 0; int numPairs = 0; int numObj = 0; int numArr = 0; int topOfStackObj = _buffer.Length - 1; int topOfStackArr = _buffer.Length - 1; while (Read()) { var tokenType = TokenType; switch (tokenType) { case JsonTokenType.ObjectStart: CopyNumber(_index); CopyNumber(-1); CopyByte((byte)JsonDb.JsonValueType.Object); PushOnObjectStack(numPairs, topOfStackObj); topOfStackObj -= 8; numPairs = 0; numObj++; break; case JsonTokenType.ObjectEnd: CopyNumberAtLocation(numPairs, FindLocation(numObj - 1, true)); numObj--; numPairs += PopFromObjectStack(topOfStackObj); topOfStackObj += 8; break; case JsonTokenType.ArrayStart: CopyNumber(_index); CopyNumber(-1); CopyByte((byte)JsonDb.JsonValueType.Array); PushOnArrayStack(numValues, topOfStackArr); topOfStackArr -= 8; numValues = 0; numArr++; break; case JsonTokenType.ArrayEnd: CopyNumberAtLocation(numValues, FindLocation(numArr - 1, false)); numArr--; numValues += PopFromArrayStack(topOfStackArr); topOfStackArr += 8; break; case JsonTokenType.Property: GetName(); numPairs++; GetValue(); numPairs++; numValues++; numValues++; break; case JsonTokenType.Value: GetValue(); numValues++; numPairs++; break; default: throw new ArgumentOutOfRangeException(); } } /*for(int i = _end+1; i < _dbIndex; i+=RowSize) { Console.Write(i + ":"); Console.Write(BitConverter.ToInt32(_buffer, i) + ":"); Console.Write(i + 4 + ":"); Console.Write(BitConverter.ToInt32(_buffer, i + 4) + ":"); Console.Write(i + 8 + ":"); Console.WriteLine(_buffer[i + 8]); }*/ /*for (int i = _buffer.Length - 1 - 4; i > _buffer.Length - 1 - 48; i-=4) { Console.WriteLine(BitConverter.ToInt32(_buffer, i)); }*/ return new JsonParseObject(_buffer, _end + 1, _dbIndex); } private void PushOnObjectStack(int val, int topOfStack) { CopyNumberAtLocation(val, topOfStack - 8); } private int PopFromObjectStack(int topOfStack) { return GetIntFrom(topOfStack); } private void PushOnArrayStack(int val, int topOfStack) { CopyNumberAtLocation(val, topOfStack - 4); } private int PopFromArrayStack(int topOfStack) { return GetIntFrom(topOfStack + 4); } private int FindLocation(int index, bool lookingForObject) { int startRow = _end + 1; int rowCounter = 0; int numFound = 0; while (true) { int numberOfRows = (rowCounter << 3) + rowCounter; // multiply by RowSize which is 9 int locationStart = startRow + numberOfRows; int locationOfTypeCode = locationStart + 8; int locationOfLength = locationStart + 4; var typeCode = _buffer[locationOfTypeCode]; var length = GetIntFrom(locationOfLength); if (length == -1 && (lookingForObject ? typeCode == (byte)JsonDb.JsonValueType.Object : typeCode == (byte)JsonDb.JsonValueType.Array)) { numFound++; } if (index == numFound - 1) { return locationOfLength; } else { if (length > 0 && (typeCode == (byte)JsonDb.JsonValueType.Object || typeCode == (byte)JsonDb.JsonValueType.Array)) { rowCounter += length; } rowCounter++; } } } private int GetIntFrom(int loc) { return BitConverter.ToInt32(_buffer, loc); } private bool Read() { var canRead = _index < _end; if (canRead) MoveToNextTokenType(); return canRead; } private void GetName() { SkipEmpty(); ReadStringValue(); _index++; } private JsonDb.JsonValueType GetJsonDb.JsonValueType() { var nextByte = _buffer[_index]; while (Utf8String.IsWhiteSpace(nextByte)) { _index++; nextByte = _buffer[_index]; } if (nextByte == '"') { return JsonDb.JsonValueType.String; } if (nextByte == '{') { return JsonDb.JsonValueType.Object; } if (nextByte == '[') { return JsonDb.JsonValueType.Array; } if (nextByte == 't') { return JsonDb.JsonValueType.True; } if (nextByte == 'f') { return JsonDb.JsonValueType.False; } if (nextByte == 'n') { return JsonDb.JsonValueType.Null; } if (nextByte == '-' || (nextByte >= '0' && nextByte <= '9')) { return JsonDb.JsonValueType.Number; } throw new FormatException("Invalid json, tried to read char '" + nextByte + "'."); } private void GetValue() { var type = GetJsonDb.JsonValueType(); SkipEmpty(); switch (type) { case JsonDb.JsonValueType.String: ReadStringValue(); return; case JsonDb.JsonValueType.Number: ReadNumberValue(); return; case JsonDb.JsonValueType.True: ReadTrueValue(); return; case JsonDb.JsonValueType.False: ReadFalseValue(); return; case JsonDb.JsonValueType.Null: ReadNullValue(); return; case JsonDb.JsonValueType.Object: case JsonDb.JsonValueType.Array: return; default: throw new ArgumentException("Invalid json value type '" + type + "'."); } } private void ReadStringValue() { _index++; var count = _index; do { while (_buffer[count] != '"') { count++; } count++; } while (AreNumOfBackSlashesAtEndOfStringOdd(count - 2)); var strLength = count - _index; CopyData(_index, strLength - 1); _index += strLength; SkipEmpty(); } private void CopyData(int startingIndex, int length) { CopyNumber(startingIndex); CopyNumber(length); _dbIndex += 1; } private void CopyNumber(int num) { _buffer[_dbIndex] = (byte)num; _buffer[_dbIndex + 1] = (byte)(num >> 8); _buffer[_dbIndex + 2] = (byte)(num >> 16); _buffer[_dbIndex + 3] = (byte)(num >> 24); _dbIndex += 4; } private void CopyByte(byte num) { _buffer[_dbIndex] = num; _dbIndex += 1; } private void CopyNumberAtLocation(int num, int loc) { _buffer[loc] = (byte)num; _buffer[loc + 1] = (byte)(num >> 8); _buffer[loc + 2] = (byte)(num >> 16); _buffer[loc + 3] = (byte)(num >> 24); } private bool AreNumOfBackSlashesAtEndOfStringOdd(int count) { var length = count - _index; if (length < 0) return false; var nextByte = _buffer[count]; if (nextByte != '\\') return false; var numOfBackSlashes = 0; while (nextByte == '\\') { numOfBackSlashes++; if ((length - numOfBackSlashes) < 0) return numOfBackSlashes % 2 != 0; nextByte = _buffer[count - numOfBackSlashes]; } return numOfBackSlashes % 2 != 0; } private void ReadNumberValue(bool copyData = false) { var count = _index; var nextByte = _buffer[count]; if (nextByte == '-') { count++; } nextByte = _buffer[count]; while (nextByte >= '0' && nextByte <= '9') { count++; nextByte = _buffer[count]; } if (nextByte == '.') { count++; } nextByte = _buffer[count]; while (nextByte >= '0' && nextByte <= '9') { count++; nextByte = _buffer[count]; } if (nextByte == 'e' || nextByte == 'E') { count++; nextByte = _buffer[count]; if (nextByte == '-' || nextByte == '+') { count++; } nextByte = _buffer[count]; while (nextByte >= '0' && nextByte <= '9') { count++; nextByte = _buffer[count]; } } var length = count - _index; CopyData(_index, count - _index); _index += length; SkipEmpty(); } private void ReadTrueValue(bool copyData = false) { CopyData(_index, 4); if (_buffer[_index + 1] != 'r' || _buffer[_index + 2] != 'u' || _buffer[_index + 3] != 'e') { throw new FormatException("Invalid json, tried to read 'true'."); } _index += 4; SkipEmpty(); } private void ReadFalseValue(bool copyData = false) { CopyData(_index, 5); if (_buffer[_index + 1] != 'a' || _buffer[_index + 2] != 'l' || _buffer[_index + 3] != 's' || _buffer[_index + 4] != 'e') { throw new FormatException("Invalid json, tried to read 'false'."); } _index += 5; SkipEmpty(); } private void ReadNullValue(bool copyData = false) { CopyData(_index, 4); if (_buffer[_index + 1] != 'u' || _buffer[_index + 2] != 'l' || _buffer[_index + 3] != 'l') { throw new FormatException("Invalid json, tried to read 'null'."); } _index += 4; SkipEmpty(); } private void SkipEmpty() { var nextByte = _buffer[_index]; while (Utf8String.IsWhiteSpace(nextByte)) { _index++; nextByte = _buffer[_index]; } } private void MoveToNextTokenType() { var nextByte = _buffer[_index]; while (Utf8String.IsWhiteSpace(nextByte)) { _index++; nextByte = _buffer[_index]; } switch (TokenType) { case JsonTokenType.ObjectStart: if (nextByte != '}') { TokenType = JsonTokenType.Property; return; } break; case JsonTokenType.ObjectEnd: if (nextByte == ',') { _index++; if (_insideObject == _insideArray) { TokenType = !_jsonStartIsObject ? JsonTokenType.Property : JsonTokenType.Value; return; } TokenType = _insideObject > _insideArray ? JsonTokenType.Property : JsonTokenType.Value; return; } break; case JsonTokenType.ArrayStart: if (nextByte != ']') { TokenType = JsonTokenType.Value; return; } break; case JsonTokenType.ArrayEnd: if (nextByte == ',') { _index++; if (_insideObject == _insideArray) { TokenType = !_jsonStartIsObject ? JsonTokenType.Property : JsonTokenType.Value; return; } TokenType = _insideObject > _insideArray ? JsonTokenType.Property : JsonTokenType.Value; return; } break; case JsonTokenType.Property: if (nextByte == ',') { _index++; return; } break; case JsonTokenType.Value: if (nextByte == ',') { _index++; return; } break; } _index++; switch (nextByte) { case (byte)'{': _insideObject++; TokenType = JsonTokenType.ObjectStart; return; case (byte)'}': _insideObject--; TokenType = JsonTokenType.ObjectEnd; return; case (byte)'[': _insideArray++; TokenType = JsonTokenType.ArrayStart; return; case (byte)']': _insideArray--; TokenType = JsonTokenType.ArrayEnd; return; default: throw new FormatException("Unable to get next token type. Check json format."); } } } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Statements { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime; using System.Activities.Validation; using System.Linq; using System.Activities.Expressions; public sealed class Compensate : NativeActivity { static Constraint compensateWithNoTarget = Compensate.CompensateWithNoTarget(); InternalCompensate internalCompensate; DefaultCompensation defaultCompensation; Variable<CompensationToken> currentCompensationToken; public Compensate() : base() { this.currentCompensationToken = new Variable<CompensationToken>(); } [DefaultValue(null)] public InArgument<CompensationToken> Target { get; set; } DefaultCompensation DefaultCompensation { get { if (this.defaultCompensation == null) { this.defaultCompensation = new DefaultCompensation() { Target = new InArgument<CompensationToken>(this.currentCompensationToken), }; } return this.defaultCompensation; } } InternalCompensate InternalCompensate { get { if (this.internalCompensate == null) { this.internalCompensate = new InternalCompensate() { Target = new InArgument<CompensationToken>(new ArgumentValue<CompensationToken> { ArgumentName = "Target" }), }; } return this.internalCompensate; } } protected override void CacheMetadata(NativeActivityMetadata metadata) { RuntimeArgument targetArgument = new RuntimeArgument("Target", typeof(CompensationToken), ArgumentDirection.In); metadata.Bind(this.Target, targetArgument); metadata.SetArgumentsCollection(new Collection<RuntimeArgument> { targetArgument }); metadata.SetImplementationVariablesCollection(new Collection<Variable> { this.currentCompensationToken }); Fx.Assert(DefaultCompensation != null, "DefaultCompensation must be valid"); Fx.Assert(InternalCompensate != null, "InternalCompensate must be valid"); metadata.SetImplementationChildrenCollection( new Collection<Activity> { DefaultCompensation, InternalCompensate }); } internal override IList<Constraint> InternalGetConstraints() { return new List<Constraint>(1) { compensateWithNoTarget }; } static Constraint CompensateWithNoTarget() { DelegateInArgument<Compensate> element = new DelegateInArgument<Compensate> { Name = "element" }; DelegateInArgument<ValidationContext> validationContext = new DelegateInArgument<ValidationContext> { Name = "validationContext" }; Variable<bool> assertFlag = new Variable<bool> { Name = "assertFlag" }; Variable<IEnumerable<Activity>> elements = new Variable<IEnumerable<Activity>>() { Name = "elements" }; Variable<int> index = new Variable<int>() { Name = "index" }; return new Constraint<Compensate> { Body = new ActivityAction<Compensate, ValidationContext> { Argument1 = element, Argument2 = validationContext, Handler = new Sequence { Variables = { assertFlag, elements, index }, Activities = { new If { Condition = new InArgument<bool>((env) => element.Get(env).Target != null), Then = new Assign<bool> { To = assertFlag, Value = true }, Else = new Sequence { Activities = { new Assign<IEnumerable<Activity>> { To = elements, Value = new GetParentChain { ValidationContext = validationContext, }, }, new While(env => (assertFlag.Get(env) != true) && index.Get(env) < elements.Get(env).Count()) { Body = new Sequence { Activities = { new If(env => (elements.Get(env).ElementAt(index.Get(env))).GetType() == typeof(CompensationParticipant)) { Then = new Assign<bool> { To = assertFlag, Value = true }, }, new Assign<int> { To = index, Value = new InArgument<int>(env => index.Get(env) + 1) }, } } } } } }, new AssertValidation { Assertion = new InArgument<bool>(assertFlag), Message = new InArgument<string>(SR.CompensateWithNoTargetConstraint) } } } } }; } protected override void Execute(NativeActivityContext context) { CompensationExtension compensationExtension = context.GetExtension<CompensationExtension>(); if (compensationExtension == null) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompensateWithoutCompensableActivity(this.DisplayName))); } if (Target.IsEmpty) { CompensationToken ambientCompensationToken = (CompensationToken)context.Properties.Find(CompensationToken.PropertyName); CompensationTokenData ambientTokenData = ambientCompensationToken == null ? null : compensationExtension.Get(ambientCompensationToken.CompensationId); if (ambientTokenData != null && ambientTokenData.IsTokenValidInSecondaryRoot) { this.currentCompensationToken.Set(context, ambientCompensationToken); if (ambientTokenData.ExecutionTracker.Count > 0) { context.ScheduleActivity(DefaultCompensation); } } else { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidCompensateActivityUsage(this.DisplayName))); } } else { CompensationToken compensationToken = Target.Get(context); CompensationTokenData tokenData = compensationToken == null ? null : compensationExtension.Get(compensationToken.CompensationId); if (compensationToken == null) { throw FxTrace.Exception.Argument("Target", SR.InvalidCompensationToken(this.DisplayName)); } if (compensationToken.CompensateCalled) { // No-Op return; } if (tokenData == null || tokenData.CompensationState != CompensationState.Completed) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.CompensableActivityAlreadyConfirmedOrCompensated)); } // A valid in-arg was passed... tokenData.CompensationState = CompensationState.Compensating; compensationToken.CompensateCalled = true; context.ScheduleActivity(InternalCompensate); } } protected override void Cancel(NativeActivityContext context) { // Suppress Cancel } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using NUnit.Framework; using Boo.Lang.Compiler.Ast; namespace Boo.Lang.Parser.Tests { /// <summary> /// Test cases for the BooParser class. /// </summary> [TestFixture] public class BooParserTestCase : AbstractParserTestFixture { [Test] public void TestEndSourceLocationForInlineClosures() { const string code = @"foo = { a = 3; return a; }"; EnsureClosureEndSourceLocation(code, 2, 11); } [Test] public void TestEndSourceLocationForBlockClosures() { const string code = @" foo = def(): return a "; EnsureClosureEndSourceLocation(code, 3, 13); } void EnsureClosureEndSourceLocation(string code, int line, int column) { CompileUnit cu = BooParser.ParseString("closures", code); Expression e = ((ExpressionStatement)cu.Modules[0].Globals.Statements[0]).Expression; BlockExpression cbe = (BlockExpression)((BinaryExpression)e).Right; SourceLocation esl = cbe.Body.EndSourceLocation; Assert.AreEqual(line, esl.Line); Assert.AreEqual(column, esl.Column); } [Test] public void TestParseExpression() { const string code = @"3 + 2 * 5"; Expression e = BooParser.ParseExpression("test", code); Assert.AreEqual("3 + (2 * 5)", e.ToString()); } [Test] public void TestSimple() { string fname = GetTestCasePath("simple.boo"); CompileUnit cu = BooParser.ParseFile(fname); Assert.IsNotNull(cu); Boo.Lang.Compiler.Ast.Module module = cu.Modules[0]; Assert.IsNotNull(module); Assert.AreEqual("simple", module.Name); Assert.AreEqual("module doc string", module.Documentation); Assert.AreEqual("Empty.simple", module.FullName); Assert.AreEqual(fname, module.LexicalInfo.FileName); Assert.IsNotNull(module.Namespace); Assert.AreEqual("Empty", module.Namespace.Name); Assert.AreEqual(4, module.Namespace.LexicalInfo.Line); Assert.AreEqual(1, module.Namespace.LexicalInfo.Column); Assert.AreEqual(fname, module.Namespace.LexicalInfo.FileName); } [Test] public void TestSimpleClasses() { string fname = GetTestCasePath("simple_classes.boo"); Boo.Lang.Compiler.Ast.Module module = BooParser.ParseFile(fname).Modules[0]; Assert.AreEqual("Foo.Bar", module.Namespace.Name); Assert.IsNotNull(module.Members); Assert.AreEqual(2, module.Members.Count); TypeMember cd = module.Members[0]; Assert.IsTrue(cd is ClassDefinition); Assert.AreEqual("Customer", cd.Name); Assert.AreEqual("Foo.Bar.Customer", cd.FullName); Assert.AreSame(module.Namespace, cd.EnclosingNamespace); cd = module.Members[1]; Assert.AreEqual("Person", cd.Name); } [Test] public void TestSimpleClassMethods() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("simple_class_methods.boo"); Assert.AreEqual("ITL.Content", module.Namespace.Name); Assert.AreEqual(1, module.Imports.Count); Import i = module.Imports[0]; Assert.AreEqual("System", i.Namespace); Assert.AreEqual(3, i.LexicalInfo.Line); Assert.AreEqual(1, module.Members.Count); ClassDefinition cd = (ClassDefinition)module.Members[0]; Assert.AreEqual("Article", cd.Name); Assert.AreEqual(3, cd.Members.Count); Method m = (Method)cd.Members[0]; Assert.AreEqual("getTitle", m.Name); Assert.IsNotNull(m.ReturnType, "ReturnType"); Assert.AreEqual("string", ((SimpleTypeReference)m.ReturnType).Name); m = (Method)cd.Members[1]; Assert.AreEqual("getBody", m.Name); Assert.IsNotNull(m.ReturnType, "ReturnType"); Assert.AreEqual("string", ((SimpleTypeReference)m.ReturnType).Name); m = (Method)cd.Members[2]; Assert.AreEqual("getTag", m.Name); Assert.IsNull(m.ReturnType, "methods without a return type must have ReturnType set to null!"); } [Test] public void TestSimpleClassFields() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("simple_class_fields.boo"); Assert.AreEqual(1, module.Members.Count); ClassDefinition cd = (ClassDefinition)module.Members[0]; Assert.AreEqual(3, cd.Members.Count, "Members"); Field f = (Field)cd.Members[0]; Assert.AreEqual("_name", f.Name); Assert.IsNotNull(f.Type, "Field.Type"); Assert.AreEqual("string", ((SimpleTypeReference)f.Type).Name); Constructor c = (Constructor)cd.Members[1]; Assert.AreEqual("constructor", c.Name); Assert.IsNull(c.ReturnType); Assert.AreEqual(1, c.Parameters.Count, "Parameters.Count"); Assert.AreEqual("name", c.Parameters[0].Name); Assert.AreEqual("string", ((SimpleTypeReference)c.Parameters[0].Type).Name); Method m = (Method)cd.Members[2]; Assert.AreEqual("getName", m.Name); Assert.IsNull(m.ReturnType); Assert.AreEqual(0, m.Parameters.Count); Assert.IsNotNull(m.Body, "Body"); Assert.AreEqual(1, m.Body.Statements.Count); ReturnStatement rs = (ReturnStatement)m.Body.Statements[0]; ReferenceExpression i = (ReferenceExpression)rs.Expression; Assert.AreEqual("_name", i.Name); } [Test] public void TestSimpleGlobalDefs() { var module = ParseTestCase("simple_global_defs.boo"); Assert.AreEqual("Math", module.Namespace.Name); Assert.AreEqual(3, module.Members.Count); Assert.AreEqual("Rational", module.Members[0].Name); Assert.AreEqual("pi", module.Members[1].Name); Assert.AreEqual("rationalPI", module.Members[2].Name); Assert.AreEqual(0, module.Globals.Statements.Count); } [Test] public void StatementModifiersOnUnpackStatement() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_3.boo"); Block body = module.Globals; Assert.AreEqual(2, body.Statements.Count); UnpackStatement stmt = (UnpackStatement)body.Statements[0]; Assert.IsNotNull(stmt.Modifier, "Modifier"); Assert.AreEqual(StatementModifierType.If, stmt.Modifier.Type); Assert.IsTrue(stmt.Modifier.Condition is BoolLiteralExpression); Assert.AreEqual(true, ((BoolLiteralExpression)stmt.Modifier.Condition).Value); RunParserTestCase("stmt_modifiers_3.boo"); } [Test] public void TestStmtModifiers1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_1.boo"); Method m = (Method)module.Members[0]; ReturnStatement rs = (ReturnStatement)m.Body.Statements[0]; Assert.IsNotNull(rs.Modifier, "Modifier"); Assert.AreEqual(StatementModifierType.If, rs.Modifier.Type); BinaryExpression be = (BinaryExpression)rs.Modifier.Condition; Assert.AreEqual(BinaryOperatorType.LessThan, be.Operator); Assert.AreEqual("n", ((ReferenceExpression)be.Left).Name); Assert.AreEqual(2, ((IntegerLiteralExpression)be.Right).Value); } [Test] public void TestStmtModifiers2() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("stmt_modifiers_2.boo"); ExpressionStatement s = (ExpressionStatement)module.Globals.Statements[0]; BinaryExpression a = (BinaryExpression)s.Expression; Assert.AreEqual(BinaryOperatorType.Assign, a.Operator); Assert.AreEqual("f", ((ReferenceExpression)a.Left).Name); Assert.AreEqual(BinaryOperatorType.Division, ((BinaryExpression)a.Right).Operator); } [Test] public void TestStaticMethod() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("static_method.boo"); Assert.AreEqual(1, module.Members.Count); ClassDefinition cd = (ClassDefinition)module.Members[0]; Assert.AreEqual("Math", cd.Name); Assert.AreEqual(1, cd.Members.Count); Method m = (Method)cd.Members[0]; Assert.AreEqual(TypeMemberModifiers.Static, m.Modifiers); Assert.AreEqual("square", m.Name); Assert.AreEqual("int", ((SimpleTypeReference)m.ReturnType).Name); } [Test] public void TestClass2() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("class_2.boo"); ClassDefinition cd = (ClassDefinition)module.Members[0]; Assert.AreEqual(6, cd.Members.Count); for (int i=0; i<5; ++i) { Assert.AreEqual(TypeMemberModifiers.None, cd.Members[i].Modifiers); } Assert.AreEqual(TypeMemberModifiers.Public | TypeMemberModifiers.Static, cd.Members[5].Modifiers); } [Test] public void TestForStmt1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("for_stmt_1.boo"); ForStatement fs = (ForStatement)module.Globals.Statements[0]; Assert.AreEqual(1, fs.Declarations.Count); Declaration d = fs.Declarations[0]; Assert.AreEqual("i", d.Name); Assert.IsNull(d.Type); ListLiteralExpression lle = (ListLiteralExpression)fs.Iterator; Assert.AreEqual(3, lle.Items.Count); for (int i=0; i<3; ++i) { Assert.AreEqual(i+1, ((IntegerLiteralExpression)lle.Items[i]).Value); } Assert.AreEqual(1, fs.Block.Statements.Count); Assert.AreEqual("print", ((ReferenceExpression)((MethodInvocationExpression)((ExpressionStatement)fs.Block.Statements[0]).Expression).Target).Name); } [Test] public void TestRELiteral1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_1.boo"); Assert.AreEqual(2, module.Globals.Statements.Count); ExpressionStatement es = (ExpressionStatement)module.Globals.Statements[1]; Assert.AreEqual("print", ((ReferenceExpression)((MethodInvocationExpression)es.Expression).Target).Name); Assert.AreEqual(StatementModifierType.If, es.Modifier.Type); BinaryExpression be = (BinaryExpression)es.Modifier.Condition; Assert.AreEqual(BinaryOperatorType.Match, be.Operator); Assert.AreEqual("s", ((ReferenceExpression)be.Left).Name); Assert.AreEqual("/foo/", ((RELiteralExpression)be.Right).Value); } [Test] public void TestRELiteral2() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_2.boo"); StatementCollection stmts = module.Globals.Statements; Assert.AreEqual(2, stmts.Count); BinaryExpression ae = (BinaryExpression)((ExpressionStatement)stmts[0]).Expression; Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator); Assert.AreEqual("\"Bamboo\"\n", ((StringLiteralExpression)ae.Right).Value); ae = (BinaryExpression)((ExpressionStatement)stmts[1]).Expression; Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator); Assert.AreEqual("/foo\\(bar\\)/", ((RELiteralExpression)ae.Right).Value); } [Test] public void TestRELiteral3() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("re_literal_3.boo"); StatementCollection stmts = module.Globals.Statements; Assert.AreEqual(2, stmts.Count); BinaryExpression ae = (BinaryExpression)((ExpressionStatement)stmts[0]).Expression; Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator); Assert.AreEqual("/\\x2f\\u002f/", ((RELiteralExpression)ae.Right).Value); } [Test] public void TestIfElse1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("if_else_1.boo"); StatementCollection stmts = module.Globals.Statements; Assert.AreEqual(1, stmts.Count); IfStatement s = (IfStatement)stmts[0]; BinaryExpression be = (BinaryExpression)s.Condition; Assert.AreEqual(BinaryOperatorType.Match, be.Operator); Assert.AreEqual("gets", ((ReferenceExpression)((MethodInvocationExpression)be.Left).Target).Name); Assert.AreEqual("/foo/", ((RELiteralExpression)be.Right).Value); Assert.AreEqual(3, s.TrueBlock.Statements.Count); Assert.IsNull(s.FalseBlock); s = (IfStatement)s.TrueBlock.Statements[2]; be = (BinaryExpression)s.Condition; Assert.AreEqual("/bar/", ((RELiteralExpression)be.Right).Value); Assert.AreEqual(1, s.TrueBlock.Statements.Count); Assert.IsNotNull(s.FalseBlock); Assert.AreEqual(1, s.FalseBlock.Statements.Count); Assert.AreEqual("foobar, eh?", ((StringLiteralExpression)((MethodInvocationExpression)((ExpressionStatement)s.TrueBlock.Statements[0]).Expression).Arguments[0]).Value); Assert.AreEqual("nah?", ((StringLiteralExpression)((MethodInvocationExpression)((ExpressionStatement)s.FalseBlock.Statements[0]).Expression).Arguments[0]).Value); } [Test] public void TestInterface1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("interface_1.boo"); Assert.AreEqual(1, module.Members.Count); InterfaceDefinition id = (InterfaceDefinition)module.Members[0]; Assert.AreEqual("IContentItem", id.Name); Assert.AreEqual(5, id.Members.Count); Property p = (Property)id.Members[0]; Assert.AreEqual("Parent", p.Name); Assert.AreEqual("IContentItem", ((SimpleTypeReference)p.Type).Name); Assert.IsNotNull(p.Getter, "Getter"); Assert.IsNull(p.Setter, "Setter"); p = (Property)id.Members[1]; Assert.AreEqual("Name", p.Name); Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name); Assert.IsNotNull(p.Getter, "Getter"); Assert.IsNotNull(p.Setter, "Setter"); Method m = (Method)id.Members[2]; Assert.AreEqual("SelectItem", m.Name); Assert.AreEqual("IContentItem", ((SimpleTypeReference)m.ReturnType).Name); Assert.AreEqual("expression", m.Parameters[0].Name); Assert.AreEqual("string", ((SimpleTypeReference)m.Parameters[0].Type).Name); Assert.AreEqual("Validate", ((Method)id.Members[3]).Name); Assert.AreEqual("OnRemove", ((Method)id.Members[4]).Name); } [Test] public void TestEnum1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("enum_1.boo"); Assert.AreEqual(2, module.Members.Count); EnumDefinition ed = (EnumDefinition)module.Members[0]; Assert.AreEqual("Priority", ed.Name); Assert.AreEqual(3, ed.Members.Count); Assert.AreEqual("Low", ed.Members[0].Name); Assert.AreEqual("Normal", ed.Members[1].Name); Assert.AreEqual("High", ed.Members[2].Name); ed = (EnumDefinition)module.Members[1]; Assert.AreEqual(3, ed.Members.Count); Assert.AreEqual("Easy", ed.Members[0].Name); Assert.AreEqual(0, ((IntegerLiteralExpression)((EnumMember)ed.Members[0]).Initializer).Value); Assert.AreEqual("Normal", ed.Members[1].Name); Assert.AreEqual(5, ((IntegerLiteralExpression)((EnumMember)ed.Members[1]).Initializer).Value); Assert.AreEqual("Hard", ed.Members[2].Name); Assert.IsNull(((EnumMember)ed.Members[2]).Initializer, "Initializer"); } [Test] public void TestProperties1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("properties_1.boo"); ClassDefinition cd = (ClassDefinition)module.Members[0]; Assert.AreEqual("Person", cd.Name); Assert.AreEqual("_id", cd.Members[0].Name); Assert.AreEqual("_name", cd.Members[1].Name); Property p = (Property)cd.Members[3]; Assert.AreEqual("ID", p.Name); Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name); Assert.IsNotNull(p.Getter, "Getter"); Assert.AreEqual(1, p.Getter.Body.Statements.Count); Assert.AreEqual("_id", ((ReferenceExpression)((ReturnStatement)p.Getter.Body.Statements[0]).Expression).Name); Assert.IsNull(p.Setter, "Setter"); p = (Property)cd.Members[4]; Assert.AreEqual("Name", p.Name); Assert.AreEqual("string", ((SimpleTypeReference)p.Type).Name); Assert.IsNotNull(p.Getter, "Getter "); Assert.AreEqual(1, p.Getter.Body.Statements.Count); Assert.AreEqual("_name", ((ReferenceExpression)((ReturnStatement)p.Getter.Body.Statements[0]).Expression).Name); Assert.IsNotNull(p.Setter, "Setter"); Assert.AreEqual(1, p.Setter.Body.Statements.Count); BinaryExpression a = (BinaryExpression)((ExpressionStatement)p.Setter.Body.Statements[0]).Expression; Assert.AreEqual(BinaryOperatorType.Assign, a.Operator); Assert.AreEqual("_name", ((ReferenceExpression)a.Left).Name); Assert.AreEqual("value", ((ReferenceExpression)a.Right).Name); } [Test] public void TestWhileStmt1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("while_stmt_1.boo"); WhileStatement ws = (WhileStatement)module.Globals.Statements[3]; Assert.AreEqual(true, ((BoolLiteralExpression)ws.Condition).Value); Assert.AreEqual(4, ws.Block.Statements.Count); BreakStatement bs = (BreakStatement)ws.Block.Statements[3]; BinaryExpression condition = (BinaryExpression)bs.Modifier.Condition; Assert.AreEqual(BinaryOperatorType.Equality, condition.Operator); } [Test] public void TestUnpackStmt1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("unpack_stmt_1.boo"); UnpackStatement us = (UnpackStatement)module.Globals.Statements[0]; Assert.AreEqual(2, us.Declarations.Count); Assert.AreEqual("arg0", us.Declarations[0].Name); Assert.AreEqual("arg1", us.Declarations[1].Name); MethodInvocationExpression mce = (MethodInvocationExpression)us.Expression; MemberReferenceExpression mre = ((MemberReferenceExpression)mce.Target); Assert.AreEqual("GetCommandLineArgs", mre.Name); Assert.AreEqual("Environment", ((ReferenceExpression)mre.Target).Name); } [Test] public void TestYieldStmt1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("yield_stmt_1.boo"); Method m = (Method)module.Members[0]; ForStatement fs = (ForStatement)m.Body.Statements[0]; YieldStatement ys = (YieldStatement)fs.Block.Statements[0]; Assert.AreEqual("i", ((ReferenceExpression)ys.Expression).Name); Assert.AreEqual(StatementModifierType.If, ys.Modifier.Type); } [Test] public void TestNonSignificantWhitespaceRegions1() { Boo.Lang.Compiler.Ast.Module module = ParseTestCase("nonsignificant_ws_regions_1.boo"); StatementCollection stmts = module.Globals.Statements; Assert.AreEqual(2, stmts.Count); ExpressionStatement es = (ExpressionStatement)stmts[0]; BinaryExpression ae = (BinaryExpression)es.Expression; Assert.AreEqual(BinaryOperatorType.Assign, ae.Operator); Assert.AreEqual("a", ((ReferenceExpression)ae.Left).Name); Assert.AreEqual(2, ((ListLiteralExpression)ae.Right).Items.Count); ForStatement fs = (ForStatement)stmts[1]; MethodInvocationExpression mce = (MethodInvocationExpression)fs.Iterator; Assert.AreEqual("map", ((ReferenceExpression)mce.Target).Name); Assert.AreEqual(2, mce.Arguments.Count); Assert.AreEqual(1, fs.Block.Statements.Count); } [Test] public void Docstrings() { /* """ A module can have a docstring. """ namespace Foo.Bar """ And so can the namespace declaration. """ class Person: """ A class can have it. With multiple lines. """ _fname as string """Fields can have one.""" def constructor([required] fname as string): """ And so can a method or constructor. """ _fname = fname FirstName as string: """And why couldn't a property?""" get: return _fname interface ICustomer: """an interface.""" def Initialize() """interface method""" Name as string: """interface property""" get enum AnEnum: """and so can an enum""" AnItem """and its items""" AnotherItem */ Boo.Lang.Compiler.Ast.Module module = ParseTestCase("docstrings_1.boo"); Assert.AreEqual("A module can have a docstring.", module.Documentation); Assert.AreEqual("And so can the namespace declaration.", module.Namespace.Documentation); ClassDefinition person = (ClassDefinition)module.Members[0]; Assert.AreEqual("A class can have it.\nWith multiple lines.", person.Documentation); Assert.AreEqual("Fields can have one.", person.Members[0].Documentation); Assert.AreEqual("\tAnd so can a method or constructor.\n\t", person.Members[1].Documentation); Assert.AreEqual("And why couldn't a property?", person.Members[2].Documentation); InterfaceDefinition customer = (InterfaceDefinition)module.Members[1]; Assert.AreEqual("an interface.", customer.Documentation); Assert.AreEqual("interface method", customer.Members[0].Documentation); Assert.AreEqual("interface property", customer.Members[1].Documentation); EnumDefinition anEnum = (EnumDefinition)module.Members[2]; Assert.AreEqual("and so can an enum", anEnum.Documentation); Assert.AreEqual("and its items", anEnum.Members[0].Documentation); } } }
using System; using System.Collections.Generic; using System.Threading; using Svelto.DataStructures; namespace Svelto.ECS { /// <summary> /// This mechanism is not for thread-safety but to be sure that all the permutations of group tags always /// point to the same group ID. /// A group compound can generate several permutation of tags, so that the order of the tag doesn't matter, /// but for this to work, each permutation must be identified by the same ID (generated by the unique combination) /// </summary> static class GroupCompoundInitializer { internal static readonly ThreadLocal<bool> skipStaticCompoundConstructorsWith4Tags = new ThreadLocal<bool>(); internal static readonly ThreadLocal<bool> skipStaticCompoundConstructorsWith3Tags = new ThreadLocal<bool>(); internal static readonly ThreadLocal<bool> skipStaticCompoundConstructorsWith2Tags = new ThreadLocal<bool>(); } public abstract class GroupCompound<G1, G2, G3, G4> where G1 : GroupTag<G1> where G2 : GroupTag<G2> where G3 : GroupTag<G3> where G4 : GroupTag<G4> { static GroupCompound() { //avoid race conditions if compounds are using on multiple thread if (Interlocked.CompareExchange(ref isInitializing, 1, 0) == 0 && GroupCompoundInitializer.skipStaticCompoundConstructorsWith4Tags.Value == false) { var group = new ExclusiveGroup(); //todo: it's a bit of a waste to create a class here even if this is a static constructor _Groups = new FasterList<ExclusiveGroupStruct>(1); _Groups.Add(group); #if DEBUG var name = $"Compound: {typeof(G1).Name}-{typeof(G2).Name}-{typeof(G3).Name}-{typeof(G4).Name} ID {(uint) group.id}"; GroupNamesMap.idToName[group] = name; #endif //The hashname is independent from the actual group ID. this is fundamental because it is want //guarantees the hash to be the same across different machines GroupHashMap.RegisterGroup(group, typeof(GroupCompound<G1, G2, G3, G4>).FullName); _GroupsHashSet = new HashSet<ExclusiveGroupStruct>(_Groups.ToArrayFast(out _)); GroupCompoundInitializer.skipStaticCompoundConstructorsWith4Tags.Value = true; //all the permutations must share the same group and group hashset. Warm them up, avoid call the //constructors again, set the desired value GroupCompound<G1, G2, G4, G3>._Groups = _Groups; GroupCompound<G1, G3, G2, G4>._Groups = _Groups; GroupCompound<G1, G3, G4, G2>._Groups = _Groups; GroupCompound<G1, G4, G2, G3>._Groups = _Groups; GroupCompound<G2, G1, G3, G4>._Groups = _Groups; GroupCompound<G2, G3, G4, G1>._Groups = _Groups; GroupCompound<G3, G1, G2, G4>._Groups = _Groups; GroupCompound<G4, G1, G2, G3>._Groups = _Groups; GroupCompound<G1, G4, G3, G2>._Groups = _Groups; GroupCompound<G2, G1, G4, G3>._Groups = _Groups; GroupCompound<G2, G4, G3, G1>._Groups = _Groups; GroupCompound<G3, G1, G4, G2>._Groups = _Groups; GroupCompound<G4, G1, G3, G2>._Groups = _Groups; GroupCompound<G2, G3, G1, G4>._Groups = _Groups; GroupCompound<G3, G4, G1, G2>._Groups = _Groups; GroupCompound<G2, G4, G1, G3>._Groups = _Groups; GroupCompound<G3, G2, G1, G4>._Groups = _Groups; GroupCompound<G3, G2, G4, G1>._Groups = _Groups; GroupCompound<G3, G4, G2, G1>._Groups = _Groups; GroupCompound<G4, G2, G1, G3>._Groups = _Groups; GroupCompound<G4, G2, G3, G1>._Groups = _Groups; GroupCompound<G4, G3, G1, G2>._Groups = _Groups; GroupCompound<G4, G3, G2, G1>._Groups = _Groups; //all the permutations are warmed up now GroupCompoundInitializer.skipStaticCompoundConstructorsWith4Tags.Value = false; GroupCompound<G1, G2, G4, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G3, G2, G4>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G3, G4, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G4, G2, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G1, G3, G4>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G3, G4, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G1, G2, G4>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G1, G2, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G4, G3, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G1, G4, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G4, G3, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G1, G4, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G1, G3, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G3, G1, G4>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G4, G1, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G4, G1, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G2, G1, G4>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G2, G4, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G4, G2, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G2, G1, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G2, G3, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G3, G1, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G4, G3, G2, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G2, G3>.Add(group); GroupCompound<G1, G2, G4>.Add(group); GroupCompound<G1, G3, G4>.Add(group); GroupCompound<G2, G3, G4>.Add(group); GroupCompound<G1, G2>.Add(group); //<G1/G2> and <G2/G1> must share the same array GroupCompound<G1, G3>.Add(group); GroupCompound<G1, G4>.Add(group); GroupCompound<G2, G3>.Add(group); GroupCompound<G2, G4>.Add(group); GroupCompound<G3, G4>.Add(group); //This is done here to be sure that the group is added once per group tag //(if done inside the previous group compound it would be added multiple times) GroupTag<G1>.Add(group); GroupTag<G2>.Add(group); GroupTag<G3>.Add(group); GroupTag<G4>.Add(group); } } public static FasterReadOnlyList<ExclusiveGroupStruct> Groups => new FasterReadOnlyList<ExclusiveGroupStruct>(_Groups); public static ExclusiveBuildGroup BuildGroup => new ExclusiveBuildGroup(_Groups[0]); public static bool Includes(ExclusiveGroupStruct group) { return _GroupsHashSet.Contains(group); } internal static void Add(ExclusiveGroupStruct group) { #if DEBUG && !PROFILE_SVELTO for (var i = 0; i < _Groups.count; ++i) if (_Groups[i] == group) throw new Exception("this test must be transformed in unit test"); #endif _Groups.Add(group); _GroupsHashSet.Add(group); } static readonly FasterList<ExclusiveGroupStruct> _Groups; static readonly HashSet<ExclusiveGroupStruct> _GroupsHashSet; //we are changing this with Interlocked, so it cannot be readonly static int isInitializing; } public abstract class GroupCompound<G1, G2, G3> where G1 : GroupTag<G1> where G2 : GroupTag<G2> where G3 : GroupTag<G3> { static GroupCompound() { if (Interlocked.CompareExchange(ref isInitializing, 1, 0) == 0 && GroupCompoundInitializer.skipStaticCompoundConstructorsWith3Tags.Value == false) { var group = new ExclusiveGroup(); //todo: it's a bit of a waste to create a class here even if this is a static constructor _Groups = new FasterList<ExclusiveGroupStruct>(1); _Groups.Add(group); #if DEBUG var name = $"Compound: {typeof(G1).Name}-{typeof(G2).Name}-{typeof(G3).Name} ID {(uint) group.id}"; GroupNamesMap.idToName[group] = name; #endif //The hashname is independent from the actual group ID. this is fundamental because it is want //guarantees the hash to be the same across different machines GroupHashMap.RegisterGroup(group, typeof(GroupCompound<G1, G2, G3>).FullName); _GroupsHashSet = new HashSet<ExclusiveGroupStruct>(_Groups.ToArrayFast(out _)); GroupCompoundInitializer.skipStaticCompoundConstructorsWith3Tags.Value = true; //all the combinations must share the same group and group hashset GroupCompound<G3, G1, G2>._Groups = _Groups; GroupCompound<G2, G3, G1>._Groups = _Groups; GroupCompound<G3, G2, G1>._Groups = _Groups; GroupCompound<G1, G3, G2>._Groups = _Groups; GroupCompound<G2, G1, G3>._Groups = _Groups; //all the constructor have been called now GroupCompoundInitializer.skipStaticCompoundConstructorsWith3Tags.Value = false; GroupCompound<G3, G1, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G3, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G3, G2, G1>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G3, G2>._GroupsHashSet = _GroupsHashSet; GroupCompound<G2, G1, G3>._GroupsHashSet = _GroupsHashSet; GroupCompound<G1, G2>.Add(group); //<G1/G2> and <G2/G1> must share the same array GroupCompound<G1, G3>.Add(group); GroupCompound<G2, G3>.Add(group); //This is done here to be sure that the group is added once per group tag //(if done inside the previous group compound it would be added multiple times) GroupTag<G1>.Add(group); GroupTag<G2>.Add(group); GroupTag<G3>.Add(group); } } public static FasterReadOnlyList<ExclusiveGroupStruct> Groups => new FasterReadOnlyList<ExclusiveGroupStruct>(_Groups); public static ExclusiveBuildGroup BuildGroup => new ExclusiveBuildGroup(_Groups[0]); public static bool Includes(ExclusiveGroupStruct group) { return _GroupsHashSet.Contains(group); } internal static void Add(ExclusiveGroupStruct group) { #if DEBUG && !PROFILE_SVELTO for (var i = 0; i < _Groups.count; ++i) if (_Groups[i] == group) throw new Exception("this test must be transformed in unit test"); #endif _Groups.Add(group); _GroupsHashSet.Add(group); } static readonly FasterList<ExclusiveGroupStruct> _Groups; static readonly HashSet<ExclusiveGroupStruct> _GroupsHashSet; //we are changing this with Interlocked, so it cannot be readonly static int isInitializing; } public abstract class GroupCompound<G1, G2> where G1 : GroupTag<G1> where G2 : GroupTag<G2> { static GroupCompound() { if (Interlocked.CompareExchange(ref isInitializing, 1, 0) == 0 && GroupCompoundInitializer.skipStaticCompoundConstructorsWith2Tags.Value == false) { var group = new ExclusiveGroup(); //todo: it's a bit of a waste to create a class here even if this is a static constructor _Groups = new FasterList<ExclusiveGroupStruct>(1); _Groups.Add(group); #if DEBUG GroupNamesMap.idToName[group] = $"Compound: {typeof(G1).Name}-{typeof(G2).Name} ID {group.id}"; #endif //The hashname is independent from the actual group ID. this is fundamental because it is want //guarantees the hash to be the same across different machines GroupHashMap.RegisterGroup(group, typeof(GroupCompound<G1, G2>).FullName); _GroupsHashSet = new HashSet<ExclusiveGroupStruct>(_Groups.ToArrayFast(out _)); GroupCompoundInitializer.skipStaticCompoundConstructorsWith2Tags.Value = true; GroupCompound<G2, G1>._Groups = _Groups; GroupCompoundInitializer.skipStaticCompoundConstructorsWith2Tags.Value = false; GroupCompound<G2, G1>._GroupsHashSet = _GroupsHashSet; //every abstract group preemptively adds this group, it may or may not be empty in future GroupTag<G1>.Add(group); GroupTag<G2>.Add(group); } } public static FasterReadOnlyList<ExclusiveGroupStruct> Groups => new FasterReadOnlyList<ExclusiveGroupStruct>(_Groups); public static ExclusiveBuildGroup BuildGroup => new ExclusiveBuildGroup(_Groups[0]); public static bool Includes(ExclusiveGroupStruct group) { return _GroupsHashSet.Contains(group); } internal static void Add(ExclusiveGroupStruct group) { #if DEBUG && !PROFILE_SVELTO for (var i = 0; i < _Groups.count; ++i) if (_Groups[i] == group) throw new Exception("this test must be transformed in unit test"); #endif _Groups.Add(group); _GroupsHashSet.Add(group); } static readonly FasterList<ExclusiveGroupStruct> _Groups; static readonly HashSet<ExclusiveGroupStruct> _GroupsHashSet; static int isInitializing; } /// <summary> /// A Group Tag holds initially just a group, itself. However the number of groups can grow with the number of /// combinations of GroupTags including this one. This because a GroupTag is an adjective and different entities /// can use the same adjective together with other ones. However since I need to be able to iterate over all the /// groups with the same adjective, a group tag needs to hold all the groups sharing it. /// </summary> /// <typeparam name="T"></typeparam> public abstract class GroupTag<T> where T : GroupTag<T> { static GroupTag() { if (Interlocked.CompareExchange(ref isInitializing, 1, 0) == 0) { var group = new ExclusiveGroup(); _Groups.Add(group); #if DEBUG var typeInfo = typeof(T); var name = $"Compound: {typeInfo.Name} ID {(uint) group.id}"; var typeInfoBaseType = typeInfo.BaseType; if (typeInfoBaseType.GenericTypeArguments[0] != typeInfo) //todo: this should shield from using a pattern different than public class GROUP_NAME : GroupTag<GROUP_NAME> {} however I am not sure it's working throw new ECSException("Invalid Group Tag declared"); GroupNamesMap.idToName[group] = name; #endif //The hashname is independent from the actual group ID. this is fundamental because it is want //guarantees the hash to be the same across different machines GroupHashMap.RegisterGroup(group, typeof(GroupTag<T>).FullName); _GroupsHashSet = new HashSet<ExclusiveGroupStruct>(_Groups.ToArrayFast(out _)); } } public static FasterReadOnlyList<ExclusiveGroupStruct> Groups => new FasterReadOnlyList<ExclusiveGroupStruct>(_Groups); public static ExclusiveBuildGroup BuildGroup => new ExclusiveBuildGroup(_Groups[0]); public static bool Includes(ExclusiveGroupStruct group) { return _GroupsHashSet.Contains(group); } //Each time a new combination of group tags is found a new group is added. internal static void Add(ExclusiveGroupStruct group) { #if DEBUG && !PROFILE_SVELTO for (var i = 0; i < _Groups.count; ++i) if (_Groups[i] == group) throw new Exception("this test must be transformed in unit test"); #endif _Groups.Add(group); _GroupsHashSet.Add(group); } static readonly FasterList<ExclusiveGroupStruct> _Groups = new FasterList<ExclusiveGroupStruct>(1); static readonly HashSet<ExclusiveGroupStruct> _GroupsHashSet; //we are changing this with Interlocked, so it cannot be readonly static int isInitializing; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; namespace Mercurial { /// <summary> /// This class handles executing external executables in order to process /// commands. /// </summary> public static class CommandProcessor { /// <summary> /// This field is used to specify the encoding of input/output streams for processes. /// </summary> private static readonly Encoding _Encoding = ClientExecutable.TextEncoding; /// <summary> /// Executes the given executable to process the given command asynchronously. /// </summary> /// <param name="workingDirectory"> /// The working directory while executing the command. /// </param> /// <param name="executable"> /// The full path to and name of the executable to execute. /// </param> /// <param name="command"> /// The options to the executable. /// </param> /// <param name="environmentVariables"> /// An array of <see cref="KeyValuePair{TKey,TValue}"/> objects, containing environment variable /// overrides to use while executing the executable. /// </param> /// <param name="specialArguments"> /// Any special arguments to pass to the executable, not defined by the <paramref name="command"/> /// object, typically common arguments that should always be passed to the executable. /// </param> /// <param name="callback"> /// A callback to call when the execution has completed. The <see cref="IAsyncResult.AsyncState"/> value of the /// <see cref="IAsyncResult"/> object passed to the <paramref name="callback"/> will be the /// <paramref name="command"/> object. /// </param> /// <returns> /// Returns a <see cref="IAsyncResult"/> object that should be passed to <see cref="EndExecute"/> when /// execution has completed. /// </returns> /// <exception cref="ArgumentNullException"> /// <para><paramref name="workingDirectory"/> is <c>null</c> or empty.</para> /// <para>- or -</para> /// <para><paramref name="executable"/> is <c>null</c> or empty.</para> /// <para>- or -</para> /// <para><paramref name="command"/> is <c>null</c>.</para> /// <para>- or -</para> /// <para><paramref name="environmentVariables"/> is <c>null</c>.</para> /// <para>- or -</para> /// <para><paramref name="specialArguments"/> is <c>null</c>.</para> /// </exception> public static IAsyncResult BeginExecute( string workingDirectory, string executable, ICommand command, KeyValuePair<string, string>[] environmentVariables, IEnumerable<string> specialArguments, AsyncCallback callback) { return new ExecuteDelegate(Execute).BeginInvoke( workingDirectory, executable, command, environmentVariables, specialArguments, callback, command); } /// <summary> /// Finalizes asynchronous execution of the command. /// </summary> /// <param name="result"> /// The <see cref="IAsyncResult"/> object returned from <see cref="BeginExecute"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="result"/> is <c>null</c>.</para> /// </exception> /// <exception cref="ArgumentException"> /// <para><paramref name="result"/> is not a <see cref="IAsyncResult"/> that was returned from <see cref="BeginExecute"/>.</para> /// </exception> public static void EndExecute(IAsyncResult result) { if (result == null) throw new ArgumentNullException("result"); var asyncResult = result as AsyncResult; if (asyncResult == null) throw new ArgumentException("invalid IAsyncResult object passed to CommandProcessor.EndExecute", "result"); var executeDelegate = asyncResult.AsyncDelegate as ExecuteDelegate; if (executeDelegate == null) throw new ArgumentException("invalid IAsyncResult object passed to CommandProcessor.EndExecute", "result"); executeDelegate.EndInvoke(result); } /// <summary> /// Executes the given executable to process the given command. /// </summary> /// <param name="workingDirectory"> /// The working directory while executing the command. /// </param> /// <param name="executable"> /// The full path to and name of the executable to execute. /// </param> /// <param name="command"> /// The options to the executable. /// </param> /// <param name="environmentVariables"> /// An array of <see cref="KeyValuePair{TKey,TValue}"/> objects, containing environment variable /// overrides to use while executing the executable. /// </param> /// <param name="specialArguments"> /// Any special arguments to pass to the executable, not defined by the <paramref name="command"/> /// object, typically common arguments that should always be passed to the executable. /// </param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="workingDirectory"/> is <c>null</c> or empty.</para> /// <para>- or -</para> /// <para><paramref name="executable"/> is <c>null</c> or empty.</para> /// <para>- or -</para> /// <para><paramref name="command"/> is <c>null</c>.</para> /// <para>- or -</para> /// <para><paramref name="environmentVariables"/> is <c>null</c>.</para> /// <para>- or -</para> /// <para><paramref name="specialArguments"/> is <c>null</c>.</para> /// </exception> /// <exception cref="MercurialException"> /// <para>The executable did not finish in the allotted time.</para> /// </exception> public static void Execute( string workingDirectory, string executable, ICommand command, KeyValuePair<string, string>[] environmentVariables, IEnumerable<string> specialArguments) { if (StringEx.IsNullOrWhiteSpace(workingDirectory)) throw new ArgumentNullException("workingDirectory"); if (StringEx.IsNullOrWhiteSpace(executable)) throw new ArgumentNullException("executable"); if (command == null) throw new ArgumentNullException("command"); if (environmentVariables == null) throw new ArgumentNullException("environmentVariables"); if (specialArguments == null) throw new ArgumentNullException("specialArguments"); command.Validate(); command.Before(); IEnumerable<string> arguments = specialArguments; arguments = arguments.Concat(command.Arguments.Where(a => !StringEx.IsNullOrWhiteSpace(a))); arguments = arguments.Concat(command.AdditionalArguments.Where(a => !StringEx.IsNullOrWhiteSpace(a))); string argumentsString = string.Join(" ", arguments.ToArray()); var psi = new ProcessStartInfo { FileName = executable, WorkingDirectory = workingDirectory, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, ErrorDialog = false, Arguments = command.Command + " " + argumentsString, }; foreach (var kvp in environmentVariables) psi.EnvironmentVariables[kvp.Key] = kvp.Value; psi.StandardErrorEncoding = _Encoding; psi.StandardOutputEncoding = _Encoding; if (command.Observer != null) command.Observer.Executing(command.Command, argumentsString); using (Process process = Process.Start(psi)) { Func<StreamReader, Action<string>, string> reader; if (command.Observer != null) { reader = delegate(StreamReader streamReader, Action<string> logToObserver) { var output = new StringBuilder(); string line; while ((line = streamReader.ReadLine()) != null) { logToObserver(line); if (output.Length > 0) output.Append(Environment.NewLine); output.Append(line); } return output.ToString(); }; } else reader = (StreamReader streamReader, Action<string> logToObserver) => streamReader.ReadToEnd(); IAsyncResult outputReader = reader.BeginInvoke(process.StandardOutput, line => command.Observer.Output(line), null, null); IAsyncResult errorReader = reader.BeginInvoke(process.StandardError, line => command.Observer.ErrorOutput(line), null, null); int timeout = Timeout.Infinite; if (command.Timeout > 0) timeout = 1000 * command.Timeout; if (!process.WaitForExit(timeout)) { if (command.Observer != null) command.Observer.Executed(psi.FileName, psi.Arguments, 0, string.Empty, string.Empty); throw new MercurialException("The executable did not complete within the allotted time"); } string standardOutput = reader.EndInvoke(outputReader); string errorOutput = reader.EndInvoke(errorReader); if (command.Observer != null) command.Observer.Executed(command.Command, argumentsString, process.ExitCode, standardOutput, errorOutput); command.After(process.ExitCode, standardOutput, errorOutput); } } #region Nested type: ExecuteDelegate /// <summary> /// A delegate that matches <see cref="Execute"/>. /// </summary> /// <param name="workingDirectory"> /// The working directory while executing the command. /// </param> /// <param name="executable"> /// The full path to and name of the executable to execute. /// </param> /// <param name="command"> /// The options to the executable. /// </param> /// <param name="environmentVariables"> /// An array of <see cref="KeyValuePair{TKey,TValue}"/> objects, containing environment variable /// overrides to use while executing the executable. /// </param> /// <param name="specialArguments"> /// Any special arguments to pass to the executable, not defined by the <paramref name="command"/> /// object, typically common arguments that should always be passed to the executable. /// </param> private delegate void ExecuteDelegate( string workingDirectory, string executable, ICommand command, KeyValuePair<string, string>[] environmentVariables, IEnumerable<string> specialArguments); #endregion } }
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 Mashup.UI.ExampleData.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Input; using log4net; using Tailviewer.Api; using Tailviewer.BusinessLogic.ActionCenter; using Tailviewer.BusinessLogic.Bookmarks; using Tailviewer.BusinessLogic.DataSources; using Tailviewer.BusinessLogic.Filters; using Tailviewer.BusinessLogic.Highlighters; using Tailviewer.Collections; using Tailviewer.Settings; using Tailviewer.Ui.DataSourceTree; using Tailviewer.Ui.GoToLine; using Tailviewer.Ui.QuickFilter; using Tailviewer.Ui.QuickNavigation; using Tailviewer.Ui.SidePanel; using Tailviewer.Ui.SidePanel.Bookmarks; using Tailviewer.Ui.SidePanel.DataSources; using Tailviewer.Ui.SidePanel.Highlighters; using Tailviewer.Ui.SidePanel.Issues; using Tailviewer.Ui.SidePanel.Outline; using Tailviewer.Ui.SidePanel.Property; using Tailviewer.Ui.SidePanel.QuickFilters; namespace Tailviewer.Ui.LogView { /// <summary> /// The view model governing the main panel which shows the current data source, data source tree, /// various side panels, etc.. /// </summary> public sealed class LogViewMainPanelViewModel : AbstractMainPanelViewModel , ILogViewMainPanelViewModel { private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly ISidePanelViewModel[] _sidePanels; private readonly BookmarksViewModel _bookmarks; private readonly PropertiesSidePanelViewModel _properties; private readonly OutlineSidePanelViewModel _outline; private readonly IssuesSidePanelViewModel _issues; private readonly DataSourcesViewModel _dataSources; private readonly QuickFiltersSidePanelViewModel _quickFilters; private HighlightersSidePanelViewModel _highlighters; private readonly IActionCenter _actionCenter; private readonly IApplicationSettings _applicationSettings; private readonly GoToLineViewModel _goToLine; private readonly QuickNavigationViewModel _quickNavigation; private LogViewerViewModel _currentDataSourceLogView; private string _windowTitle; private string _windowTitleSuffix; private bool _showQuickNavigation; private ISidePanelViewModel _selectedSidePanel; public LogViewMainPanelViewModel(IServiceContainer services, IActionCenter actionCenter, IDataSources dataSources, IQuickFilters quickFilters, IHighlighters highlighters, IApplicationSettings applicationSettings) { _applicationSettings = applicationSettings; _actionCenter = actionCenter ?? throw new ArgumentNullException(nameof(actionCenter)); _dataSources = new DataSourcesViewModel(applicationSettings, dataSources, _actionCenter); _dataSources.PropertyChanged += DataSourcesOnPropertyChanged; _quickFilters = new QuickFiltersSidePanelViewModel(applicationSettings, quickFilters); _quickFilters.OnFiltersChanged += OnFiltersChanged; _highlighters = new HighlightersSidePanelViewModel(highlighters); _goToLine = new GoToLineViewModel(); _goToLine.LineNumberChosen += GoToLineOnLineNumberChosen; _quickNavigation = new QuickNavigationViewModel(dataSources); _quickNavigation.DataSourceChosen += QuickNavigationOnDataSourceChosen; _bookmarks = new BookmarksViewModel(dataSources, OnNavigateToBookmark); _properties = new PropertiesSidePanelViewModel(services); _outline = new OutlineSidePanelViewModel(services); _issues = new IssuesSidePanelViewModel(services); _sidePanels = new ISidePanelViewModel[] { _quickFilters, //_highlighters, _bookmarks, _properties, _outline, _issues }; SelectedSidePanel = _sidePanels.FirstOrDefault(x => x.Id == _applicationSettings.MainWindow?.SelectedSidePanel); PropertyChanged += OnPropertyChanged; ChangeDataSource(CurrentDataSource); } public void GetOrAddFile(string fileName) { CurrentDataSource = _dataSources.GetOrAddFile(fileName); } public void GetOrAddFolder(string folder) { CurrentDataSource = _dataSources.GetOrAddFolder(folder); } private void GoToLineOnLineNumberChosen(LogLineIndex logLineIndex) { Log.DebugFormat("Going to line {0}", logLineIndex); var dataSourceViewModel = _currentDataSourceLogView.DataSource; var dataSource = dataSourceViewModel.DataSource; var logFile = dataSource.FilteredLogSource; var originalIndex = logFile.GetLogLineIndexOfOriginalLineIndex(logLineIndex); dataSourceViewModel.SelectedLogLines = new HashSet<LogLineIndex> { originalIndex }; dataSourceViewModel.RequestBringIntoView(originalIndex); } private void QuickNavigationOnDataSourceChosen(IDataSource dataSource) { var viewModel = _dataSources.DataSources.FirstOrDefault(x => x.DataSource == dataSource); if (viewModel != null) { Log.DebugFormat("Navigating to '{0}'", viewModel); _dataSources.SelectedItem = viewModel; } else { Log.WarnFormat("Unable to navigate to data source '{0}': Can't find it!", dataSource); } } private void OnFiltersChanged() { var source = CurrentDataSource; if (source != null) source.QuickFilterChain = _quickFilters.CreateFilterChain(); } public bool CanBeDragged(IDataSourceViewModel source) { return _dataSources.CanBeDragged(source); } public bool CanBeDropped(IDataSourceViewModel source, IDataSourceViewModel dest, DataSourceDropType dropType, out IDataSourceViewModel finalDest) { return _dataSources.CanBeDropped(source, dest, dropType, out finalDest); } public void OnDropped(IDataSourceViewModel source, IDataSourceViewModel dest, DataSourceDropType dropType) { _dataSources.OnDropped(source, dest, dropType); } private void DataSourcesOnPropertyChanged(object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case nameof(DataSourcesViewModel.SelectedItem): ChangeDataSource(_dataSources.SelectedItem); EmitPropertyChanged(nameof(CurrentDataSource)); break; } } private void ChangeDataSource(IDataSourceViewModel value) { if (value != null) value.QuickFilterChain = _quickFilters.CreateFilterChain(); _dataSources.SelectedItem = value; _quickFilters.CurrentDataSource = value; _bookmarks.CurrentDataSource = value?.DataSource; _properties.CurrentDataSource = value?.DataSource; _outline.CurrentDataSource = value?.DataSource; _issues.CurrentDataSource = value?.DataSource; Search = value?.Search; FindAll = value?.FindAll; OpenFile(value); } private void OnNavigateToBookmark(Bookmark bookmark) { var dataSourceViewModel = _dataSources.DataSources.FirstOrDefault(x => x.DataSource == bookmark.DataSource); if (dataSourceViewModel != null) { CurrentDataSource = dataSourceViewModel; var index = bookmark.Index; var logFile = dataSourceViewModel.DataSource.FilteredLogSource; if (logFile != null) { var actualIndex = logFile.GetLogLineIndexOfOriginalLineIndex(index); if (actualIndex == LogLineIndex.Invalid) { Log.WarnFormat("Unable to find index '{0}' of {1}", index, dataSourceViewModel); return; } index = actualIndex; } dataSourceViewModel.SelectedLogLines = new HashSet<LogLineIndex> { index }; dataSourceViewModel.RequestBringIntoView(index); } } public bool RequestBringIntoView(LogLineIndex index) { return RequestBringIntoView(CurrentDataSource, index); } public bool RequestBringIntoView(DataSourceId dataSource, LogLineIndex index) { var dataSourceViewModel = _dataSources.DataSources.FirstOrDefault(x => x.DataSource.Id == dataSource); return RequestBringIntoView(dataSourceViewModel, index); } private static bool RequestBringIntoView(IDataSourceViewModel dataSourceViewModel, LogLineIndex index) { if (dataSourceViewModel == null) return false; var logFile = dataSourceViewModel.DataSource.FilteredLogSource; if (logFile != null) { var actualIndex = logFile.GetLogLineIndexOfOriginalLineIndex(index); if (actualIndex == LogLineIndex.Invalid) { Log.WarnFormat("Unable to find index '{0}' of {1}", index, dataSourceViewModel); return false; } index = actualIndex; } dataSourceViewModel.SelectedLogLines = new HashSet<LogLineIndex> {index}; dataSourceViewModel.RequestBringIntoView(index); return true; } public DataSourcesViewModel DataSources => _dataSources; public GoToLineViewModel GoToLine => _goToLine; public QuickNavigationViewModel QuickNavigation => _quickNavigation; public bool ShowQuickNavigation { get { return _showQuickNavigation; } set { if (value == _showQuickNavigation) return; _showQuickNavigation = value; EmitPropertyChanged(); if (!value) { _quickNavigation.SearchTerm = null; } } } public string WindowTitle { get { return _windowTitle; } set { if (value == _windowTitle) return; _windowTitle = value; EmitPropertyChanged(); } } public string WindowTitleSuffix { get { return _windowTitleSuffix; } set { if (value == _windowTitleSuffix) return; _windowTitleSuffix = value; EmitPropertyChanged(); } } public IDataSourceViewModel CurrentDataSource { get { return _dataSources.SelectedItem; } set { var old = _dataSources.SelectedItem; _dataSources.SelectedItem = value; if (old != null) { old.PropertyChanged -= CurrentDataSourceOnPropertyChanged; } if (value != null) { value.PropertyChanged += CurrentDataSourceOnPropertyChanged; } if (old != value) EmitPropertyChanged(); UpdateWindowTitle(value); } } private void CurrentDataSourceOnPropertyChanged(object sender, PropertyChangedEventArgs e) { UpdateWindowTitle(CurrentDataSource); } private void UpdateWindowTitle(IDataSourceViewModel value) { if (value != null) { WindowTitle = string.Format("{0} - {1}", Constants.MainWindowTitle, value.DisplayName); var child = value as ISingleDataSourceViewModel; var parentId = value.DataSource.ParentId; var parent = _dataSources.TryGet(parentId); if (child != null && parent != null) { WindowTitleSuffix = string.Format("{0} -> [{1}] {2}", parent.DisplayName, child.CharacterCode, child.DataSourceOrigin); } else { WindowTitleSuffix = value.DataSourceOrigin; } } else { WindowTitle = Constants.MainWindowTitle; WindowTitleSuffix = null; } } public IDataSourceViewModel GetOrAddPath(string path) { IDataSourceViewModel dataSource; if (Directory.Exists(path)) { dataSource = _dataSources.GetOrAddFolder(path); } else { dataSource = _dataSources.GetOrAddFile(path); } OpenFile(dataSource); return dataSource; } private void OnPropertyChanged(object sender, PropertyChangedEventArgs args) { switch (args.PropertyName) { case nameof(CurrentDataSource): OpenFile(CurrentDataSource); break; } } private void OpenFile(IDataSourceViewModel dataSource) { if (CurrentDataSourceLogView?.DataSource == dataSource) return; if (dataSource != null) { CurrentDataSource = dataSource; CurrentDataSourceLogView = new LogViewerViewModel( dataSource, _actionCenter, _applicationSettings); } else { CurrentDataSource = null; CurrentDataSourceLogView = null; } } public LogViewerViewModel CurrentDataSourceLogView { get { return _currentDataSourceLogView; } set { if (_currentDataSourceLogView == value) return; _currentDataSourceLogView = value; EmitPropertyChanged(); } } public IEnumerable<ISidePanelViewModel> SidePanels => _sidePanels; public ISidePanelViewModel SelectedSidePanel { get { return _selectedSidePanel; } set { if (value == _selectedSidePanel) return; _selectedSidePanel = value; EmitPropertyChanged(); _applicationSettings.MainWindow.SelectedSidePanel = value?.Id; _applicationSettings.SaveAsync(); } } public IEnumerable<IDataSourceViewModel> RecentFiles => _dataSources.Observable; public ILogViewerSettings Settings => _applicationSettings.LogViewer; public ICommand AddBookmarkCommand => _bookmarks.AddBookmarkCommand; public ICommand RemoveAllBookmarkCommand => _bookmarks.RemoveAllBookmarksCommand; public override void Update() { CurrentDataSourceLogView?.Update(); _dataSources.Update(); _properties.Update(); _bookmarks.Update(); _outline.Update(); _issues.Update(); } public QuickFilterViewModel AddQuickFilter() { return _quickFilters.AddQuickFilter(); } public void ShowQuickFilters() { SelectedSidePanel = _quickFilters; } public bool AddBookmark() { if (!_bookmarks.AddBookmarkCommand.CanExecute(null)) return false; _bookmarks.AddBookmarkCommand.Execute(null); return true; } public void ShowBookmarks() { SelectedSidePanel = _bookmarks; } public void GoToPreviousDataSource() { var dataSources = _dataSources.DataSources; if (dataSources.Count == 0) return; var idx = dataSources.IndexOf(_dataSources.SelectedItem); if (idx == -1) return; var nextIndex = idx - 1; if (nextIndex < 0) nextIndex = dataSources.Count - 1; var next = dataSources[nextIndex]; _dataSources.SelectedItem = next; } public void GoToNextDataSource() { var dataSources = _dataSources.DataSources; if (dataSources.Count == 0) return; var idx = dataSources.IndexOf(_dataSources.SelectedItem); if (idx == -1) return; var nextIndex = idx + 1; if (nextIndex >= dataSources.Count) nextIndex = 0; var next = dataSources[nextIndex]; _dataSources.SelectedItem = next; } } }
// 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.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable { private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance(); internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty; protected ExpressionCompilerTestBase() { // We never want to swallow Exceptions (generate a non-fatal Watson) when running tests. ExpressionEvaluatorFatalError.IsFailFastEnabled = true; } public override void Dispose() { base.Dispose(); foreach (var instance in _runtimeInstances) { instance.Dispose(); } _runtimeInstances.Free(); } // TODO: remove -- workaround for bugs in Portable PDB handling in EE internal static void WithRuntimeInstancePortableBug(Compilation compilation, Action<RuntimeInstance> validator) { WithRuntimeInstancePortableBug(compilation, null, validator); } // TODO: remove -- workaround for bugs in Portable PDB handling in EE internal static void WithRuntimeInstancePortableBug(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator) { using (var instance = RuntimeInstance.Create(compilation, references, DebugInformationFormat.Pdb, true)) { validator(instance); } } internal static void WithRuntimeInstance(Compilation compilation, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, null, true, validator); } internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, references, true, validator); } internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, bool includeLocalSignatures, Action<RuntimeInstance> validator) { foreach (var debugFormat in new[] { DebugInformationFormat.Pdb, DebugInformationFormat.PortablePdb }) { using (var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures)) { validator(instance); } } } internal RuntimeInstance CreateRuntimeInstance(IEnumerable<ModuleInstance> modules) { var instance = RuntimeInstance.Create(modules); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( Compilation compilation, IEnumerable<MetadataReference> references = null, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( ModuleInstance module, IEnumerable<MetadataReference> references) { var instance = RuntimeInstance.Create(module, references); _runtimeInstances.Add(instance); return instance; } internal static void GetContextState( RuntimeInstance runtime, string methodOrTypeName, out ImmutableArray<MetadataBlock> blocks, out Guid moduleVersionId, out ISymUnmanagedReader symReader, out int methodOrTypeToken, out int localSignatureToken) { var moduleInstances = runtime.Modules; blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock); var compilation = blocks.ToCompilation(); var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName); var module = (PEModuleSymbol)methodOrType.ContainingModule; var id = module.Module.GetModuleVersionIdOrThrow(); var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id); moduleVersionId = id; symReader = (ISymUnmanagedReader)moduleInstance.SymReader; EntityHandle methodOrTypeHandle; if (methodOrType.Kind == SymbolKind.Method) { methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle; localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle); } else { methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle; localSignatureToken = -1; } MetadataReader reader = null; // null should be ok methodOrTypeToken = reader.GetToken(methodOrTypeHandle); } internal static EvaluationContext CreateMethodContext( RuntimeInstance runtime, string methodName, int atLineNumber = -1) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber); return EvaluationContext.CreateMethodContext( default(CSharpMetadataContext), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); } internal static EvaluationContext CreateTypeContext( RuntimeInstance runtime, string typeName) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); return EvaluationContext.CreateTypeContext( default(CSharpMetadataContext), blocks, moduleVersionId, typeToken); } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, int atLineNumber = -1, bool includeSymbols = true) { ResultProperties resultProperties; string error; var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols); Assert.Null(error); return result; } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, out ResultProperties resultProperties, out string error, int atLineNumber = -1, bool includeSymbols = true) { var compilation0 = CreateCompilationWithMscorlib( source, options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe); var runtime = CreateRuntimeInstance(compilation0, debugFormat: includeSymbols ? DebugInformationFormat.Pdb : 0); var context = CreateMethodContext(runtime, methodName, atLineNumber); var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return testData; } /// <summary> /// Verify all type parameters from the method /// are from that method or containing types. /// </summary> internal static void VerifyTypeParameters(MethodSymbol method) { Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType)); AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument)); AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type)); VerifyTypeParameters(method.ContainingType); } internal static void VerifyLocal( CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName = null, DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None, string expectedILOpt = null, bool expectedGeneric = false, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>( testData, typeName, localAndMethod, expectedMethodName, expectedLocalName, expectedLocalDisplayName ?? expectedLocalName, expectedFlags, VerifyTypeParameters, expectedILOpt, expectedGeneric, expectedValueSourcePath, expectedValueSourceLine); } /// <summary> /// Verify all type parameters from the type /// are from that type or containing types. /// </summary> internal static void VerifyTypeParameters(NamedTypeSymbol type) { AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument)); var container = type.ContainingType; if ((object)container != null) { VerifyTypeParameters(container); } } internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature) { string[] parameterTypeNames; var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames); var candidates = compilation.GetMembers(methodOrTypeName); var methodOrType = (parameterTypeNames == null) ? candidates.FirstOrDefault() : candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.Type.Name))); Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'."); return methodOrType; } internal static Alias VariableAlias(string name, Type type = null) { return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName) { return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ObjectIdAlias(uint id, Type type = null) { return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName) { Assert.NotEqual(0u, id); // Not a valid id. var name = $"${id}"; return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ReturnValueAlias(int id = -1, Type type = null) { return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName) { var name = $"Method M{(id < 0 ? "" : id.ToString())} returned"; var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}"; return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias ExceptionAlias(Type type = null, bool stowed = false) { return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed); } internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false) { var name = "Error"; var fullName = stowed ? "$stowedexception" : "$exception"; var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception; return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(CustomTypeInfo)); } internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, CustomTypeInfo customTypeInfo) { return new Alias(kind, name, fullName, type, customTypeInfo); } } }
using System; using System.Text; using Fonet.DataTypes; namespace Fonet.Fo.Properties { internal class InlineProgressionDimensionMaker : LengthRangeProperty.Maker { private class SP_MinimumMaker : LengthProperty.Maker { protected internal SP_MinimumMaker(string sPropName) : base(sPropName) { } protected override bool IsAutoLengthAllowed() { return true; } public override IPercentBase GetPercentBase(FObj fo, PropertyList propertyList) { return new LengthBase(fo, propertyList, LengthBase.CONTAINING_BOX); } } private static readonly PropertyMaker s_MinimumMaker = new SP_MinimumMaker("inline-progression-dimension.minimum"); private class SP_OptimumMaker : LengthProperty.Maker { protected internal SP_OptimumMaker(string sPropName) : base(sPropName) { } protected override bool IsAutoLengthAllowed() { return true; } public override IPercentBase GetPercentBase(FObj fo, PropertyList propertyList) { return new LengthBase(fo, propertyList, LengthBase.CONTAINING_BOX); } } private static readonly PropertyMaker s_OptimumMaker = new SP_OptimumMaker("inline-progression-dimension.optimum"); private class SP_MaximumMaker : LengthProperty.Maker { protected internal SP_MaximumMaker(string sPropName) : base(sPropName) { } protected override bool IsAutoLengthAllowed() { return true; } public override IPercentBase GetPercentBase(FObj fo, PropertyList propertyList) { return new LengthBase(fo, propertyList, LengthBase.CONTAINING_BOX); } } private static readonly PropertyMaker s_MaximumMaker = new SP_MaximumMaker("inline-progression-dimension.maximum"); new public static PropertyMaker Maker(string propName) { return new InlineProgressionDimensionMaker(propName); } protected InlineProgressionDimensionMaker(string name) : base(name) { m_shorthandMaker = GetSubpropMaker("minimum"); } private PropertyMaker m_shorthandMaker; public override Property CheckEnumValues(string value) { return m_shorthandMaker.CheckEnumValues(value); } protected override bool IsCompoundMaker() { return true; } protected override PropertyMaker GetSubpropMaker(string subprop) { if (subprop.Equals("minimum")) { return s_MinimumMaker; } if (subprop.Equals("optimum")) { return s_OptimumMaker; } if (subprop.Equals("maximum")) { return s_MaximumMaker; } return base.GetSubpropMaker(subprop); } protected override Property SetSubprop(Property baseProp, string subpropName, Property subProp) { LengthRange val = baseProp.GetLengthRange(); val.SetComponent(subpropName, subProp, false); return baseProp; } public override Property GetSubpropValue(Property baseProp, string subpropName) { LengthRange val = baseProp.GetLengthRange(); return val.GetComponent(subpropName); } private Property m_defaultProp = null; public override Property Make(PropertyList propertyList) { if (m_defaultProp == null) { m_defaultProp = MakeCompound(propertyList, propertyList.getParentFObj()); } return m_defaultProp; } protected override Property MakeCompound(PropertyList pList, FObj fo) { LengthRange p = new LengthRange(); Property subProp; subProp = GetSubpropMaker("minimum").Make(pList, GetDefaultForMinimum(), fo); p.SetComponent("minimum", subProp, true); subProp = GetSubpropMaker("optimum").Make(pList, GetDefaultForOptimum(), fo); p.SetComponent("optimum", subProp, true); subProp = GetSubpropMaker("maximum").Make(pList, GetDefaultForMaximum(), fo); p.SetComponent("maximum", subProp, true); return new LengthRangeProperty(p); } protected virtual String GetDefaultForMinimum() { return "auto"; } protected virtual String GetDefaultForOptimum() { return "auto"; } protected virtual String GetDefaultForMaximum() { return "auto"; } public override Property ConvertProperty(Property p, PropertyList pList, FObj fo) { if (p is LengthRangeProperty) { return p; } if (!(p is EnumProperty)) { p = m_shorthandMaker.ConvertProperty(p, pList, fo); } if (p != null) { Property prop = MakeCompound(pList, fo); LengthRange pval = prop.GetLengthRange(); pval.SetComponent("minimum", p, false); pval.SetComponent("optimum", p, false); pval.SetComponent("maximum", p, false); return prop; } else { return null; } } public override bool IsInherited() { return false; } public override bool IsCorrespondingForced(PropertyList propertyList) { StringBuilder sbExpr = new StringBuilder(); sbExpr.Length = 0; sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); if (propertyList.GetExplicitProperty(sbExpr.ToString()) != null) { return true; } sbExpr.Length = 0; sbExpr.Append("min-"); sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); if (propertyList.GetExplicitProperty(sbExpr.ToString()) != null) { return true; } sbExpr.Length = 0; sbExpr.Append("max-"); sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); if (propertyList.GetExplicitProperty(sbExpr.ToString()) != null) { return true; } return false; } public override Property Compute(PropertyList propertyList) { FObj parentFO = propertyList.getParentFObj(); StringBuilder sbExpr = new StringBuilder(); Property p = null; sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); p = propertyList.GetExplicitOrShorthandProperty(sbExpr.ToString()); if (p != null) { p = ConvertProperty(p, propertyList, parentFO); } else { p = MakeCompound(propertyList, parentFO); } Property subprop; sbExpr.Length = 0; sbExpr.Append("min-"); sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); subprop = propertyList.GetExplicitOrShorthandProperty(sbExpr.ToString()); if (subprop != null) { SetSubprop(p, "minimum", subprop); } sbExpr.Length = 0; sbExpr.Append("max-"); sbExpr.Append(propertyList.wmRelToAbs(PropertyList.INLINEPROGDIM)); subprop = propertyList.GetExplicitOrShorthandProperty(sbExpr.ToString()); if (subprop != null) { SetSubprop(p, "maximum", subprop); } return p; } } }
/* * Copyright 2011 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; namespace ZXing.OneD { /// <summary> /// <p>Encapsulates functionality and implementation that is common to one-dimensional barcodes.</p> /// <author>dsbnatut@gmail.com (Kazuki Nishiura)</author> /// </summary> public abstract class OneDimensionalCodeWriter : Writer { private static readonly System.Text.RegularExpressions.Regex NUMERIC = new System.Text.RegularExpressions.Regex("[0-9]+"); /// <summary> /// returns supported formats /// </summary> protected abstract IList<BarcodeFormat> SupportedWriteFormats { get; } /// <summary> /// Encode the contents to boolean array expression of one-dimensional barcode. /// Start code and end code should be included in result, and side margins should not be included. /// </summary> /// <param name="contents">barcode contents to encode</param> /// <returns>a <c>bool[]</c> of horizontal pixels (false = white, true = black)</returns> public abstract bool[] encode(String contents); /// <summary> /// Can be overwritten if the encode requires to read the hints map. Otherwise it defaults to {@code encode}. /// </summary> /// <param name="contents">barcode contents to encode</param> /// <param name="hints">encoding hints</param> /// <returns>a <c>bool[]</c> of horizontal pixels (false = white, true = black)</returns> protected virtual bool[] encode(String contents, IDictionary<EncodeHintType, object> hints) { return encode(contents); } /// <summary> /// Encode a barcode using the default settings. /// </summary> /// <param name="contents">The contents to encode in the barcode</param> /// <param name="format">The barcode format to generate</param> /// <param name="width">The preferred width in pixels</param> /// <param name="height">The preferred height in pixels</param> /// <returns> /// The generated barcode as a Matrix of unsigned bytes (0 == black, 255 == white) /// </returns> public BitMatrix encode(String contents, BarcodeFormat format, int width, int height) { return encode(contents, format, width, height, null); } /// <summary> /// Encode the contents following specified format. /// {@code width} and {@code height} are required size. This method may return bigger size /// {@code BitMatrix} when specified size is too small. The user can set both {@code width} and /// {@code height} to zero to get minimum size barcode. If negative value is set to {@code width} /// or {@code height}, {@code IllegalArgumentException} is thrown. /// </summary> public virtual BitMatrix encode(String contents, BarcodeFormat format, int width, int height, IDictionary<EncodeHintType, object> hints) { if (String.IsNullOrEmpty(contents)) { throw new ArgumentException("Found empty contents"); } if (width < 0 || height < 0) { throw new ArgumentException("Negative size is not allowed. Input: " + width + 'x' + height); } var supportedFormats = SupportedWriteFormats; if (supportedFormats != null && !supportedFormats.Contains(format)) { #if NET20 || NET35 || UNITY || PORTABLE var supportedFormatsArray = new string[supportedFormats.Count]; for (var i = 0; i < supportedFormats.Count; i++) supportedFormatsArray[i] = supportedFormats[i].ToString(); throw new ArgumentException("Can only encode " + string.Join(", ", supportedFormatsArray) + ", but got " + format); #else throw new ArgumentException("Can only encode " + string.Join(", ", supportedFormats) + ", but got " + format); #endif } int sidesMargin = DefaultMargin; if (hints != null) { var sidesMarginInt = hints.ContainsKey(EncodeHintType.MARGIN) ? hints[EncodeHintType.MARGIN] : null; if (sidesMarginInt != null) { sidesMargin = Convert.ToInt32(sidesMarginInt); } } var code = encode(contents, hints); return renderResult(code, width, height, sidesMargin); } /// <summary> /// </summary> /// <returns>a byte array of horizontal pixels (0 = white, 1 = black)</returns> private static BitMatrix renderResult(bool[] code, int width, int height, int sidesMargin) { int inputWidth = code.Length; // Add quiet zone on both sides. int fullWidth = inputWidth + sidesMargin; int outputWidth = Math.Max(width, fullWidth); int outputHeight = Math.Max(1, height); int multiple = outputWidth / fullWidth; int leftPadding = (outputWidth - (inputWidth * multiple)) / 2; BitMatrix output = new BitMatrix(outputWidth, outputHeight); for (int inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) { if (code[inputX]) { output.setRegion(outputX, 0, multiple, outputHeight); } } return output; } /// <summary> /// Throw ArgumentException if input contains characters other than digits 0-9. /// </summary> /// <param name="contents">string to check for numeric characters</param> /// <exception cref="ArgumentException">if input contains characters other than digits 0-9.</exception> protected static void checkNumeric(String contents) { if (!NUMERIC.Match(contents).Success) { throw new ArgumentException("Input should only contain digits 0-9"); } } /// <summary> /// Appends the given pattern to the target array starting at pos. /// </summary> /// <param name="target">encode black/white pattern into this array</param> /// <param name="pos">position to start encoding at in <c>target</c></param> /// <param name="pattern">lengths of black/white runs to encode</param> /// <param name="startColor">starting color - false for white, true for black</param> /// <returns>the number of elements added to target.</returns> protected static int appendPattern(bool[] target, int pos, int[] pattern, bool startColor) { bool color = startColor; int numAdded = 0; foreach (int len in pattern) { for (int j = 0; j < len; j++) { target[pos++] = color; } numAdded += len; color = !color; // flip color after each segment } return numAdded; } /// <summary> /// Gets the default margin. /// </summary> virtual public int DefaultMargin { get { // CodaBar spec requires a side margin to be more than ten times wider than narrow space. // This seems like a decent idea for a default for all formats. return 10; } } /// <summary> /// Calculates the checksum digit modulo10. /// </summary> /// <param name="contents">The contents.</param> /// <returns></returns> public static String CalculateChecksumDigitModulo10(String contents) { var oddsum = 0; var evensum = 0; for (var index = contents.Length - 1; index >= 0; index -= 2) { oddsum += (contents[index] - '0'); } for (var index = contents.Length - 2; index >= 0; index -= 2) { evensum += (contents[index] - '0'); } return contents + ((10 - ((oddsum * 3 + evensum) % 10)) % 10); } } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using DotSpatial.Serialization; namespace DotSpatial.Symbology.Forms { /// <summary> /// SymbolSizeChooser. /// </summary> [DefaultEvent("SelectedSizeChanged")] [ToolboxItem(false)] public class SymbolSizeChooser : Control, ISupportInitialize { #region Fields private Color _boxBackColor; private List<SizeBox> _boxes; private Color _boxSelectionColor; private Size _boxSize; private bool _isInitializing; private Size2D _maxSize; private Size2D _minSize; private int _numBoxes; private Orientation _orientation; private int _roundingRadius; private Size2D _selectedSize; private ISymbol _symbol; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="SymbolSizeChooser"/> class. /// </summary> public SymbolSizeChooser() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="SymbolSizeChooser"/> class. /// </summary> /// <param name="symbol">The symbol to draw.</param> public SymbolSizeChooser(ISymbol symbol) { Configure(); _symbol = symbol; } #endregion #region Events /// <summary> /// Occurs when the selected size has changed /// </summary> public event EventHandler SelectedSizeChanged; #endregion #region Properties /// <summary> /// Gets or sets the normal background color for the boxes. /// </summary> [Description("Gets or sets the normal background color for the boxes.")] public Color BoxBackColor { get { return _boxBackColor; } set { _boxBackColor = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the box selection color. /// </summary> [Description("Gets or sets the box selection color")] public Color BoxSelectionColor { get { return _boxSelectionColor; } set { _boxSelectionColor = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the rectangular extent for all the boxes. This is not the size of the symbol. /// </summary> [Description("Gets or sets the rectangular extent for all the boxes. This is not the size of the symbol.")] public Size BoxSize { get { return _boxSize; } set { _boxSize = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the maximum symbol size. /// </summary> [Description("Gets or sets the maximum symbol size.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Size2D MaximumSymbolSize { get { return _maxSize; } set { _maxSize = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the minimum symbol size. /// </summary> [Description("Gets or sets the minimum symbol size")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Size2D MinimumSymbolSize { get { return _minSize; } set { _minSize = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the number of boxes. /// </summary> [Description("Gets or sets the number of boxes")] public int NumBoxes { get { return _numBoxes; } set { _numBoxes = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets whether the boxes are drawn horizontally or vertically. /// </summary> [Description("Gets or sets whether the boxes are drawn horizontally or vertically.")] public Orientation Orientation { get { return _orientation; } set { _orientation = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the rounding radius for the boxes. /// </summary> [Description("Gets or sets the rounding radius for the boxes")] public int RoundingRadius { get { return _roundingRadius; } set { _roundingRadius = value; if (!_isInitializing) RefreshBoxes(); } } /// <summary> /// Gets or sets the currently selected size. /// </summary> [Description("Gets or sets the currently selected size.")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public Size2D SelectedSize { get { return _selectedSize; } set { _selectedSize = value; if (!_isInitializing) Invalidate(); } } /// <summary> /// Gets or sets the symbol to use for this control. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ISymbol Symbol { get { return _symbol; } set { _symbol = value; foreach (SizeBox sb in _boxes) { sb.IsSelected = _symbol.Size == sb.Size; } if (!_isInitializing) Invalidate(); } } #endregion #region Methods /// <summary> /// Prevent redundant updates to the boxes every time a property is changed. /// </summary> public void BeginInit() { _isInitializing = true; } /// <summary> /// Enable live updating so that from now on, changes rebuild boxes. /// </summary> public void EndInit() { _isInitializing = false; RefreshBoxes(); } /// <summary> /// Forces the box sub-categories to refresh given the new content. /// </summary> public virtual void RefreshBoxes() { _boxes = new List<SizeBox>(); for (int i = 0; i < NumBoxes; i++) { CreateBox(i); } Invalidate(); } /// <summary> /// Occurs durring drawing but is overridable by subclasses. /// </summary> /// <param name="g">The graphics object used for drawing.</param> /// <param name="clip">The clip rectangle.</param> protected virtual void OnDraw(Graphics g, Rectangle clip) { foreach (SizeBox sb in _boxes) { sb.Draw(g, clip, _symbol); } } /// <summary> /// Handles the mouse up situation. /// </summary> /// <param name="e">The event args.</param> protected override void OnMouseUp(MouseEventArgs e) { bool changed = false; foreach (SizeBox sb in _boxes) { if (sb.Bounds.Contains(e.Location)) { if (!sb.IsSelected) { sb.IsSelected = true; _selectedSize = sb.Size.Copy(); _symbol.Size.Height = sb.Size.Height; _symbol.Size.Width = sb.Size.Width; changed = true; } } else { if (sb.IsSelected) { sb.IsSelected = false; } } } Invalidate(); if (changed) OnSelectedSizeChanged(); base.OnMouseUp(e); } /// <summary> /// Occurs as the SymbolSizeChooser control is being drawn. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Prevent flicker. /// </summary> /// <param name="e">The event args.</param> protected override void OnPaintBackground(PaintEventArgs e) { // base.OnPaintBackground(pevent); } /// <summary> /// Fires the selected size changed event. /// </summary> protected virtual void OnSelectedSizeChanged() { SelectedSizeChanged?.Invoke(this, EventArgs.Empty); } private void Configure() { _boxes = new List<SizeBox>(); _numBoxes = 4; _minSize = new Size2D(4, 4); _maxSize = new Size2D(30, 30); _selectedSize = _minSize.Copy(); _boxSize = new Size(36, 36); _boxBackColor = SystemColors.Control; _boxSelectionColor = SystemColors.Highlight; _symbol = new SimpleSymbol(); _orientation = Orientation.Horizontal; _roundingRadius = 6; RefreshBoxes(); } private void CreateBox(int i) { SizeBox sb = new SizeBox(); int x = 1; int y = 1; if (_orientation == Orientation.Horizontal) { x = ((_boxSize.Width + 2) * i) + 1; } else { y = ((_boxSize.Height + 2) * i) + 1; } sb.Bounds = new Rectangle(x, y, _boxSize.Width, _boxSize.Height); sb.BackColor = _boxBackColor; sb.SelectionColor = _boxSelectionColor; sb.RoundingRadius = _roundingRadius; if (i == 0) { sb.Size = _minSize != null ? _minSize.Copy() : new Size2D(4, 4); } else if (i == _numBoxes - 1) { sb.Size = _maxSize != null ? _maxSize.Copy() : new Size2D(32, 32); } else { if (_minSize != null && _maxSize != null) { // because of the elses, we know that the number must be greater than 2, and that the current item is not the min or max // Use squaring so that bigger sizes have larger differences between them. double cw = (_maxSize.Width - _minSize.Width) / _numBoxes; double ch = (_maxSize.Height - _minSize.Height) / _numBoxes; sb.Size = new Size2D(_minSize.Width + (cw * i), _minSize.Height + (ch * i)); } else { sb.Size = new Size2D(16, 16); } } _boxes.Add(sb); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace EffectEditor { using XnaColor = Microsoft.Xna.Framework.Graphics.Color; using System.Reflection; using FlatRedBall.Graphics.Model; using System.Threading; using EffectEditor.HelperClasses; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; using System.IO; using EffectEditor.EffectComponents; using EffectEditor.EffectComponents.HLSLInformation; using System.Collections; public partial class EditorForm : Form { #region Fields Dictionary<String, PositionedModel> mModelDictionary = new Dictionary<string,PositionedModel>(); ModelEditor mModelEditor; EffectComponent mEffectComponent; // The current effect EffectDefinition mEffectDefinition; List<EffectComponent> mLoadedComponents; private bool mSuspendTechniqueChange = false; private bool mSuspendPassChange = false; #endregion public EditorForm() { InitializeComponent(); mEffectDefinition = new EffectDefinition("NewEffect"); // Allow model drag-drop modelViewPanel.AllowDrop = true; modelViewPanel.DragEnter += new DragEventHandler(modelViewPanel_DragEnter); modelViewPanel.DragDrop += new DragEventHandler(modelViewPanel_DragDrop); // Allow effect drag-drop effectEditBox.AllowDrop = true; effectEditBox.DragEnter += new DragEventHandler(effectEditBox_DragEnter); effectEditBox.DragDrop += new DragEventHandler(effectEditBox_DragDrop); modelViewPanel.ModelLoaded = ModelLoaded; hlslInfoBox.ReadOnly = true; hlslInfoBox.Clear(); effectParametersList.Parameters = mEffectDefinition.Parameters; UpdateStandardParameters(); effectComponentsList.DataSource = mEffectDefinition.Components; effectTechniquesList.DataSource = mEffectDefinition.Techniques; // populate shader profiles boxes in techniques tab string[] shaderProfiles = Enum.GetNames(typeof(ShaderProfile)); for (int i = 0; i < shaderProfiles.Length; i++) { if (shaderProfiles[i].Contains("VS")) passVertexShaderProfileBox.Items.Add(shaderProfiles[i]); if (shaderProfiles[i].Contains("PS")) passPixelShaderProfileBox.Items.Add(shaderProfiles[i]); } mLoadedComponents = new List<EffectComponent>(); vertexShaderEditor.AllowComponentUsage = true; pixelShaderEditor.AllowComponentUsage = true; } #region Model View Panel Input private void frbPanel1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (modelViewPanel.Focused && e.KeyCode != Keys.Tab) e.IsInputKey = true; } private void modelViewPanel_MouseDown(object sender, MouseEventArgs e) { modelViewPanel.Focus(); } private void bgColorComboBox_SelectedIndexChanged(object sender, EventArgs e) { String colorName = bgColorComboBox.Text; if (colorName != "Custom...") { PropertyInfo colorProperty = typeof(XnaColor).GetProperty(colorName); if (colorProperty != null) { XnaColor color = (XnaColor)colorProperty.GetValue(typeof(XnaColor), BindingFlags.Static | BindingFlags.Public, null, null, null); modelViewPanel.BackgroundColor = color; redCustomColorBar.Value = color.R; greenCustomColorBar.Value = color.G; blueCustomColorBar.Value = color.B; } RLabel.Enabled = false; GLabel.Enabled = false; BLabel.Enabled = false; redCustomColorBar.Enabled = false; greenCustomColorBar.Enabled = false; blueCustomColorBar.Enabled = false; } else { RLabel.Enabled = true; GLabel.Enabled = true; BLabel.Enabled = true; redCustomColorBar.Enabled = true; greenCustomColorBar.Enabled = true; blueCustomColorBar.Enabled = true; } } private void CustomColorBar_Scroll(object sender, EventArgs e) { if (redCustomColorBar.Enabled) { modelViewPanel.BackgroundColor = new XnaColor( (byte)redCustomColorBar.Value, (byte)greenCustomColorBar.Value, (byte)blueCustomColorBar.Value); } } private void modelSelectionBox_SelectedIndexChanged(object sender, EventArgs e) { foreach (PositionedModel model in mModelDictionary.Values) { model.Visible = false; } String selectedName = (string)modelSelectionBox.Items[modelSelectionBox.SelectedIndex]; // Check if the value is "Load Model..." if (selectedName == "Load Model...") { if (openModelFileDialog.ShowDialog() == DialogResult.OK) { foreach (String file in openModelFileDialog.FileNames) { modelViewPanel.AddModel(file); } } } else { // Set visible, and set effect properties PositionedModel selectedModel = mModelDictionary[selectedName]; selectedModel.Visible = true; modelViewPanel.CurrentModel = selectedModel; SelectModel(selectedModel); } } void SelectModel(PositionedModel model) { mModelEditor = new ModelEditor(model); modelPropertyGrid.SelectedObject = mModelEditor; } delegate void ModelLoadedCallback(String name, PositionedModel model); private void ModelLoaded(String name, PositionedModel model) { if (this.InvokeRequired) { ModelLoadedCallback d = new ModelLoadedCallback(ModelLoaded); this.Invoke(d, new object[] { name, model }); } else { // Add the new model if (mModelDictionary.ContainsKey(name)) { mModelDictionary[name] = model; } else { mModelDictionary.Add(name, model); } // Repopulate the model list, and select the newest addition modelSelectionBox.Items.Clear(); foreach (String key in mModelDictionary.Keys) { modelSelectionBox.Items.Add(key); } // Add "Load Model..." item modelSelectionBox.Items.Add("Load Model..."); modelSelectionBox.SelectedIndex = modelSelectionBox.Items.IndexOf(name); } } #endregion private void exitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void compileEffectButton_Click(object sender, EventArgs e) { // Get the effect source string effectSource = string.Empty; for (int i = 0; i < effectEditBox.Lines.Length; i++) { effectSource += effectEditBox.Lines[i] + Environment.NewLine; } // Start output effectCompileOutput.Clear(); effectCompileOutput.AppendText("Compiling Effect..." + Environment.NewLine); // Compile the effect CompiledEffect effectCompiled = Effect.CompileEffectFromSource( effectSource, null, //new CompilerMacro[] { }, null, CompilerOptions.None, TargetPlatform.Windows); // Check for errors if (!effectCompiled.Success) { effectCompileOutput.AppendText("There were errors:" + Environment.NewLine); effectCompileOutput.AppendText(" " + effectCompiled.ErrorsAndWarnings + Environment.NewLine); } else { effectCompileOutput.AppendText("Success!"); effectPropertyGrid.SelectedObject = null; // Apply the effect Effect effect = modelViewPanel.ApplyEffect(effectCompiled.GetEffectCode()); // Set the property grid EffectPropertyEditor editor = new EffectPropertyEditor(effect); effectPropertyGrid.SelectedObject = editor; // Switch tabs mainTabControl.SelectedTab = mainTabControl.TabPages[0]; } } #region Drag and Drop Effects void effectEditBox_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } void effectEditBox_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files != null && files.Length > 0) { effectEditBox.Clear(); effectEditBox.LoadFile(files[0], RichTextBoxStreamType.PlainText); } } #endregion #region Drag and Drop Models void modelViewPanel_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { // Check if the files list contains an X or XNB file string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); string extension = Path.GetExtension(files[0]).ToLower(); bool canLoad = (extension == "x" || extension == "xnb"); e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } void modelViewPanel_DragDrop(object sender, DragEventArgs e) { string[] files = (string[])e.Data.GetData(DataFormats.FileDrop); if (files != null && files.Length > 0 && Path.GetExtension(files[0]).ToLower() == "x" || Path.GetExtension(files[0]).ToLower() == "xnb") { modelViewPanel.AddModel(files[0]); } } #endregion #region Components private void mainTabControl_SelectedIndexChanged(object sender, EventArgs e) { componentToolStripMenuItem.Visible = (mainTabControl.SelectedTab.Text == "Component Editor"); } private void newComponentToolStripMenuItem_Click(object sender, EventArgs e) { EffectComponent component = new EffectComponent(); component.Name = "NewComponent"; componentEditor.SetComponent(component); } private void saveComponentToolStripMenuItem_Click(object sender, EventArgs e) { if (saveComponentDialog.ShowDialog() == DialogResult.OK) { componentEditor.Component.Save(saveComponentDialog.FileName); } } private void loadComponentToolStripMenuItem_Click(object sender, EventArgs e) { if (openComponentDialog.ShowDialog() == DialogResult.OK) { EffectComponent component = EffectComponent.FromFile(openComponentDialog.FileName); componentEditor.SetComponent(component); } } #endregion #region Effect Editing #region Components private void UpdateAvailableComponents() { mLoadedComponents.Clear(); foreach (string componentFileName in mEffectDefinition.Components) { mLoadedComponents.Add(EffectComponent.FromFile(componentFileName)); } vertexShaderEditor.AvailableComponents = mLoadedComponents; pixelShaderEditor.AvailableComponents = mLoadedComponents; } private void addEffectComponentButton_Click(object sender, EventArgs e) { if (openComponentDialog.ShowDialog() == DialogResult.OK) { mEffectDefinition.Components.Add(openComponentDialog.FileName); int selectedIndex = effectComponentsList.SelectedIndex; effectComponentsList.DataSource = null; effectComponentsList.DataSource = mEffectDefinition.Components; effectComponentsList.SelectedIndex = selectedIndex; UpdateAvailableComponents(); } } private void removeEffectComponentButton_Click(object sender, EventArgs e) { if (effectComponentsList.SelectedIndex >= 0) { mEffectDefinition.Components.RemoveAt(effectComponentsList.SelectedIndex); int selectedIndex = effectComponentsList.SelectedIndex; if (selectedIndex >= mEffectDefinition.Components.Count) selectedIndex = mEffectDefinition.Components.Count - 1; effectComponentsList.DataSource = null; effectComponentsList.DataSource = mEffectDefinition.Components; effectComponentsList.SelectedIndex = selectedIndex; UpdateAvailableComponents(); } } private void effectComponentsList_SelectedIndexChanged(object sender, EventArgs e) { removeEffectComponentButton.Enabled = (effectComponentsList.SelectedIndex >= 0); } #endregion #region Parameters private void UpdateStandardParameters() { int selectedIndex = standardParametersList.SelectedIndex; standardParametersList.Items.Clear(); foreach (EffectParameterDefinition param in FRBConstants.StandardParameters) { if (!effectParametersList.Parameters.Contains(param)) standardParametersList.Items.Add(param); } if (selectedIndex >= standardParametersList.Items.Count) selectedIndex = standardParametersList.Items.Count - 1; standardParametersList.SelectedIndex = selectedIndex; } private void standardParametersList_SelectedIndexChanged(object sender, EventArgs e) { addStandardParameterButton.Enabled = (standardParametersList.SelectedIndex >= 0); } private void addStandardParameterButton_Click(object sender, EventArgs e) { EffectParameterDefinition param = (EffectParameterDefinition)standardParametersList.SelectedItem; mEffectDefinition.Parameters.Add(param); effectParametersList.Parameters = mEffectDefinition.Parameters; UpdateStandardParameters(); } #endregion #region Vertex Shaders private void effectEdit_vertexShaderListChanged(object sender, EventArgs e) { EffectComponent currentSelection; int index = vertexShadersList.SelectedIndex; vertexShaderEditor.SaveNameEditPosition(); if (vertexShadersList.SelectedIndex >= 0) { currentSelection = mEffectDefinition.VertexShaders[vertexShadersList.SelectedIndex]; mEffectDefinition.VertexShaders.Sort(); index = mEffectDefinition.VertexShaders.IndexOf(currentSelection); } vertexShadersList.DataSource = null; vertexShadersList.DataSource = mEffectDefinition.VertexShaders; mSuspendPassChange = true; passVertexShaderBox.DataSource = null; passVertexShaderBox.DataSource = mEffectDefinition.VertexShaders; mSuspendPassChange = false; vertexShadersList.SelectedIndex = index; vertexShaderEditor.RestoreNameEditPosition(); vertexShaderEditor.Enabled = mEffectDefinition.VertexShaders.Count > 0; } private void vertexShadersList_SelectedIndexChanged(object sender, EventArgs e) { if (vertexShadersList.SelectedIndex != -1 && vertexShadersList.Items.Count > 0) { EffectComponent component = (EffectComponent)vertexShadersList.SelectedItem; vertexShaderEditor.SetComponent(component); } } private void addVertexShaderButton_Click(object sender, EventArgs e) { EffectComponent component = new EffectComponent(); component.Name = "NewVertexShader"; component.IsInline = false; HlslSemantic inputSemantic = Semantics.Find("POSITION", true, true); inputSemantic.ResourceNumber = 0; component.Parameters.Add(new EffectParameterDefinition( "Position", inputSemantic.Type, inputSemantic)); HlslSemantic outputSemantic = Semantics.Find("POSITION", true, false); outputSemantic.ResourceNumber = 0; component.ReturnType.Add(new EffectParameterDefinition( "Position", outputSemantic.Type, outputSemantic)); mEffectDefinition.VertexShaders.Add(component); effectEdit_vertexShaderListChanged(sender, e); vertexShadersList.SelectedItem = component; if (mEffectDefinition.VertexShaders.Count > 0) vertexShaderEditor.Enabled = true; } private void vertexShaderEditor_ComponentChanged(object sender, EventArgs e) { effectEdit_vertexShaderListChanged(sender, e); vertexShadersList.SelectedItem = vertexShaderEditor.Component; } private void removeVertexShaderButton_Click(object sender, EventArgs e) { int selectedIndex = vertexShadersList.SelectedIndex; mEffectDefinition.VertexShaders.RemoveAt(selectedIndex); vertexShadersList.DataSource = null; vertexShadersList.DataSource = mEffectDefinition.VertexShaders; if (selectedIndex >= mEffectDefinition.VertexShaders.Count && mEffectDefinition.VertexShaders.Count > 0) vertexShadersList.SelectedIndex = mEffectDefinition.VertexShaders.Count - 1; if (mEffectDefinition.VertexShaders.Count <= 0) vertexShaderEditor.Enabled = false; } #endregion #region Pixel Shaders private void effectEdit_pixelShaderListChanged(object sender, EventArgs e) { EffectComponent currentSelection; int index = pixelShadersList.SelectedIndex; pixelShaderEditor.SaveNameEditPosition(); if (pixelShadersList.SelectedIndex >= 0) { currentSelection = mEffectDefinition.PixelShaders[pixelShadersList.SelectedIndex]; mEffectDefinition.PixelShaders.Sort(); index = mEffectDefinition.PixelShaders.IndexOf(currentSelection); } pixelShadersList.DataSource = null; pixelShadersList.DataSource = mEffectDefinition.PixelShaders; mSuspendPassChange = true; passPixelShaderBox.DataSource = null; passPixelShaderBox.DataSource = mEffectDefinition.PixelShaders; mSuspendPassChange = false; pixelShadersList.SelectedIndex = index; pixelShaderEditor.RestoreNameEditPosition(); pixelShaderEditor.Enabled = mEffectDefinition.PixelShaders.Count > 0; } private void pixelShadersList_SelectedIndexChanged(object sender, EventArgs e) { if (pixelShadersList.SelectedIndex != -1 && pixelShadersList.Items.Count > 0) { EffectComponent component = (EffectComponent)pixelShadersList.SelectedItem; pixelShaderEditor.SetComponent(component); } } private void addPixelShaderButton_Click(object sender, EventArgs e) { EffectComponent component = new EffectComponent(); component.Name = "NewPixelShader"; component.IsInline = false; HlslSemantic outputSemantic = Semantics.Find("COLOR", true, false); outputSemantic.ResourceNumber = 0; component.ReturnType.Add(new EffectParameterDefinition( "Color", outputSemantic.Type, outputSemantic)); mEffectDefinition.PixelShaders.Add(component); effectEdit_pixelShaderListChanged(sender, e); pixelShadersList.SelectedItem = component; if (mEffectDefinition.PixelShaders.Count > 0) pixelShaderEditor.Enabled = true; } private void pixelShaderEditor_ComponentChanged(object sender, EventArgs e) { effectEdit_pixelShaderListChanged(sender, e); pixelShadersList.SelectedItem = pixelShaderEditor.Component; } private void removePixelShaderButton_Click(object sender, EventArgs e) { int selectedIndex = pixelShadersList.SelectedIndex; mEffectDefinition.PixelShaders.RemoveAt(selectedIndex); pixelShadersList.DataSource = null; pixelShadersList.DataSource = mEffectDefinition.PixelShaders; if (selectedIndex >= mEffectDefinition.PixelShaders.Count && mEffectDefinition.PixelShaders.Count > 0) pixelShadersList.SelectedIndex = mEffectDefinition.PixelShaders.Count - 1; if (mEffectDefinition.PixelShaders.Count <= 0) pixelShaderEditor.Enabled = false; } #endregion #region Techniques private void addTechniqueButton_Click(object sender, EventArgs e) { EffectTechniqueDefinition technique = new EffectTechniqueDefinition("NewTechnique"); technique.Passes.Add(new EffectPassDefinition( "Pass0", (mEffectDefinition.VertexShaders.Count > 0) ? mEffectDefinition.VertexShaders[0].Name : String.Empty, (mEffectDefinition.PixelShaders.Count > 0) ? mEffectDefinition.PixelShaders[0].Name : String.Empty, (mEffectDefinition.VertexShaders.Count > 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), mEffectDefinition.VertexShaders[0].MinimumVertexShaderProfile, true) : ShaderProfile.VS_1_1, (mEffectDefinition.PixelShaders.Count > 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), mEffectDefinition.PixelShaders[0].MinimumPixelShaderProfile, true) : ShaderProfile.PS_1_1)); mEffectDefinition.Techniques.Add(technique); effectTechniquesList.DataSource = null; effectTechniquesList.DataSource = mEffectDefinition.Techniques; effectTechniquesList.SelectedIndex = mEffectDefinition.Techniques.IndexOf(technique); } private void removeTechniqueButton_Click(object sender, EventArgs e) { if (effectTechniquesList.SelectedIndex >= 0) { mEffectDefinition.Techniques.RemoveAt(effectTechniquesList.SelectedIndex); int selectedIndex = effectTechniquesList.SelectedIndex; if (selectedIndex >= mEffectDefinition.Techniques.Count) selectedIndex = mEffectDefinition.Techniques.Count - 1; effectTechniquesList.DataSource = null; effectTechniquesList.DataSource = mEffectDefinition.Techniques; effectTechniquesList.SelectedIndex = selectedIndex; } } private void effectTechniquesList_SelectedIndexChanged(object sender, EventArgs e) { if (!mSuspendTechniqueChange) { effectTechniquePassesEditor.Enabled = (effectTechniquesList.SelectedIndex >= 0); if (effectTechniquesList.SelectedIndex >= 0) { EffectTechniqueDefinition technique = mEffectDefinition.Techniques[ effectTechniquesList.SelectedIndex]; effectTechniquePassesList.DataSource = null; effectTechniquePassesList.DataSource = technique.Passes; effectTechniquePassesList.ClearSelected(); techniqueNameBox.Text = technique.Name; if (technique.Passes.Count > 0) effectTechniquePassesList.SelectedIndex = 0; } } } private void techniqueNameBox_TextChanged(object sender, EventArgs e) { mSuspendTechniqueChange = true; EffectTechniqueDefinition technique = mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex]; technique.Name = techniqueNameBox.Text; mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex] = technique; effectTechniquesList.SuspendLayout(); int selectedIndex = effectTechniquesList.SelectedIndex; effectTechniquesList.DataSource = null; effectTechniquesList.DataSource = mEffectDefinition.Techniques; effectTechniquesList.SelectedIndex = selectedIndex; effectTechniquesList.ResumeLayout(); mSuspendTechniqueChange = false; } private void addPassButton_Click(object sender, EventArgs e) { EffectTechniqueDefinition technique = mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex]; technique.Passes.Add(new EffectPassDefinition( "Pass" + technique.Passes.Count.ToString(), (mEffectDefinition.VertexShaders.Count > 0) ? mEffectDefinition.VertexShaders[0].Name : String.Empty, (mEffectDefinition.PixelShaders.Count > 0) ? mEffectDefinition.PixelShaders[0].Name : String.Empty, (mEffectDefinition.VertexShaders.Count > 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), mEffectDefinition.VertexShaders[0].MinimumVertexShaderProfile, true) : ShaderProfile.VS_1_1, (mEffectDefinition.PixelShaders.Count > 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), mEffectDefinition.PixelShaders[0].MinimumPixelShaderProfile, true) : ShaderProfile.PS_1_1)); mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex] = technique; effectTechniquePassesList.DataSource = null; effectTechniquePassesList.DataSource = technique.Passes; effectTechniquePassesList.SelectedIndex = technique.Passes.Count - 1; } private void removePassButton_Click(object sender, EventArgs e) { EffectTechniqueDefinition technique = mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex]; technique.Passes.RemoveAt(effectTechniquePassesList.SelectedIndex); mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex] = technique; int selectedIndex = effectTechniquePassesList.SelectedIndex; if (selectedIndex >= technique.Passes.Count) selectedIndex = technique.Passes.Count - 1; effectTechniquePassesList.DataSource = null; effectTechniquePassesList.DataSource = technique.Passes; effectTechniquePassesList.SelectedIndex = selectedIndex; } private void effectTechniquePassesList_SelectedIndexChanged(object sender, EventArgs e) { if (!mSuspendPassChange) { removePassButton.Enabled = (effectTechniquePassesList.SelectedIndex >= 0); effectTechniquePassesEditor.Panel2.Enabled = (effectTechniquePassesList.SelectedIndex >= 0); if (effectTechniquePassesList.SelectedIndex >= 0) { EffectPassDefinition pass = ((EffectPassDefinition)effectTechniquePassesList.SelectedItem); passNameBox.Text = pass.Name; // vertex shaders int shaderIndex = -1; for (int i = 0; i < mEffectDefinition.VertexShaders.Count; i++) { if (mEffectDefinition.VertexShaders[i].Name == pass.VertexShaderName) shaderIndex = i; } passVertexShaderBox.SelectedIndex = shaderIndex; passVertexShaderProfileBox.SelectedIndex = (passVertexShaderProfileBox.Items.Contains(pass.VertexShaderProfile.ToString()) ? passVertexShaderProfileBox.Items.IndexOf(pass.VertexShaderProfile.ToString()) : -1); // pixel shaders shaderIndex = -1; for (int i = 0; i < mEffectDefinition.PixelShaders.Count; i++) { if (mEffectDefinition.PixelShaders[i].Name == pass.PixelShaderName) shaderIndex = i; } passPixelShaderBox.SelectedIndex = shaderIndex; passPixelShaderProfileBox.SelectedIndex = (passPixelShaderProfileBox.Items.Contains(pass.PixelShaderProfile.ToString()) ? passPixelShaderProfileBox.Items.IndexOf(pass.PixelShaderProfile.ToString()) : -1); } } } private void pass_Changed(object sender, EventArgs e) { if (!mSuspendPassChange) { EffectPassDefinition pass = new EffectPassDefinition( passNameBox.Text, (passVertexShaderBox.SelectedIndex >= 0) ? mEffectDefinition.VertexShaders[passVertexShaderBox.SelectedIndex].Name : String.Empty, (passPixelShaderBox.SelectedIndex >= 0) ? mEffectDefinition.PixelShaders[passPixelShaderBox.SelectedIndex].Name : String.Empty, (passVertexShaderProfileBox.SelectedIndex >= 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), (string)passVertexShaderProfileBox.SelectedItem, true) : ShaderProfile.VS_1_1, (passPixelShaderProfileBox.SelectedIndex >= 0) ? (ShaderProfile)Enum.Parse(typeof(ShaderProfile), (string)passPixelShaderProfileBox.SelectedItem, true) : ShaderProfile.PS_1_1); mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex].Passes[effectTechniquePassesList.SelectedIndex] = pass; mSuspendPassChange = true; int nameBoxStart = passNameBox.SelectionStart; int nameBoxLen = passNameBox.SelectionLength; int selectedIndex = effectTechniquePassesList.SelectedIndex; effectTechniquePassesList.DataSource = null; effectTechniquePassesList.DataSource = mEffectDefinition.Techniques[effectTechniquesList.SelectedIndex].Passes; effectTechniquePassesList.SelectedIndex = selectedIndex; passNameBox.SelectionStart = nameBoxStart; passNameBox.SelectionLength = nameBoxLen; mSuspendPassChange = false; } } #endregion #endregion private void compileEffectButton_Click_1(object sender, EventArgs e) { effectCompileOutput.Clear(); effectEditBox.Text = mEffectDefinition.GetEffectCode(); compileEffectButton_Click(sender, e); string output = effectCompileOutput.Text + Environment.NewLine + Environment.NewLine + mEffectDefinition.GetEffectCode(); effectCompileOutput.Text = output; } private void loadEffectToolStripMenuItem_Click(object sender, EventArgs e) { if (openEffectDialog.ShowDialog() == DialogResult.OK) { mEffectDefinition = EffectDefinition.FromFile(openEffectDialog.FileName); this.SuspendLayout(); effectComponentsList.DataSource = null; effectComponentsList.DataSource = mEffectDefinition.Components; UpdateAvailableComponents(); effectParametersList.Parameters = mEffectDefinition.Parameters; UpdateStandardParameters(); effectEdit_vertexShaderListChanged(null, new EventArgs()); effectEdit_pixelShaderListChanged(null, new EventArgs()); if (mEffectDefinition.VertexShaders.Count > 0) vertexShadersList.SelectedIndex = 0; if (mEffectDefinition.PixelShaders.Count > 0) pixelShadersList.SelectedIndex = 0; effectTechniquesList.DataSource = null; effectTechniquesList.DataSource = mEffectDefinition.Techniques; this.ResumeLayout(); } } private void saveEffectToolStripMenuItem_Click(object sender, EventArgs e) { if (saveEffectDialog.ShowDialog() == DialogResult.OK) { mEffectDefinition.Save(saveEffectDialog.FileName); } } } }
// // SqlMoneyTest.cs - NUnit Test Cases for System.Data.SqlTypes.SqlMoney // // Authors: // Ville Palo (vi64pa@koti.soon.fi) // Martin Willemoes Hansen (mwh@sysrq.dk) // // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data.SqlTypes; using System.Threading; using System.Globalization; namespace MonoTests.System.Data.SqlTypes { [TestFixture] public class SqlMoneyTest : Assertion { private SqlMoney Test1; private SqlMoney Test2; private SqlMoney Test3; private SqlMoney Test4; [SetUp] public void GetReady() { Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US"); Test1 = new SqlMoney (6464.6464d); Test2 = new SqlMoney (90000.0m); Test3 = new SqlMoney (90000.0m); Test4 = new SqlMoney (-45000.0m); } // Test constructor [Test] public void Create() { try { SqlMoney Test = new SqlMoney (1000000000000000m); Fail ("#B01"); } catch (Exception e) { AssertEquals ("#A02", typeof (OverflowException), e.GetType ()); } SqlMoney CreationTest = new SqlMoney ((decimal)913.3); AssertEquals ("A03", 913.3000m, CreationTest.Value); try { SqlMoney Test = new SqlMoney (1e200); Fail ("#B04"); } catch (Exception e) { AssertEquals ("#A05", typeof (OverflowException), e.GetType ()); } SqlMoney CreationTest2 = new SqlMoney ((double)913.3); AssertEquals ("A06", 913.3000m, CreationTest2.Value); SqlMoney CreationTest3 = new SqlMoney ((int)913); AssertEquals ("A07", 913.0000m, CreationTest3.Value); SqlMoney CreationTest4 = new SqlMoney ((long)913.3); AssertEquals ("A08", 913.0000m, CreationTest4.Value); } // Test public fields [Test] public void PublicFields() { // FIXME: There is a error in msdn docs, it says thath MaxValue // is 922,337,203,685,475.5807 when the actual value is // 922,337,203,685,477.5807 AssertEquals ("#B01", 922337203685477.5807m, SqlMoney.MaxValue.Value); AssertEquals ("#B02", -922337203685477.5808m, SqlMoney.MinValue.Value); Assert ("#B03", SqlMoney.Null.IsNull); AssertEquals ("#B04", 0m, SqlMoney.Zero.Value); } // Test properties [Test] public void Properties() { AssertEquals ("#C01", 90000.0000m, Test2.Value); AssertEquals ("#C02", -45000.0000m, Test4.Value); Assert ("#C03", SqlMoney.Null.IsNull); } // PUBLIC METHODS [Test] public void ArithmeticMethods() { SqlMoney TestMoney2 = new SqlMoney (2); // Add AssertEquals ("#D01", (SqlMoney)96464.6464m, SqlMoney.Add (Test1, Test2)); AssertEquals ("#D02", (SqlMoney)180000m, SqlMoney.Add (Test2, Test2)); AssertEquals ("#D03", (SqlMoney)45000m, SqlMoney.Add (Test2, Test4)); try { SqlMoney test = SqlMoney.Add(SqlMoney.MaxValue, Test2); Fail ("#D04"); } catch (Exception e) { AssertEquals ("#D05", typeof (OverflowException), e.GetType ()); } // Divide AssertEquals ("#D06", (SqlMoney)45000m, SqlMoney.Divide (Test2, TestMoney2)); try { SqlMoney test = SqlMoney.Divide (Test2, SqlMoney.Zero); Fail ("#D07"); } catch (Exception e) { AssertEquals ("#D08", typeof (DivideByZeroException), e.GetType()); } // Multiply AssertEquals ("#D09", (SqlMoney)581818176m, SqlMoney.Multiply (Test1, Test2)); AssertEquals ("#D10", (SqlMoney)(-4050000000m), SqlMoney.Multiply (Test3, Test4)); try { SqlMoney test = SqlMoney.Multiply (SqlMoney.MaxValue, Test2); Fail ("#D11"); } catch (Exception e) { AssertEquals ("#D12", typeof (OverflowException), e.GetType ()); } // Subtract AssertEquals ("#D13", (SqlMoney)0m, SqlMoney.Subtract (Test2, Test3)); AssertEquals ("#D14", (SqlMoney)83535.3536m, SqlMoney.Subtract (Test2, Test1)); try { SqlMoney test = SqlMoney.Subtract (SqlMoney.MinValue, Test2); } catch (Exception e) { AssertEquals ("#D15", typeof (OverflowException), e.GetType ()); } } [Test] public void CompareTo() { Assert ("#E01", Test1.CompareTo (Test2) < 0); Assert ("#E02", Test3.CompareTo (Test1) > 0); Assert ("#E03", Test3.CompareTo (Test2) == 0); Assert ("#E04", Test3.CompareTo (SqlMoney.Null) > 0); } [Test] public void EqualsMethods() { Assert ("#F01", !Test1.Equals (Test2)); Assert ("#F02", Test2.Equals (Test3)); Assert ("#F03", !SqlMoney.Equals (Test1, Test2).Value); Assert ("#F04", SqlMoney.Equals (Test3, Test2).Value); } [Test] public void GetHashCodeTest() { // FIXME: Better way to test HashCode AssertEquals ("#G01", Test3.GetHashCode (), Test2.GetHashCode ()); Assert ("#G02", Test2.GetHashCode () != Test1.GetHashCode ()); } [Test] public void GetTypeTest() { AssertEquals ("#H01", "System.Data.SqlTypes.SqlMoney", Test1.GetType ().ToString ()); } [Test] public void Greaters() { // GreateThan () Assert ("#I01", !SqlMoney.GreaterThan (Test1, Test2).Value); Assert ("#I02", SqlMoney.GreaterThan (Test2, Test1).Value); Assert ("#I03", !SqlMoney.GreaterThan (Test2, Test3).Value); Assert ("#I04", SqlMoney.GreaterThan (Test2, SqlMoney.Null).IsNull); // GreaterTharOrEqual () Assert ("#I05", !SqlMoney.GreaterThanOrEqual (Test1, Test2).Value); Assert ("#I06", SqlMoney.GreaterThanOrEqual (Test2, Test1).Value); Assert ("#I07", SqlMoney.GreaterThanOrEqual (Test3, Test2).Value); Assert ("#I08", SqlMoney.GreaterThanOrEqual (Test3, SqlMoney.Null).IsNull); } [Test] public void Lessers() { // LessThan() Assert ("#J01", !SqlMoney.LessThan (Test2, Test3).Value); Assert ("#J02", !SqlMoney.LessThan (Test2, Test1).Value); Assert ("#J03", SqlMoney.LessThan (Test1, Test2).Value); Assert ("#J04", SqlMoney.LessThan (SqlMoney.Null, Test2).IsNull); // LessThanOrEqual () Assert ("#J05", SqlMoney.LessThanOrEqual (Test1, Test2).Value); Assert ("#J06", !SqlMoney.LessThanOrEqual (Test2, Test1).Value); Assert ("#J07", SqlMoney.LessThanOrEqual (Test2, Test2).Value); Assert ("#J08", SqlMoney.LessThanOrEqual (Test2, SqlMoney.Null).IsNull); } [Test] public void NotEquals() { Assert ("#K01", SqlMoney.NotEquals (Test1, Test2).Value); Assert ("#K02", SqlMoney.NotEquals (Test2, Test1).Value); Assert ("#K03", !SqlMoney.NotEquals (Test2, Test3).Value); Assert ("#K04", !SqlMoney.NotEquals (Test3, Test2).Value); Assert ("#K05", SqlMoney.NotEquals (SqlMoney.Null, Test2).IsNull); } [Test] public void Parse() { try { SqlMoney.Parse (null); Fail ("#L01"); } catch (Exception e) { AssertEquals ("#L02", typeof (ArgumentNullException), e.GetType ()); } try { SqlMoney.Parse ("not-a-number"); Fail ("#L03"); } catch (Exception e) { AssertEquals ("#L04", typeof (FormatException), e.GetType ()); } try { SqlMoney.Parse ("1000000000000000"); Fail ("#L05"); } catch (Exception e) { AssertEquals ("#L06", typeof (OverflowException), e.GetType ()); } AssertEquals("#L07", 150.0000M, SqlMoney.Parse ("150").Value); } [Test] public void Conversions() { SqlMoney TestMoney100 = new SqlMoney (100); // ToDecimal AssertEquals ("#M01", (decimal)6464.6464, Test1.ToDecimal ()); // ToDouble AssertEquals ("#M02", (double)6464.6464, Test1.ToDouble ()); // ToInt32 AssertEquals ("#M03", (int)90000, Test2.ToInt32 ()); AssertEquals ("#M04", (int)6465, Test1.ToInt32 ()); // ToInt64 AssertEquals ("#M05", (long)90000, Test2.ToInt64 ()); AssertEquals ("#M06", (long)6465, Test1.ToInt64 ()); // ToSqlBoolean () Assert ("#M07", Test1.ToSqlBoolean ().Value); Assert ("#M08", !SqlMoney.Zero.ToSqlBoolean ().Value); Assert ("#M09", SqlMoney.Null.ToSqlBoolean ().IsNull); // ToSqlByte () AssertEquals ("#M10", (byte)100, TestMoney100.ToSqlByte ().Value); try { SqlByte b = (byte)Test2.ToSqlByte (); Fail ("#M11"); } catch (Exception e) { AssertEquals ("#M12", typeof (OverflowException), e.GetType ()); } // ToSqlDecimal () AssertEquals ("#M13", (decimal)6464.6464, Test1.ToSqlDecimal ().Value); AssertEquals ("#M14", -45000.0000m, Test4.ToSqlDecimal ().Value); // ToSqlInt16 () AssertEquals ("#M15", (short)6465, Test1.ToSqlInt16 ().Value); try { SqlInt16 test = SqlMoney.MaxValue.ToSqlInt16().Value; Fail ("#M17"); } catch (Exception e) { AssertEquals ("#M18", typeof (OverflowException), e.GetType ()); } // ToSqlInt32 () AssertEquals ("#M19", (int)6465, Test1.ToSqlInt32 ().Value); AssertEquals ("#M20", (int)(-45000), Test4.ToSqlInt32 ().Value); try { SqlInt32 test = SqlMoney.MaxValue.ToSqlInt32 ().Value; Fail ("#M21"); } catch (Exception e) { AssertEquals ("#M22", typeof (OverflowException), e.GetType ()); } // ToSqlInt64 () AssertEquals ("#M23", (long)6465, Test1.ToSqlInt64 ().Value); AssertEquals ("#M24", (long)(-45000), Test4.ToSqlInt64 ().Value); // ToSqlSingle () AssertEquals ("#M25", (float)6464.6464, Test1.ToSqlSingle ().Value); // ToSqlString () AssertEquals ("#M26", "6464.6464", Test1.ToSqlString ().Value); AssertEquals ("#M27", "90000.0000", Test2.ToSqlString ().Value); // ToString () AssertEquals ("#M28", "6464.6464", Test1.ToString ()); AssertEquals ("#M29", "90000.0000", Test2.ToString ()); } // OPERATORS [Test] public void ArithmeticOperators() { // "+"-operator AssertEquals ("#N01", (SqlMoney)96464.6464m, Test1 + Test2); try { SqlMoney test = SqlMoney.MaxValue + SqlMoney.MaxValue; Fail ("#N02"); } catch (Exception e) { AssertEquals ("#N03", typeof (OverflowException), e.GetType ()); } // "/"-operator AssertEquals ("#N04", (SqlMoney)13.9219m, Test2 / Test1); try { SqlMoney test = Test3 / SqlMoney.Zero; Fail ("#N05"); } catch (Exception e) { AssertEquals ("#N06", typeof (DivideByZeroException), e.GetType ()); } // "*"-operator AssertEquals ("#N07", (SqlMoney)581818176m, Test1 * Test2); try { SqlMoney test = SqlMoney.MaxValue * Test1; Fail ("#N08"); } catch (Exception e) { AssertEquals ("#N09", typeof (OverflowException), e.GetType ()); } // "-"-operator AssertEquals ("#N10", (SqlMoney)83535.3536m, Test2 - Test1); try { SqlMoney test = SqlMoney.MinValue - SqlMoney.MaxValue; Fail ("#N11"); } catch (Exception e) { AssertEquals ("#N12", typeof (OverflowException), e.GetType ()); } } [Test] public void ThanOrEqualOperators() { // == -operator Assert ("#O01", (Test2 == Test2).Value); Assert ("#O02", !(Test1 == Test2).Value); Assert ("#O03", (Test1 == SqlMoney.Null).IsNull); // != -operator Assert ("#O04", !(Test2 != Test3).Value); Assert ("#O05", (Test1 != Test3).Value); Assert ("#O06", (Test1 != Test4).Value); Assert ("#O07", (Test1 != SqlMoney.Null).IsNull); // > -operator Assert ("#O08", (Test1 > Test4).Value); Assert ("#O09", (Test2 > Test1).Value); Assert ("#O10", !(Test2 > Test3).Value); Assert ("#O11", (Test1 > SqlMoney.Null).IsNull); // >= -operator Assert ("#O12", !(Test1 >= Test3).Value); Assert ("#O13", (Test3 >= Test1).Value); Assert ("#O14", (Test2 >= Test3).Value); Assert ("#O15", (Test1 >= SqlMoney.Null).IsNull); // < -operator Assert ("#O16", !(Test2 < Test1).Value); Assert ("#O17", (Test1 < Test3).Value); Assert ("#O18", !(Test2 < Test3).Value); Assert ("#O19", (Test1 < SqlMoney.Null).IsNull); // <= -operator Assert ("#O20", (Test1 <= Test3).Value); Assert ("#O21", !(Test3 <= Test1).Value); Assert ("#O22", (Test2 <= Test3).Value); Assert ("#O23", (Test1 <= SqlMoney.Null).IsNull); } [Test] public void UnaryNegation() { AssertEquals ("#P01", (decimal)(-6464.6464), -(Test1).Value); AssertEquals ("#P02", 45000.0000M, -(Test4).Value); } [Test] public void SqlBooleanToSqlMoney() { SqlBoolean TestBoolean = new SqlBoolean (true); AssertEquals ("#Q01", 1.0000M, ((SqlMoney)TestBoolean).Value); Assert ("#Q02", ((SqlDecimal)SqlBoolean.Null).IsNull); } [Test] public void SqlDecimalToSqlMoney() { SqlDecimal TestDecimal = new SqlDecimal (4000); SqlDecimal TestDecimal2 = new SqlDecimal (1E+20); SqlMoney TestMoney = (SqlMoney)TestDecimal; AssertEquals ("#R01", 4000.0000M,TestMoney.Value); try { SqlMoney test = (SqlMoney)TestDecimal2; Fail ("#R02"); } catch (Exception e) { AssertEquals ("#R03", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlDoubleToSqlMoney() { SqlDouble TestDouble = new SqlDouble (1E+9); SqlDouble TestDouble2 = new SqlDouble (1E+20); SqlMoney TestMoney = (SqlMoney)TestDouble; AssertEquals ("#S01", 1000000000.0000m, TestMoney.Value); try { SqlMoney test = (SqlMoney)TestDouble2; Fail ("#S02"); } catch (Exception e) { AssertEquals ("#S03", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlMoneyToDecimal() { AssertEquals ("#T01", (decimal)6464.6464, (decimal)Test1); AssertEquals ("#T02", -45000.0000M, (decimal)Test4); } [Test] public void SqlSingleToSqlMoney() { SqlSingle TestSingle = new SqlSingle (1e10); SqlSingle TestSingle2 = new SqlSingle (1e20); AssertEquals ("#U01", 10000000000.0000m, ((SqlMoney)TestSingle).Value); try { SqlMoney test = (SqlMoney)TestSingle2; Fail ("#U02"); } catch (Exception e) { AssertEquals ("#U03", typeof (OverflowException), e.GetType()); } } [Test] public void SqlStringToSqlMoney() { SqlString TestString = new SqlString ("Test string"); SqlString TestString100 = new SqlString ("100"); AssertEquals ("#V01", 100.0000M, ((SqlMoney)TestString100).Value); try { SqlMoney test = (SqlMoney)TestString; Fail ("#V02"); } catch(Exception e) { AssertEquals ("#V03", typeof (FormatException), e.GetType ()); } } [Test] public void DecimalToSqlMoney() { decimal TestDecimal = 1e10m; decimal TestDecimal2 = 1e20m; AssertEquals ("#W01", 10000000000.0000M, ((SqlMoney)TestDecimal).Value); try { SqlMoney test = (SqlMoney)TestDecimal2; Fail ("#W02"); } catch (Exception e) { AssertEquals ("#W03", typeof (OverflowException), e.GetType ()); } } [Test] public void SqlByteToSqlMoney() { SqlByte TestByte = new SqlByte ((byte)200); AssertEquals ("#X01", 200.0000m, ((SqlMoney)TestByte).Value); } [Test] public void IntsToSqlMoney() { SqlInt16 TestInt16 = new SqlInt16 (5000); SqlInt32 TestInt32 = new SqlInt32 (5000); SqlInt64 TestInt64 = new SqlInt64 (5000); AssertEquals ("#Y01", 5000.0000m, ((SqlMoney)TestInt16).Value); AssertEquals ("#Y02", 5000.0000m, ((SqlMoney)TestInt32).Value); AssertEquals ("#Y03", 5000.0000m, ((SqlMoney)TestInt64).Value); try { SqlMoney test = (SqlMoney)SqlInt64.MaxValue; Fail ("#Y04"); } catch (Exception e) { AssertEquals ("#Y05", typeof (OverflowException), e.GetType ()); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Interfaces; using log4net; namespace OpenSim.Region.ScriptEngine.XEngine { /// <summary> /// Prepares events so they can be directly executed upon a script by EventQueueManager, then queues it. /// </summary> public class EventManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private XEngine myScriptEngine; public EventManager(XEngine _ScriptEngine) { myScriptEngine = _ScriptEngine; m_log.Info("[XEngine] Hooking up to server events"); myScriptEngine.World.EventManager.OnAttach += attach; myScriptEngine.World.EventManager.OnObjectGrab += touch_start; myScriptEngine.World.EventManager.OnObjectGrabbing += touch; myScriptEngine.World.EventManager.OnObjectDeGrab += touch_end; myScriptEngine.World.EventManager.OnScriptChangedEvent += changed; myScriptEngine.World.EventManager.OnScriptAtTargetEvent += at_target; myScriptEngine.World.EventManager.OnScriptNotAtTargetEvent += not_at_target; myScriptEngine.World.EventManager.OnScriptAtRotTargetEvent += at_rot_target; myScriptEngine.World.EventManager.OnScriptNotAtRotTargetEvent += not_at_rot_target; myScriptEngine.World.EventManager.OnScriptControlEvent += control; myScriptEngine.World.EventManager.OnScriptColliderStart += collision_start; myScriptEngine.World.EventManager.OnScriptColliding += collision; myScriptEngine.World.EventManager.OnScriptCollidingEnd += collision_end; myScriptEngine.World.EventManager.OnScriptLandColliderStart += land_collision_start; myScriptEngine.World.EventManager.OnScriptLandColliding += land_collision; myScriptEngine.World.EventManager.OnScriptLandColliderEnd += land_collision_end; IMoneyModule money=myScriptEngine.World.RequestModuleInterface<IMoneyModule>(); if (money != null) { money.OnObjectPaid+=HandleObjectPaid; } } /// <summary> /// When an object gets paid by an avatar and generates the paid event, /// this will pipe it to the script engine /// </summary> /// <param name="objectID">Object ID that got paid</param> /// <param name="agentID">Agent Id that did the paying</param> /// <param name="amount">Amount paid</param> private void HandleObjectPaid(UUID objectID, UUID agentID, int amount) { // Since this is an event from a shared module, all scenes will // get it. But only one has the object in question. The others // just ignore it. // SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(objectID); if (part == null) return; m_log.Debug("Paid: " + objectID + " from " + agentID + ", amount " + amount); if (part.ParentGroup != null) part = part.ParentGroup.RootPart; if (part != null) { money(part.LocalId, agentID, amount); } } /// <summary> /// Handles piping the proper stuff to The script engine for touching /// Including DetectedParams /// </summary> /// <param name="localID"></param> /// <param name="originalID"></param> /// <param name="offsetPos"></param> /// <param name="remoteClient"></param> /// <param name="surfaceArgs"></param> public void touch_start(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_start", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void touch(uint localID, uint originalID, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); det[0].OffsetPos = new LSL_Types.Vector3(offsetPos.X, offsetPos.Y, offsetPos.Z); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void touch_end(uint localID, uint originalID, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { // Add to queue for all scripts in ObjectID object DetectParams[] det = new DetectParams[1]; det[0] = new DetectParams(); det[0].Key = remoteClient.AgentId; det[0].Populate(myScriptEngine.World); if (originalID == 0) { SceneObjectPart part = myScriptEngine.World.GetSceneObjectPart(localID); if (part == null) return; det[0].LinkNum = part.LinkNum; } else { SceneObjectPart originalPart = myScriptEngine.World.GetSceneObjectPart(originalID); det[0].LinkNum = originalPart.LinkNum; } if (surfaceArgs != null) { det[0].SurfaceTouchArgs = surfaceArgs; } myScriptEngine.PostObjectEvent(localID, new EventParams( "touch_end", new Object[] { new LSL_Types.LSLInteger(1) }, det)); } public void changed(uint localID, uint change) { // Add to queue for all scripts in localID, Object pass change. myScriptEngine.PostObjectEvent(localID, new EventParams( "changed",new object[] { new LSL_Types.LSLInteger(change) }, new DetectParams[0])); } // state_entry: not processed here // state_exit: not processed here public void money(uint localID, UUID agentID, int amount) { myScriptEngine.PostObjectEvent(localID, new EventParams( "money", new object[] { new LSL_Types.LSLString(agentID.ToString()), new LSL_Types.LSLInteger(amount) }, new DetectParams[0])); } public void collision_start(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_start", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void collision(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void collision_end(uint localID, ColliderArgs col) { // Add to queue for all scripts in ObjectID object List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Key =detobj.keyUUID; d.Populate(myScriptEngine.World); det.Add(d); } if (det.Count > 0) myScriptEngine.PostObjectEvent(localID, new EventParams( "collision_end", new Object[] { new LSL_Types.LSLInteger(det.Count) }, det.ToArray())); } public void land_collision_start(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = new LSL_Types.Vector3(detobj.posVector.X, detobj.posVector.Y, detobj.posVector.Z); d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_start", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } public void land_collision(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = new LSL_Types.Vector3(detobj.posVector.X, detobj.posVector.Y, detobj.posVector.Z); d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } public void land_collision_end(uint localID, ColliderArgs col) { List<DetectParams> det = new List<DetectParams>(); foreach (DetectedObject detobj in col.Colliders) { DetectParams d = new DetectParams(); d.Position = new LSL_Types.Vector3(detobj.posVector.X, detobj.posVector.Y, detobj.posVector.Z); d.Populate(myScriptEngine.World); det.Add(d); myScriptEngine.PostObjectEvent(localID, new EventParams( "land_collision_end", new Object[] { new LSL_Types.Vector3(d.Position) }, det.ToArray())); } } // timer: not handled here // listen: not handled here public void control(uint localID, UUID itemID, UUID agentID, uint held, uint change) { myScriptEngine.PostObjectEvent(localID, new EventParams( "control",new object[] { new LSL_Types.LSLString(agentID.ToString()), new LSL_Types.LSLInteger(held), new LSL_Types.LSLInteger(change)}, new DetectParams[0])); } public void email(uint localID, UUID itemID, string timeSent, string address, string subject, string message, int numLeft) { myScriptEngine.PostObjectEvent(localID, new EventParams( "email",new object[] { new LSL_Types.LSLString(timeSent), new LSL_Types.LSLString(address), new LSL_Types.LSLString(subject), new LSL_Types.LSLString(message), new LSL_Types.LSLInteger(numLeft)}, new DetectParams[0])); } public void at_target(uint localID, uint handle, Vector3 targetpos, Vector3 atpos) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_target", new object[] { new LSL_Types.LSLInteger(handle), new LSL_Types.Vector3(targetpos.X,targetpos.Y,targetpos.Z), new LSL_Types.Vector3(atpos.X,atpos.Y,atpos.Z) }, new DetectParams[0])); } public void not_at_target(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_target",new object[0], new DetectParams[0])); } public void at_rot_target(uint localID, uint handle, Quaternion targetrot, Quaternion atrot) { myScriptEngine.PostObjectEvent(localID, new EventParams( "at_rot_target", new object[] { new LSL_Types.LSLInteger(handle), new LSL_Types.Quaternion(targetrot.X,targetrot.Y,targetrot.Z,targetrot.W), new LSL_Types.Quaternion(atrot.X,atrot.Y,atrot.Z,atrot.W) }, new DetectParams[0])); } public void not_at_rot_target(uint localID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "not_at_rot_target",new object[0], new DetectParams[0])); } // run_time_permissions: not handled here public void attach(uint localID, UUID itemID, UUID avatar) { myScriptEngine.PostObjectEvent(localID, new EventParams( "attach",new object[] { new LSL_Types.LSLString(avatar.ToString()) }, new DetectParams[0])); } // dataserver: not handled here // link_message: not handled here public void moving_start(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_start",new object[0], new DetectParams[0])); } public void moving_end(uint localID, UUID itemID) { myScriptEngine.PostObjectEvent(localID, new EventParams( "moving_end",new object[0], new DetectParams[0])); } // object_rez: not handled here // remote_data: not handled here // http_response: not handled here } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using Xunit; namespace System.Threading.Tests { public static class ExecutionContextTests { [Fact] public static void CreateCopyTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var asyncLocal = new AsyncLocal<int>(); ExecutionContext executionContext = ExecutionContext.Capture(); VerifyExecutionContext(executionContext, asyncLocal, 0); executionContext = ExecutionContext.Capture(); ExecutionContext executionContextCopy0 = executionContext.CreateCopy(); asyncLocal.Value = 1; executionContext = ExecutionContext.Capture(); VerifyExecutionContext(executionContext, asyncLocal, 1); VerifyExecutionContext(executionContextCopy0, asyncLocal, 0); executionContext = ExecutionContext.Capture(); ExecutionContext executionContextCopy1 = executionContext.CreateCopy(); VerifyExecutionContext(executionContextCopy1, asyncLocal, 1); }); } [Fact] public static void DisposeTest() { ExecutionContext executionContext = ExecutionContext.Capture(); executionContext.CreateCopy().Dispose(); executionContext.CreateCopy().Dispose(); } [Fact] public static void SerializationTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 1; ExecutionContext executionContext = ExecutionContext.Capture(); VerifyExecutionContext(executionContext, asyncLocal, 1); Assert.Throws<ArgumentNullException>(() => executionContext.GetObjectData(null, new StreamingContext())); var binaryFormatter = new BinaryFormatter(); var memoryStream = new MemoryStream(); binaryFormatter.Serialize(memoryStream, executionContext); memoryStream.Close(); byte[] binaryData = memoryStream.ToArray(); memoryStream = new MemoryStream(binaryData); executionContext = (ExecutionContext)binaryFormatter.Deserialize(memoryStream); memoryStream.Close(); }); } [Fact] public static void FlowTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 1; var asyncFlowControl = default(AsyncFlowControl); Action<Action, Action> verifySuppressRestore = (suppressFlow, restoreFlow) => { VerifyExecutionContextFlow(asyncLocal, 1); ExecutionContext executionContext2 = ExecutionContext.Capture(); suppressFlow(); VerifyExecutionContextFlow(asyncLocal, 0); VerifyExecutionContext(executionContext2, asyncLocal, 1); executionContext2 = ExecutionContext.Capture(); restoreFlow(); VerifyExecutionContextFlow(asyncLocal, 1); VerifyExecutionContext(executionContext2, asyncLocal, 0); }; verifySuppressRestore( () => asyncFlowControl = ExecutionContext.SuppressFlow(), () => asyncFlowControl.Undo()); verifySuppressRestore( () => asyncFlowControl = ExecutionContext.SuppressFlow(), () => asyncFlowControl.Dispose()); verifySuppressRestore( () => ExecutionContext.SuppressFlow(), () => ExecutionContext.RestoreFlow()); Assert.Throws<InvalidOperationException>(() => ExecutionContext.RestoreFlow()); asyncFlowControl = ExecutionContext.SuppressFlow(); Assert.Throws<InvalidOperationException>(() => ExecutionContext.SuppressFlow()); ThreadTestHelpers.RunTestInBackgroundThread(() => { ExecutionContext.SuppressFlow(); Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Undo()); Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Dispose()); ExecutionContext.RestoreFlow(); }); asyncFlowControl.Undo(); Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Undo()); Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Dispose()); // Changing an async local value does not prevent undoing a flow-suppressed execution context. In .NET Core, the // execution context is immutable, so changing an async local value changes the execution context instance, // contrary to the desktop framework. asyncFlowControl = ExecutionContext.SuppressFlow(); asyncLocal.Value = 2; asyncFlowControl.Undo(); VerifyExecutionContextFlow(asyncLocal, 2); asyncFlowControl = ExecutionContext.SuppressFlow(); asyncLocal.Value = 3; asyncFlowControl.Dispose(); VerifyExecutionContextFlow(asyncLocal, 3); ExecutionContext.SuppressFlow(); asyncLocal.Value = 4; ExecutionContext.RestoreFlow(); VerifyExecutionContextFlow(asyncLocal, 4); // An async flow control cannot be undone when a different execution context is applied. The desktop framework // mutates the execution context when its state changes, and only changes the instance when an execution context // is applied (for instance, through ExecutionContext.Run). The framework prevents a suppressed-flow execution // context from being applied by returning null from ExecutionContext.Capture, so the only type of execution // context that can be applied is one whose flow is not suppressed. After suppressing flow and changing an async // local's value, the desktop framework verifies that a different execution context has not been applied by // checking the execution context instance against the one saved from when flow was suppressed. In .NET Core, // since the execution context instance will change after changing the async local's value, it verifies that a // different execution context has not been applied, by instead ensuring that the current execution context's // flow is suppressed. { ExecutionContext executionContext = null; Action verifyCannotUndoAsyncFlowControlAfterChangingExecutionContext = () => { ExecutionContext.Run( executionContext, state => { Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Undo()); Assert.Throws<InvalidOperationException>(() => asyncFlowControl.Dispose()); }, null); }; executionContext = ExecutionContext.Capture(); asyncFlowControl = ExecutionContext.SuppressFlow(); verifyCannotUndoAsyncFlowControlAfterChangingExecutionContext(); asyncFlowControl.Undo(); executionContext = ExecutionContext.Capture(); asyncFlowControl = ExecutionContext.SuppressFlow(); asyncLocal.Value = 5; verifyCannotUndoAsyncFlowControlAfterChangingExecutionContext(); asyncFlowControl.Undo(); VerifyExecutionContextFlow(asyncLocal, 5); } }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] // desktop framework has a bug public static void CaptureThenSuppressThenRunFlowTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 1; ExecutionContext executionContext = ExecutionContext.Capture(); ExecutionContext.SuppressFlow(); ExecutionContext.Run( executionContext, state => { Assert.Equal(1, asyncLocal.Value); VerifyExecutionContextFlow(asyncLocal, 1); }, null); Assert.Equal(1, asyncLocal.Value); VerifyExecutionContextFlow(asyncLocal, 0); ExecutionContext.RestoreFlow(); VerifyExecutionContextFlow(asyncLocal, 1); executionContext = ExecutionContext.Capture(); asyncLocal.Value = 2; ExecutionContext.SuppressFlow(); Assert.True(ExecutionContext.IsFlowSuppressed()); ExecutionContext.Run( executionContext, state => { Assert.Equal(1, asyncLocal.Value); VerifyExecutionContextFlow(asyncLocal, 1); }, null); Assert.Equal(2, asyncLocal.Value); VerifyExecutionContextFlow(asyncLocal, 0); ExecutionContext.RestoreFlow(); VerifyExecutionContextFlow(asyncLocal, 2); }); } private static void VerifyExecutionContext( ExecutionContext executionContext, AsyncLocal<int> asyncLocal, int expectedValue) { int actualValue = 0; Action run = () => ExecutionContext.Run(executionContext, state => actualValue = asyncLocal.Value, null); if (executionContext == null) { Assert.Throws<InvalidOperationException>(() => run()); } else { run(); } Assert.Equal(expectedValue, actualValue); } private static void VerifyExecutionContextFlow(AsyncLocal<int> asyncLocal, int expectedValue) { Assert.Equal(expectedValue == 0, ExecutionContext.IsFlowSuppressed()); if (ExecutionContext.IsFlowSuppressed()) { Assert.Null(ExecutionContext.Capture()); } VerifyExecutionContext(ExecutionContext.Capture(), asyncLocal, expectedValue); int asyncLocalValue = -1; var done = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( state => { asyncLocalValue = asyncLocal.Value; done.Set(); }); done.CheckedWait(); Assert.Equal(expectedValue, asyncLocalValue); } [Fact] public static void AsyncFlowControlTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { Action<AsyncFlowControl, AsyncFlowControl, bool> verifyEquality = (afc0, afc1, areExpectedToBeEqual) => { Assert.Equal(areExpectedToBeEqual, afc0.Equals(afc1)); Assert.Equal(areExpectedToBeEqual, afc0.Equals((object)afc1)); Assert.Equal(areExpectedToBeEqual, afc0 == afc1); Assert.NotEqual(areExpectedToBeEqual, afc0 != afc1); }; AsyncFlowControl asyncFlowControl0 = ExecutionContext.SuppressFlow(); ExecutionContext.RestoreFlow(); AsyncFlowControl asyncFlowControl1 = ExecutionContext.SuppressFlow(); ExecutionContext.RestoreFlow(); verifyEquality(asyncFlowControl0, asyncFlowControl1, true); verifyEquality(asyncFlowControl1, asyncFlowControl0, true); var asyncLocal = new AsyncLocal<int>(); asyncLocal.Value = 1; asyncFlowControl1 = ExecutionContext.SuppressFlow(); ExecutionContext.RestoreFlow(); verifyEquality(asyncFlowControl0, asyncFlowControl1, true); verifyEquality(asyncFlowControl1, asyncFlowControl0, true); asyncFlowControl1 = new AsyncFlowControl(); verifyEquality(asyncFlowControl0, asyncFlowControl1, false); verifyEquality(asyncFlowControl1, asyncFlowControl0, false); ThreadTestHelpers.RunTestInBackgroundThread(() => asyncFlowControl1 = ExecutionContext.SuppressFlow()); verifyEquality(asyncFlowControl0, asyncFlowControl1, false); verifyEquality(asyncFlowControl1, asyncFlowControl0, false); }); } } }
using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; namespace Lucene.Net.Util { /// <summary> /// 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. /// </summary> [TestFixture] public class TestNumericUtils : LuceneTestCase { [Test] public virtual void TestLongConversionAndOrdering() { // generate a series of encoded longs, each numerical one bigger than the one before BytesRef last = null, act = new BytesRef(NumericUtils.BUF_SIZE_LONG); for (long l = -100000L; l < 100000L; l++) { NumericUtils.LongToPrefixCodedBytes(l, 0, act); if (last != null) { // test if smaller Assert.IsTrue(last.CompareTo(act) < 0, "actual bigger than last (BytesRef)"); //Assert.IsTrue(last.Utf8ToString().CompareTo(act.Utf8ToString()) < 0, "actual bigger than last (as String)"); } // test is back and forward conversion works Assert.AreEqual(l, NumericUtils.PrefixCodedToLong(act), "forward and back conversion should generate same long"); // next step last = act; act = new BytesRef(NumericUtils.BUF_SIZE_LONG); } } [Test] public virtual void TestIntConversionAndOrdering() { // generate a series of encoded ints, each numerical one bigger than the one before BytesRef last = null, act = new BytesRef(NumericUtils.BUF_SIZE_INT); for (int i = -100000; i < 100000; i++) { NumericUtils.IntToPrefixCodedBytes(i, 0, act); if (last != null) { // test if smaller Assert.IsTrue(last.CompareTo(act) < 0, "actual bigger than last (BytesRef)"); //Assert.IsTrue(last.Utf8ToString().CompareTo(act.Utf8ToString()) < 0, "actual bigger than last (as String)"); } // test is back and forward conversion works Assert.AreEqual(i, NumericUtils.PrefixCodedToInt(act), "forward and back conversion should generate same int"); // next step last = act; act = new BytesRef(NumericUtils.BUF_SIZE_INT); } } [Test] public virtual void TestLongSpecialValues() { long[] vals = new long[] { long.MinValue, long.MinValue + 1, long.MinValue + 2, -5003400000000L, -4000L, -3000L, -2000L, -1000L, -1L, 0L, 1L, 10L, 300L, 50006789999999999L, long.MaxValue - 2, long.MaxValue - 1, long.MaxValue }; BytesRef[] prefixVals = new BytesRef[vals.Length]; for (int i = 0; i < vals.Length; i++) { prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_LONG); NumericUtils.LongToPrefixCodedBytes(vals[i], 0, prefixVals[i]); // check forward and back conversion Assert.AreEqual(vals[i], NumericUtils.PrefixCodedToLong(prefixVals[i]), "forward and back conversion should generate same long"); // test if decoding values as int fails correctly try { NumericUtils.PrefixCodedToInt(prefixVals[i]); Assert.Fail("decoding a prefix coded long value as int should fail"); } catch (FormatException e) { // worked } } // check sort order (prefixVals should be ascending) for (int i = 1; i < prefixVals.Length; i++) { Assert.IsTrue(prefixVals[i - 1].CompareTo(prefixVals[i]) < 0, "check sort order"); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits BytesRef @ref = new BytesRef(NumericUtils.BUF_SIZE_LONG); for (int i = 0; i < vals.Length; i++) { for (int j = 0; j < 64; j++) { NumericUtils.LongToPrefixCodedBytes(vals[i], j, @ref); long prefixVal = NumericUtils.PrefixCodedToLong(@ref); long mask = (1L << j) - 1L; Assert.AreEqual(vals[i] & mask, vals[i] - prefixVal, "difference between prefix val and original value for " + vals[i] + " with shift=" + j); } } } [Test] public virtual void TestIntSpecialValues() { int[] vals = new int[] { int.MinValue, int.MinValue + 1, int.MinValue + 2, -64765767, -4000, -3000, -2000, -1000, -1, 0, 1, 10, 300, 765878989, int.MaxValue - 2, int.MaxValue - 1, int.MaxValue }; BytesRef[] prefixVals = new BytesRef[vals.Length]; for (int i = 0; i < vals.Length; i++) { prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_INT); NumericUtils.IntToPrefixCodedBytes(vals[i], 0, prefixVals[i]); // check forward and back conversion Assert.AreEqual(vals[i], NumericUtils.PrefixCodedToInt(prefixVals[i]), "forward and back conversion should generate same int"); // test if decoding values as long fails correctly try { NumericUtils.PrefixCodedToLong(prefixVals[i]); Assert.Fail("decoding a prefix coded int value as long should fail"); } catch (FormatException e) { // worked } } // check sort order (prefixVals should be ascending) for (int i = 1; i < prefixVals.Length; i++) { Assert.IsTrue(prefixVals[i - 1].CompareTo(prefixVals[i]) < 0, "check sort order"); } // check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits BytesRef @ref = new BytesRef(NumericUtils.BUF_SIZE_LONG); for (int i = 0; i < vals.Length; i++) { for (int j = 0; j < 32; j++) { NumericUtils.IntToPrefixCodedBytes(vals[i], j, @ref); int prefixVal = NumericUtils.PrefixCodedToInt(@ref); int mask = (1 << j) - 1; Assert.AreEqual(vals[i] & mask, vals[i] - prefixVal, "difference between prefix val and original value for " + vals[i] + " with shift=" + j); } } } [Test] public virtual void TestDoubles() { double[] vals = new double[] { double.NegativeInfinity, -2.3E25, -1.0E15, -1.0, -1.0E-1, -1.0E-2, -0.0, +0.0, 1.0E-2, 1.0E-1, 1.0, 1.0E15, 2.3E25, double.PositiveInfinity, double.NaN }; long[] longVals = new long[vals.Length]; // check forward and back conversion for (int i = 0; i < vals.Length; i++) { longVals[i] = NumericUtils.DoubleToSortableLong(vals[i]); Assert.IsTrue(vals[i].CompareTo(NumericUtils.SortableLongToDouble(longVals[i])) == 0, "forward and back conversion should generate same double"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < longVals.Length; i++) { Assert.IsTrue(longVals[i - 1] < longVals[i], "check sort order"); } } public static readonly double[] DOUBLE_NANs = new double[] { double.NaN, BitConverter.Int64BitsToDouble(0x7ff0000000000001L), BitConverter.Int64BitsToDouble(0x7fffffffffffffffL), BitConverter.Int64BitsToDouble(unchecked((long)0xfff0000000000001L)), BitConverter.Int64BitsToDouble(unchecked((long)0xffffffffffffffffL)) }; [Test] public virtual void TestSortableDoubleNaN() { long plusInf = NumericUtils.DoubleToSortableLong(double.PositiveInfinity); foreach (double nan in DOUBLE_NANs) { Assert.IsTrue(double.IsNaN(nan)); long sortable = NumericUtils.DoubleToSortableLong(nan); Assert.IsTrue((ulong)sortable > (ulong)plusInf, "Double not sorted correctly: " + nan + ", long repr: " + sortable + ", positive inf.: " + plusInf); } } [Test] public virtual void TestFloats() { float[] vals = new float[] { float.NegativeInfinity, -2.3E25f, -1.0E15f, -1.0f, -1.0E-1f, -1.0E-2f, -0.0f, +0.0f, 1.0E-2f, 1.0E-1f, 1.0f, 1.0E15f, 2.3E25f, float.PositiveInfinity, float.NaN }; int[] intVals = new int[vals.Length]; // check forward and back conversion for (int i = 0; i < vals.Length; i++) { intVals[i] = NumericUtils.FloatToSortableInt(vals[i]); Assert.IsTrue(vals[i].CompareTo(NumericUtils.SortableIntToFloat(intVals[i])) == 0, "forward and back conversion should generate same double"); } // check sort order (prefixVals should be ascending) for (int i = 1; i < intVals.Length; i++) { Assert.IsTrue(intVals[i - 1] < intVals[i], "check sort order"); } } public static readonly float[] FLOAT_NANs = new float[] { float.NaN, Number.IntBitsToFloat(0x7f800001), Number.IntBitsToFloat(0x7fffffff), Number.IntBitsToFloat(unchecked((int)0xff800001)), Number.IntBitsToFloat(unchecked((int)0xffffffff)) }; [Test] public virtual void TestSortableFloatNaN() { int plusInf = NumericUtils.FloatToSortableInt(float.PositiveInfinity); foreach (float nan in FLOAT_NANs) { Assert.IsTrue(float.IsNaN(nan)); uint sortable = (uint)NumericUtils.FloatToSortableInt(nan); Assert.IsTrue(sortable > plusInf, "Float not sorted correctly: " + nan + ", int repr: " + sortable + ", positive inf.: " + plusInf); } } // INFO: Tests for trieCodeLong()/trieCodeInt() not needed because implicitely tested by range filter tests /// <summary> /// Note: The neededBounds Iterable must be unsigned (easier understanding what's happening) </summary> private void AssertLongRangeSplit(long lower, long upper, int precisionStep, bool useBitSet, IEnumerable<long> expectedBounds, IEnumerable<int> expectedShifts) { // Cannot use FixedBitSet since the range could be long: LongBitSet bits = useBitSet ? new LongBitSet(upper - lower + 1) : null; IEnumerator<long> neededBounds = (expectedBounds == null) ? null : expectedBounds.GetEnumerator(); IEnumerator<int> neededShifts = (expectedShifts == null) ? null : expectedShifts.GetEnumerator(); NumericUtils.SplitLongRange(new LongRangeBuilderAnonymousInnerClassHelper(this, lower, upper, useBitSet, bits, neededBounds, neededShifts), precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.Flip(0, upper - lower + 1); Assert.AreEqual(0, bits.Cardinality(), "The sub-range concenated should match the whole range"); } } private class LongRangeBuilderAnonymousInnerClassHelper : NumericUtils.LongRangeBuilder { private readonly TestNumericUtils OuterInstance; private long Lower; private long Upper; private bool UseBitSet; private LongBitSet Bits; private IEnumerator<long> NeededBounds; private IEnumerator<int> NeededShifts; public LongRangeBuilderAnonymousInnerClassHelper(TestNumericUtils outerInstance, long lower, long upper, bool useBitSet, LongBitSet bits, IEnumerator<long> neededBounds, IEnumerator<int> neededShifts) { this.OuterInstance = outerInstance; this.Lower = lower; this.Upper = upper; this.UseBitSet = useBitSet; this.Bits = bits; this.NeededBounds = neededBounds; this.NeededShifts = neededShifts; } public override void AddRange(long min, long max, int shift) { Assert.IsTrue(min >= Lower && min <= Upper && max >= Lower && max <= Upper, "min, max should be inside bounds"); if (UseBitSet) { for (long l = min; l <= max; l++) { Assert.IsFalse(Bits.GetAndSet(l - Lower), "ranges should not overlap"); // extra exit condition to prevent overflow on MAX_VALUE if (l == max) { break; } } } if (NeededBounds == null || NeededShifts == null) { return; } // make unsigned longs for easier display and understanding min ^= unchecked((long)0x8000000000000000L); max ^= unchecked((long)0x8000000000000000L); //System.out.println("0x"+Long.toHexString(min>>>shift)+"L,0x"+Long.toHexString(max>>>shift)+"L)/*shift="+shift+"*/,"); NeededShifts.MoveNext(); Assert.AreEqual(NeededShifts.Current, shift, "shift"); NeededBounds.MoveNext(); Assert.AreEqual(NeededBounds.Current, (long)((ulong)min >> shift), "inner min bound"); NeededBounds.MoveNext(); Assert.AreEqual(NeededBounds.Current, (long)((ulong)max >> shift), "inner max bound"); } } /// <summary> /// LUCENE-2541: NumericRangeQuery errors with endpoints near long min and max values </summary> [Test] public virtual void TestLongExtremeValues() { // upper end extremes AssertLongRangeSplit(long.MaxValue, long.MaxValue, 1, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 2, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 4, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 6, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 8, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue, long.MaxValue, 64, true, Arrays.AsList(unchecked((long)0xffffffffffffffffL), unchecked((long)0xffffffffffffffffL)), Arrays.AsList(0)); AssertLongRangeSplit(long.MaxValue - 0xfL, long.MaxValue, 4, true, Arrays.AsList(0xfffffffffffffffL, 0xfffffffffffffffL), Arrays.AsList(4)); AssertLongRangeSplit(long.MaxValue - 0x10L, long.MaxValue, 4, true, Arrays.AsList(unchecked((long)0xffffffffffffffefL), unchecked((long)0xffffffffffffffefL), 0xfffffffffffffffL, 0xfffffffffffffffL), Arrays.AsList(0, 4)); // lower end extremes AssertLongRangeSplit(long.MinValue, long.MinValue, 1, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue, 2, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue, 4, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue, 6, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue, 8, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue, 64, true, Arrays.AsList(0x0000000000000000L, 0x0000000000000000L), Arrays.AsList(0)); AssertLongRangeSplit(long.MinValue, long.MinValue + 0xfL, 4, true, Arrays.AsList(0x000000000000000L, 0x000000000000000L), Arrays.AsList(4)); AssertLongRangeSplit(long.MinValue, long.MinValue + 0x10L, 4, true, Arrays.AsList(0x0000000000000010L, 0x0000000000000010L, 0x000000000000000L, 0x000000000000000L), Arrays.AsList(0, 4)); } [Test] public virtual void TestRandomSplit() { long num = (long)AtLeast(10); for (long i = 0; i < num; i++) { ExecuteOneRandomSplit(Random()); } } private void ExecuteOneRandomSplit(Random random) { long lower = RandomLong(random); long len = random.Next(16384 * 1024); // not too large bitsets, else OOME! while (lower + len < lower) // overflow { lower >>= 1; } AssertLongRangeSplit(lower, lower + len, random.Next(64) + 1, true, null, null); } private long RandomLong(Random random) { long val; switch (random.Next(4)) { case 0: val = 1L << (random.Next(63)); // patterns like 0x000000100000 (-1 yields patterns like 0x0000fff) break; case 1: val = -1L << (random.Next(63)); // patterns like 0xfffff00000 break; default: val = random.NextLong(); break; } val += random.Next(5) - 2; if (random.NextBoolean()) { if (random.NextBoolean()) { val += random.Next(100) - 50; } if (random.NextBoolean()) { val = ~val; } if (random.NextBoolean()) { val = val << 1; } if (random.NextBoolean()) { val = (long)((ulong)val >> 1); } } return val; } [Test] public virtual void TestSplitLongRange() { // a hard-coded "standard" range AssertLongRangeSplit(-5000L, 9500L, 4, true, new long[] { 0x7fffffffffffec78L, 0x7fffffffffffec7fL, unchecked((long)0x8000000000002510L), unchecked((long)0x800000000000251cL), 0x7fffffffffffec8L, 0x7fffffffffffecfL, 0x800000000000250L, 0x800000000000250L, 0x7fffffffffffedL, 0x7fffffffffffefL, 0x80000000000020L, 0x80000000000024L, 0x7ffffffffffffL, 0x8000000000001L }, new int[] { 0, 0, 4, 4, 8, 8, 12 }); // the same with no range splitting AssertLongRangeSplit(-5000L, 9500L, 64, true, new long[] { 0x7fffffffffffec78L, unchecked((long)0x800000000000251cL) }, new int[] { 0 }); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely AssertLongRangeSplit(0L, 1024L + 63L, 4, true, new long[] { 0x800000000000040L, 0x800000000000043L, 0x80000000000000L, 0x80000000000003L }, new int[] { 4, 8 }); // the full long range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) AssertLongRangeSplit(long.MinValue, long.MaxValue, 8, false, new long[] { 0x00L, 0xffL }, new int[] { 56 }); // the same with precisionStep=4 AssertLongRangeSplit(long.MinValue, long.MaxValue, 4, false, new long[] { 0x0L, 0xfL }, new int[] { 60 }); // the same with precisionStep=2 AssertLongRangeSplit(long.MinValue, long.MaxValue, 2, false, new long[] { 0x0L, 0x3L }, new int[] { 62 }); // the same with precisionStep=1 AssertLongRangeSplit(long.MinValue, long.MaxValue, 1, false, new long[] { 0x0L, 0x1L }, new int[] { 63 }); // a inverse range should produce no sub-ranges AssertLongRangeSplit(9500L, -5000L, 4, false, new long[] { }, new int[] { }); // a 0-length range should reproduce the range itself AssertLongRangeSplit(9500L, 9500L, 4, false, new long[] { unchecked((long)0x800000000000251cL), unchecked((long)0x800000000000251cL) }, new int[] { 0 }); } /// <summary> /// Note: The neededBounds Iterable must be unsigned (easier understanding what's happening) </summary> private void AssertIntRangeSplit(int lower, int upper, int precisionStep, bool useBitSet, IEnumerable<int> expectedBounds, IEnumerable<int> expectedShifts) { FixedBitSet bits = useBitSet ? new FixedBitSet(upper - lower + 1) : null; IEnumerator<int> neededBounds = (expectedBounds == null) ? null : expectedBounds.GetEnumerator(); IEnumerator<int> neededShifts = (expectedShifts == null) ? null : expectedShifts.GetEnumerator(); NumericUtils.SplitIntRange(new IntRangeBuilderAnonymousInnerClassHelper(this, lower, upper, useBitSet, bits, neededBounds, neededShifts), precisionStep, lower, upper); if (useBitSet) { // after flipping all bits in the range, the cardinality should be zero bits.Flip(0, upper - lower + 1); Assert.AreEqual(0, bits.Cardinality(), "The sub-range concenated should match the whole range"); } } private class IntRangeBuilderAnonymousInnerClassHelper : NumericUtils.IntRangeBuilder { private readonly TestNumericUtils OuterInstance; private int Lower; private int Upper; private bool UseBitSet; private FixedBitSet Bits; private IEnumerator<int> NeededBounds; private IEnumerator<int> NeededShifts; public IntRangeBuilderAnonymousInnerClassHelper(TestNumericUtils outerInstance, int lower, int upper, bool useBitSet, FixedBitSet bits, IEnumerator<int> neededBounds, IEnumerator<int> neededShifts) { this.OuterInstance = outerInstance; this.Lower = lower; this.Upper = upper; this.UseBitSet = useBitSet; this.Bits = bits; this.NeededBounds = neededBounds; this.NeededShifts = neededShifts; } public override void AddRange(int min, int max, int shift) { Assert.IsTrue(min >= Lower && min <= Upper && max >= Lower && max <= Upper, "min, max should be inside bounds"); if (UseBitSet) { for (int i = min; i <= max; i++) { Assert.IsFalse(Bits.GetAndSet(i - Lower), "ranges should not overlap"); // extra exit condition to prevent overflow on MAX_VALUE if (i == max) { break; } } } if (NeededBounds == null) { return; } // make unsigned ints for easier display and understanding min ^= unchecked((int)0x80000000); max ^= unchecked((int)0x80000000); //System.out.println("0x"+Integer.toHexString(min>>>shift)+",0x"+Integer.toHexString(max>>>shift)+")/*shift="+shift+"*/,"); NeededShifts.MoveNext(); Assert.AreEqual(NeededShifts.Current, shift, "shift"); NeededBounds.MoveNext(); Assert.AreEqual(NeededBounds.Current, (int)((uint)min >> shift), "inner min bound"); NeededBounds.MoveNext(); Assert.AreEqual(NeededBounds.Current, (int)((uint)max >> shift), "inner max bound"); } } [Test] public virtual void TestSplitIntRange() { // a hard-coded "standard" range AssertIntRangeSplit(-5000, 9500, 4, true, Arrays.AsList(0x7fffec78, 0x7fffec7f, unchecked((int)0x80002510), unchecked((int)0x8000251c), 0x7fffec8, 0x7fffecf, 0x8000250, 0x8000250, 0x7fffed, 0x7fffef, 0x800020, 0x800024, 0x7ffff, 0x80001), Arrays.AsList(0, 0, 4, 4, 8, 8, 12)); // the same with no range splitting AssertIntRangeSplit(-5000, 9500, 32, true, Arrays.AsList(0x7fffec78, unchecked((int)0x8000251c)), Arrays.AsList(0)); // this tests optimized range splitting, if one of the inner bounds // is also the bound of the next lower precision, it should be used completely AssertIntRangeSplit(0, 1024 + 63, 4, true, Arrays.AsList(0x8000040, 0x8000043, 0x800000, 0x800003), Arrays.AsList(4, 8)); // the full int range should only consist of a lowest precision range; no bitset testing here, as too much memory needed :-) AssertIntRangeSplit(int.MinValue, int.MaxValue, 8, false, Arrays.AsList(0x00, 0xff), Arrays.AsList(24)); // the same with precisionStep=4 AssertIntRangeSplit(int.MinValue, int.MaxValue, 4, false, Arrays.AsList(0x0, 0xf), Arrays.AsList(28)); // the same with precisionStep=2 AssertIntRangeSplit(int.MinValue, int.MaxValue, 2, false, Arrays.AsList(0x0, 0x3), Arrays.AsList(30)); // the same with precisionStep=1 AssertIntRangeSplit(int.MinValue, int.MaxValue, 1, false, Arrays.AsList(0x0, 0x1), Arrays.AsList(31)); // a inverse range should produce no sub-ranges AssertIntRangeSplit(9500, -5000, 4, false, new List<int>(), new List<int>()); // a 0-length range should reproduce the range itself AssertIntRangeSplit(9500, 9500, 4, false, Arrays.AsList(unchecked((int)0x8000251c), unchecked((int)0x8000251c)), Arrays.AsList(0)); } } }
using System; namespace Cocos2D { public class TextInputTest : CCLayer { KeyboardNotificationLayer m_pNotificationLayer; TextInputTestScene textinputTestScene = new TextInputTestScene(); public void restartCallback(object pSender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.restartTextInputTest()); CCDirector.SharedDirector.ReplaceScene(s); } public void nextCallback(object pSender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.nextTextInputTest()); CCDirector.SharedDirector.ReplaceScene(s); } public void backCallback(object pSender) { CCScene s = new TextInputTestScene(); s.AddChild(textinputTestScene.backTextInputTest()); CCDirector.SharedDirector.ReplaceScene(s); } public virtual string title() { return "text input test"; } public void addKeyboardNotificationLayer(KeyboardNotificationLayer pLayer) { m_pNotificationLayer = pLayer; AddChild(pLayer); } public override void OnEnter() { base.OnEnter(); CCSize s = CCDirector.SharedDirector.WinSize; CCLabelTTF label = new CCLabelTTF(title(), "arial", 24); AddChild(label); label.Position = new CCPoint(s.Width / 2, s.Height - 50); string subTitle = m_pNotificationLayer.subtitle(); if (subTitle != null) { CCLabelTTF l = new CCLabelTTF(subTitle, subtitle(), 16); AddChild(l, 1); l.Position = new CCPoint(s.Width / 2, s.Height - 80); } CCMenuItemImage item1 = new CCMenuItemImage("Images/b1.png", "Images/b2.png", backCallback); CCMenuItemImage item2 = new CCMenuItemImage("Images/r1.png", "Images/r2.png", restartCallback); CCMenuItemImage item3 = new CCMenuItemImage("Images/f1.png", "Images/f2.png", nextCallback); CCMenu menu = new CCMenu(item1, item2, item3); menu.Position = new CCPoint(0, 0); item1.Position = new CCPoint(s.Width / 2 - 100, 30); item2.Position = new CCPoint(s.Width / 2, 30); item3.Position = new CCPoint(s.Width / 2 + 100, 30); AddChild(menu, 1); } public virtual string subtitle() { return String.Empty; } } public class KeyboardNotificationLayer : CCLayer { public KeyboardNotificationLayer() { base.TouchEnabled = true; } public virtual string subtitle() { throw new NotFiniteNumberException(); } public virtual void onClickTrackNode(bool bClicked) { throw new NotFiniteNumberException(); } public override void RegisterWithTouchDispatcher() { CCDirector.SharedDirector.TouchDispatcher.AddTargetedDelegate(this, 0, false); } public override bool TouchBegan(CCTouch pTouch) { m_beginPos = pTouch.Location; return true; } public override void TouchEnded(CCTouch pTouch) { if (m_pTrackNode == null) { return; } var endPos = pTouch.Location; if (m_pTrackNode.BoundingBox.ContainsPoint(m_beginPos) && m_pTrackNode.BoundingBox.ContainsPoint(endPos)) { onClickTrackNode(true); } else { onClickTrackNode(false); } } protected CCTextFieldTTF m_pTrackNode; protected CCPoint m_beginPos; } public class TextFieldTTFDefaultTest : KeyboardNotificationLayer { public override void onClickTrackNode(bool bClicked) { if (bClicked && m_pTrackNode != null) { m_pTrackNode.Edit("CCTextFieldTTF test", "Enter text"); } } public override void OnEnter() { base.OnEnter(); var s = CCDirector.SharedDirector.WinSize; var pTextField = new CCTextFieldTTF( "<click here for input>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE ); pTextField.Position = CCDirector.SharedDirector.WinSize.Center; pTextField.AutoEdit = true; AddChild(pTextField); //m_pTrackNode = pTextField; } public override string subtitle() { return "TextFieldTTF with default behavior test"; } } ////////////////////////////////////////////////////////////////////////// // TextFieldTTFActionTest ////////////////////////////////////////////////////////////////////////// public class TextFieldTTFActionTest : KeyboardNotificationLayer { CCTextFieldTTF m_pTextField; CCAction m_pTextFieldAction; bool m_bAction; int m_nCharLimit; // the textfield max char limit public void callbackRemoveNodeWhenDidAction(CCNode node) { this.RemoveChild(node, true); } // KeyboardNotificationLayer public override string subtitle() { return "CCTextFieldTTF with action and char limit test"; } public override void onClickTrackNode(bool bClicked) { if (bClicked) { m_pTrackNode.Edit(); } else { m_pTrackNode.EndEdit(); } } // CCLayer public override void OnEnter() { base.OnEnter(); m_nCharLimit = 12; m_pTextFieldAction = new CCRepeatForever( (CCActionInterval) new CCSequence( new CCFadeOut(0.25f), new CCFadeIn(0.25f))); //m_pTextFieldAction->retain(); m_bAction = false; // add CCTextFieldTTF CCSize s = CCDirector.SharedDirector.WinSize; m_pTextField = new CCTextFieldTTF("<click here for input>", TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE); AddChild(m_pTextField); m_pTrackNode = m_pTextField; } // CCTextFieldDelegate public virtual bool onTextFieldAttachWithIME(CCTextFieldTTF pSender) { if (m_bAction != null) { m_pTextField.RunAction(m_pTextFieldAction); m_bAction = true; } return false; } public virtual bool onTextFieldDetachWithIME(CCTextFieldTTF pSender) { if (m_bAction != null) { m_pTextField.StopAction(m_pTextFieldAction); m_pTextField.Opacity = 255; m_bAction = false; } return false; } public virtual bool onTextFieldInsertText(CCTextFieldTTF pSender, string text, int nLen) { // if insert enter, treat as default to detach with ime if ("\n" == text) { return false; } // if the textfield's char count more than m_nCharLimit, doesn't insert text anymore. if (pSender.Text.Length >= m_nCharLimit) { return true; } // create a insert text sprite and do some action CCLabelTTF label = new CCLabelTTF(text, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE); this.AddChild(label); CCColor3B color = new CCColor3B { R = 226, G = 121, B = 7 }; label.Color = color; // move the sprite from top to position CCPoint endPos = pSender.Position; if (pSender.Text.Length > 0) { endPos.X += pSender.ContentSize.Width / 2; } CCSize inputTextSize = label.ContentSize; CCPoint beginPos = new CCPoint(endPos.X, CCDirector.SharedDirector.WinSize.Height - inputTextSize.Height * 2); float duration = 0.5f; label.Position = beginPos; label.Scale = 8; CCAction seq = new CCSequence( new CCSpawn( new CCMoveTo (duration, endPos), new CCScaleTo(duration, 1), new CCFadeOut (duration)), new CCCallFuncN(callbackRemoveNodeWhenDidAction)); label.RunAction(seq); return false; } public virtual bool onTextFieldDeleteBackward(CCTextFieldTTF pSender, string delText, int nLen) { // create a delete text sprite and do some action CCLabelTTF label = new CCLabelTTF(delText, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE); this.AddChild(label); // move the sprite to fly out CCPoint beginPos = pSender.Position; CCSize textfieldSize = pSender.ContentSize; CCSize labelSize = label.ContentSize; beginPos.X += (textfieldSize.Width - labelSize.Width) / 2.0f; int RAND_MAX = 32767; CCRandom rand = new CCRandom(); CCSize winSize = CCDirector.SharedDirector.WinSize; CCPoint endPos = new CCPoint(-winSize.Width / 4.0f, winSize.Height * (0.5f + (float)CCRandom.Next() / (2.0f * RAND_MAX))); float duration = 1; float rotateDuration = 0.2f; int repeatTime = 5; label.Position = beginPos; CCAction seq = new CCSequence( new CCSpawn( new CCMoveTo (duration, endPos), new CCRepeat ( new CCRotateBy (rotateDuration, (CCRandom.Next() % 2 > 0) ? 360 : -360), (uint)repeatTime), new CCFadeOut (duration)), new CCCallFuncN(callbackRemoveNodeWhenDidAction)); label.RunAction(seq); return false; } public virtual bool onDraw(CCTextFieldTTF pSender) { return false; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Net; using System.Text; using log4net; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Framework.Servers { public class MainServer { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static BaseHttpServer instance = null; private static Dictionary<uint, BaseHttpServer> m_Servers = new Dictionary<uint, BaseHttpServer>(); /// <summary> /// Control the printing of certain debug messages. /// </summary> /// <remarks> /// If DebugLevel >= 1 then short warnings are logged when receiving bad input data. /// If DebugLevel >= 2 then long warnings are logged when receiving bad input data. /// If DebugLevel >= 3 then short notices about all incoming non-poll HTTP requests are logged. /// If DebugLevel >= 4 then the time taken to fulfill the request is logged. /// If DebugLevel >= 5 then the start of the body of incoming non-poll HTTP requests will be logged. /// If DebugLevel >= 6 then the entire body of incoming non-poll HTTP requests will be logged. /// </remarks> public static int DebugLevel { get { return s_debugLevel; } set { s_debugLevel = value; lock (m_Servers) foreach (BaseHttpServer server in m_Servers.Values) server.DebugLevel = s_debugLevel; } } private static int s_debugLevel; /// <summary> /// Set the main HTTP server instance. /// </summary> /// <remarks> /// This will be used to register all handlers that listen to the default port. /// </remarks> /// <exception cref='Exception'> /// Thrown if the HTTP server has not already been registered via AddHttpServer() /// </exception> public static BaseHttpServer Instance { get { return instance; } set { lock (m_Servers) if (!m_Servers.ContainsValue(value)) throw new Exception("HTTP server must already have been registered to be set as the main instance"); instance = value; } } /// <summary> /// Get all the registered servers. /// </summary> /// <remarks> /// Returns a copy of the dictionary so this can be iterated through without locking. /// </remarks> /// <value></value> public static Dictionary<uint, BaseHttpServer> Servers { get { return new Dictionary<uint, BaseHttpServer>(m_Servers); } } public static void RegisterHttpConsoleCommands(ICommandConsole console) { console.Commands.AddCommand( "Comms", false, "show http-handlers", "show http-handlers", "Show all registered http handlers", HandleShowHttpHandlersCommand); console.Commands.AddCommand( "Debug", false, "debug http", "debug http <in|out|all> [<level>]", "Turn on http request logging.", "If in or all and\n" + " level <= 0 then no extra logging is done.\n" + " level >= 1 then short warnings are logged when receiving bad input data.\n" + " level >= 2 then long warnings are logged when receiving bad input data.\n" + " level >= 3 then short notices about all incoming non-poll HTTP requests are logged.\n" + " level >= 4 then the time taken to fulfill the request is logged.\n" + " level >= 5 then a sample from the beginning of the incoming data is logged.\n" + " level >= 6 then the entire incoming data is logged.\n" + " no level is specified then the current level is returned.\n\n" + "If out or all and\n" + " level >= 3 then short notices about all outgoing requests going through WebUtil are logged.\n" + " level >= 4 then the time taken to fulfill the request is logged.\n", HandleDebugHttpCommand); } /// <summary> /// Turn on some debugging values for OpenSim. /// </summary> /// <param name="args"></param> private static void HandleDebugHttpCommand(string module, string[] cmdparams) { if (cmdparams.Length < 3) { MainConsole.Instance.Output("Usage: debug http <in|out|all> 0..6"); return; } bool inReqs = false; bool outReqs = false; bool allReqs = false; string subCommand = cmdparams[2]; if (subCommand.ToLower() == "in") { inReqs = true; } else if (subCommand.ToLower() == "out") { outReqs = true; } else if (subCommand.ToLower() == "all") { allReqs = true; } else { MainConsole.Instance.Output("You must specify in, out or all"); return; } if (cmdparams.Length >= 4) { string rawNewDebug = cmdparams[3]; int newDebug; if (!int.TryParse(rawNewDebug, out newDebug)) { MainConsole.Instance.OutputFormat("{0} is not a valid debug level", rawNewDebug); return; } if (newDebug < 0 || newDebug > 6) { MainConsole.Instance.OutputFormat("{0} is outside the valid debug level range of 0..6", newDebug); return; } if (allReqs || inReqs) { MainServer.DebugLevel = newDebug; MainConsole.Instance.OutputFormat("IN debug level set to {0}", newDebug); } if (allReqs || outReqs) { WebUtil.DebugLevel = newDebug; MainConsole.Instance.OutputFormat("OUT debug level set to {0}", newDebug); } } else { if (allReqs || inReqs) MainConsole.Instance.OutputFormat("Current IN debug level is {0}", MainServer.DebugLevel); if (allReqs || outReqs) MainConsole.Instance.OutputFormat("Current OUT debug level is {0}", WebUtil.DebugLevel); } } private static void HandleShowHttpHandlersCommand(string module, string[] args) { if (args.Length != 2) { MainConsole.Instance.Output("Usage: show http-handlers"); return; } StringBuilder handlers = new StringBuilder(); lock (m_Servers) { foreach (BaseHttpServer httpServer in m_Servers.Values) { handlers.AppendFormat( "Registered HTTP Handlers for server at {0}:{1}\n", httpServer.ListenIPAddress, httpServer.Port); handlers.AppendFormat("* XMLRPC:\n"); foreach (String s in httpServer.GetXmlRpcHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* HTTP:\n"); foreach (String s in httpServer.GetHTTPHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* HTTP (poll):\n"); foreach (String s in httpServer.GetPollServiceHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* JSONRPC:\n"); foreach (String s in httpServer.GetJsonRpcHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); // handlers.AppendFormat("* Agent:\n"); // foreach (String s in httpServer.GetAgentHandlerKeys()) // handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* LLSD:\n"); foreach (String s in httpServer.GetLLSDHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* StreamHandlers ({0}):\n", httpServer.GetStreamHandlerKeys().Count); foreach (String s in httpServer.GetStreamHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.Append("\n"); } } MainConsole.Instance.Output(handlers.ToString()); } /// <summary> /// Register an already started HTTP server to the collection of known servers. /// </summary> /// <param name='server'></param> public static void AddHttpServer(BaseHttpServer server) { lock (m_Servers) { if (m_Servers.ContainsKey(server.Port)) throw new Exception(string.Format("HTTP server for port {0} already exists.", server.Port)); m_Servers.Add(server.Port, server); } } /// <summary> /// Removes the http server listening on the given port. /// </summary> /// <remarks> /// It is the responsibility of the caller to do clean up. /// </remarks> /// <param name='port'></param> /// <returns></returns> public static bool RemoveHttpServer(uint port) { lock (m_Servers) return m_Servers.Remove(port); } /// <summary> /// Does this collection of servers contain one with the given port? /// </summary> /// <remarks> /// Unlike GetHttpServer, this will not instantiate a server if one does not exist on that port. /// </remarks> /// <param name='port'></param> /// <returns>true if a server with the given port is registered, false otherwise.</returns> public static bool ContainsHttpServer(uint port) { lock (m_Servers) return m_Servers.ContainsKey(port); } /// <summary> /// Get the default http server or an http server for a specific port. /// </summary> /// <remarks> /// If the requested HTTP server doesn't already exist then a new one is instantiated and started. /// </remarks> /// <returns></returns> /// <param name='port'>If 0 then the default HTTP server is returned.</param> public static IHttpServer GetHttpServer(uint port) { return GetHttpServer(port, null); } /// <summary> /// Get the default http server, an http server for a specific port /// and/or an http server bound to a specific address /// </summary> /// <remarks> /// If the requested HTTP server doesn't already exist then a new one is instantiated and started. /// </remarks> /// <returns></returns> /// <param name='port'>If 0 then the default HTTP server is returned.</param> /// <param name='ipaddr'>A specific IP address to bind to. If null then the default IP address is used.</param> public static IHttpServer GetHttpServer(uint port, IPAddress ipaddr) { if (port == 0) return Instance; if (instance != null && port == Instance.Port) return Instance; lock (m_Servers) { if (m_Servers.ContainsKey(port)) return m_Servers[port]; m_Servers[port] = new BaseHttpServer(port); if (ipaddr != null) m_Servers[port].ListenIPAddress = ipaddr; m_Servers[port].Start(); return m_Servers[port]; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Find_Fest_API.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; /// <summary> /// String.PadRight(Int32) /// Right-aligns the characters in this instance, /// padding with spaces on the left for a specified total length /// </summary> public class StringPadRight1 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars) private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars) private const int c_MAX_LONG_STR_LEN = 65535; public static int Main() { StringPadRight1 spl = new StringPadRight1(); TestLibrary.TestFramework.BeginTestCase("for method: System.String.PadRight(Int32)"); if (spl.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; return retVal; } #region Positive test scenarios public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Total width is greater than old string length"; const string c_TEST_ID = "P001"; int totalWidth; string str; bool condition1 = false; //Verify the space paded bool condition2 = false; //Verify the old string bool expectedValue = true; bool actualValue = false; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); //str = "hello"; totalWidth = GetInt32(str.Length + 1, str.Length + c_MAX_STRING_LEN); //totalWidth = 8; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { string strPaded = str.PadRight(totalWidth); char[] trimChs = new char[] {'\x0020'}; string spaces = new string('\x0020', totalWidth - str.Length); string spacesPaded = strPaded.Substring(str.Length, totalWidth - str.Length); condition1 = (string.CompareOrdinal(spaces, spacesPaded) == 0); condition2 = (string.CompareOrdinal(strPaded.TrimEnd(trimChs), str) == 0); actualValue = condition1 && condition2; if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(str, totalWidth); TestLibrary.TestFramework.LogError("001" + "TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: 0 <= total width <= old string length"; const string c_TEST_ID = "P002"; int totalWidth; string str; bool expectedValue = true; bool actualValue = false; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); totalWidth = GetInt32(0, str.Length - 1); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { string strPaded = str.PadRight(totalWidth); actualValue = (0 == string.CompareOrdinal(strPaded, str)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(str, totalWidth); TestLibrary.TestFramework.LogError("003" + "TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } #endregion #region Negative test scenarios //ArgumentException public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: Total width is less than zero. "; const string c_TEST_ID = "N001"; int totalWidth; string str; totalWidth = -1 * TestLibrary.Generator.GetInt32(-55) - 1; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str.PadRight(totalWidth); TestLibrary.TestFramework.LogError("005" + "TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected" + GetDataString(str, totalWidth)); retVal = false; } catch (ArgumentException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e +GetDataString(str, totalWidth)); retVal = false; } return retVal; } //OutOfMemoryException public bool NegTest2() // bug 8-8-2006 Noter(v-yaduoj) { bool retVal = true; const string c_TEST_DESC = "NegTest2: Too great width "; const string c_TEST_ID = "N002"; int totalWidth; string str; totalWidth = Int32.MaxValue; str = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { str.PadRight(totalWidth); TestLibrary.TestFramework.LogError("007" + "TestId-" + c_TEST_ID, "OutOfMemoryException is not thrown as expected" + GetDataString(str, totalWidth)); retVal = false; } catch (OutOfMemoryException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(str, totalWidth)); retVal = false; } return retVal; } #endregion #region helper methods for generating test data private bool GetBoolean() { Int32 i = this.GetInt32(1, 2); return (i == 1) ? true : false; } //Get a non-negative integer between minValue and maxValue private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } private Int32 Min(Int32 i1, Int32 i2) { return (i1 <= i2) ? i1 : i2; } private Int32 Max(Int32 i1, Int32 i2) { return (i1 >= i2) ? i1 : i2; } #endregion private string GetDataString(string strSrc, int totalWidth) { string str1, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Total width]\n{0}", totalWidth); return str; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using Document = Lucene.Net.Documents.Document; using Field = Lucene.Net.Documents.Field; using Norm = Lucene.Net.Index.SegmentReader.Norm; using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using LockObtainFailedException = Lucene.Net.Store.LockObtainFailedException; using MockRAMDirectory = Lucene.Net.Store.MockRAMDirectory; using Similarity = Lucene.Net.Search.Similarity; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { /// <summary> Tests cloning multiple types of readers, modifying the deletedDocs and norms /// and verifies copy on write semantics of the deletedDocs and norms is /// implemented properly /// </summary> [TestFixture] public class TestIndexReaderClone:LuceneTestCase { [Test] public virtual void TestCloneReadOnlySegmentReader() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader reader = IndexReader.Open(dir1, false); IndexReader readOnlyReader = reader.Clone(true); Assert.IsTrue(IsReadOnly(readOnlyReader), "reader isn't read only"); Assert.IsFalse(DeleteWorked(1, readOnlyReader), "deleting from the original should not have worked"); reader.Close(); readOnlyReader.Close(); dir1.Close(); } // open non-readOnly reader1, clone to non-readOnly // reader2, make sure we can change reader2 [Test] public virtual void TestCloneNoChangesStillReadOnly() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader r1 = IndexReader.Open(dir1, false); IndexReader r2 = r1.Clone(false); Assert.IsTrue(DeleteWorked(1, r2), "deleting from the cloned should have worked"); r1.Close(); r2.Close(); dir1.Close(); } // open non-readOnly reader1, clone to non-readOnly // reader2, make sure we can change reader1 [Test] public virtual void TestCloneWriteToOrig() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader r1 = IndexReader.Open(dir1, false); IndexReader r2 = r1.Clone(false); Assert.IsTrue(DeleteWorked(1, r1), "deleting from the original should have worked"); r1.Close(); r2.Close(); dir1.Close(); } // open non-readOnly reader1, clone to non-readOnly // reader2, make sure we can change reader2 [Test] public virtual void TestCloneWriteToClone() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader r1 = IndexReader.Open(dir1, false); IndexReader r2 = r1.Clone(false); Assert.IsTrue(DeleteWorked(1, r2), "deleting from the original should have worked"); // should fail because reader1 holds the write lock Assert.IsTrue(!DeleteWorked(1, r1), "first reader should not be able to delete"); r2.Close(); // should fail because we are now stale (reader1 // committed changes) Assert.IsTrue(!DeleteWorked(1, r1), "first reader should not be able to delete"); r1.Close(); dir1.Close(); } // create single-segment index, open non-readOnly // SegmentReader, add docs, reopen to multireader, then do // delete [Test] public virtual void TestReopenSegmentReaderToMultiReader() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader reader1 = IndexReader.Open(dir1, false); TestIndexReaderReopen.ModifyIndex(5, dir1); IndexReader reader2 = reader1.Reopen(); Assert.IsTrue(reader1 != reader2); Assert.IsTrue(DeleteWorked(1, reader2)); reader1.Close(); reader2.Close(); dir1.Close(); } // open non-readOnly reader1, clone to readOnly reader2 [Test] public virtual void TestCloneWriteableToReadOnly() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader = IndexReader.Open(dir1, false); IndexReader readOnlyReader = reader.Clone(true); Assert.IsTrue(IsReadOnly(readOnlyReader), "reader isn't read only"); Assert.IsFalse(DeleteWorked(1, readOnlyReader), "deleting from the original should not have worked"); // this readonly reader shouldn't have a write lock Assert.IsFalse(readOnlyReader.hasChanges, "readOnlyReader has a write lock"); reader.Close(); readOnlyReader.Close(); dir1.Close(); } // open non-readOnly reader1, reopen to readOnly reader2 [Test] public virtual void TestReopenWriteableToReadOnly() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader = IndexReader.Open(dir1, false); int docCount = reader.NumDocs(); Assert.IsTrue(DeleteWorked(1, reader)); Assert.AreEqual(docCount - 1, reader.NumDocs()); IndexReader readOnlyReader = reader.Reopen(true); Assert.IsTrue(IsReadOnly(readOnlyReader), "reader isn't read only"); Assert.IsFalse(DeleteWorked(1, readOnlyReader)); Assert.AreEqual(docCount - 1, readOnlyReader.NumDocs()); reader.Close(); readOnlyReader.Close(); dir1.Close(); } // open readOnly reader1, clone to non-readOnly reader2 [Test] public virtual void TestCloneReadOnlyToWriteable() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader1 = IndexReader.Open(dir1, true); IndexReader reader2 = reader1.Clone(false); Assert.IsFalse(IsReadOnly(reader2), "reader should not be read only"); Assert.IsFalse(DeleteWorked(1, reader1), "deleting from the original reader should not have worked"); // this readonly reader shouldn't yet have a write lock Assert.IsFalse(reader2.hasChanges, "cloned reader should not have write lock"); Assert.IsTrue(DeleteWorked(1, reader2), "deleting from the cloned reader should have worked"); reader1.Close(); reader2.Close(); dir1.Close(); } // open non-readOnly reader1 on multi-segment index, then // optimize the index, then clone to readOnly reader2 [Test] public virtual void TestReadOnlyCloneAfterOptimize() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader1 = IndexReader.Open(dir1, false); IndexWriter w = new IndexWriter(dir1, new SimpleAnalyzer(), IndexWriter.MaxFieldLength.LIMITED); w.Optimize(); w.Close(); IndexReader reader2 = reader1.Clone(true); Assert.IsTrue(IsReadOnly(reader2)); reader1.Close(); reader2.Close(); dir1.Close(); } private static bool DeleteWorked(int doc, IndexReader r) { bool exception = false; try { // trying to delete from the original reader should throw an exception r.DeleteDocument(doc); } catch (System.Exception ex) { exception = true; } return !exception; } [Test] public virtual void TestCloneReadOnlyDirectoryReader() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader = IndexReader.Open(dir1, false); IndexReader readOnlyReader = reader.Clone(true); Assert.IsTrue(IsReadOnly(readOnlyReader), "reader isn't read only"); reader.Close(); readOnlyReader.Close(); dir1.Close(); } public static bool IsReadOnly(IndexReader r) { if (r is ReadOnlySegmentReader || r is ReadOnlyDirectoryReader) return true; return false; } [Test] public virtual void TestParallelReader() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); Directory dir2 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir2, true); IndexReader r1 = IndexReader.Open(dir1, false); IndexReader r2 = IndexReader.Open(dir2, false); ParallelReader pr1 = new ParallelReader(); pr1.Add(r1); pr1.Add(r2); PerformDefaultTests(pr1); pr1.Close(); dir1.Close(); dir2.Close(); } /// <summary> 1. Get a norm from the original reader 2. Clone the original reader 3. /// Delete a document and set the norm of the cloned reader 4. Verify the norms /// are not the same on each reader 5. Verify the doc deleted is only in the /// cloned reader 6. Try to delete a document in the original reader, an /// exception should be thrown /// /// </summary> /// <param name="r1">IndexReader to perform tests on /// </param> /// <throws> Exception </throws> private void PerformDefaultTests(IndexReader r1) { float norm1 = Similarity.DecodeNorm(r1.Norms("field1")[4]); IndexReader pr1Clone = (IndexReader) r1.Clone(); pr1Clone.DeleteDocument(10); pr1Clone.SetNorm(4, "field1", 0.5f); Assert.IsTrue(Similarity.DecodeNorm(r1.Norms("field1")[4]) == norm1); Assert.IsTrue(Similarity.DecodeNorm(pr1Clone.Norms("field1")[4]) != norm1); Assert.IsTrue(!r1.IsDeleted(10)); Assert.IsTrue(pr1Clone.IsDeleted(10)); // try to update the original reader, which should throw an exception Assert.Throws<LockObtainFailedException>(() => r1.DeleteDocument(11), "Tried to delete doc 11 and an exception should have been thrown"); pr1Clone.Close(); } [Test] public virtual void TestMixedReaders() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); Directory dir2 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir2, true); IndexReader r1 = IndexReader.Open(dir1, false); IndexReader r2 = IndexReader.Open(dir2, false); MultiReader multiReader = new MultiReader(new IndexReader[]{r1, r2}); PerformDefaultTests(multiReader); multiReader.Close(); dir1.Close(); dir2.Close(); } [Test] public virtual void TestSegmentReaderUndeleteall() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); SegmentReader origSegmentReader = SegmentReader.GetOnlySegmentReader(dir1); origSegmentReader.DeleteDocument(10); AssertDelDocsRefCountEquals(1, origSegmentReader); origSegmentReader.UndeleteAll(); Assert.IsNull(origSegmentReader.deletedDocsRef_ForNUnit); origSegmentReader.Close(); // need to test norms? dir1.Close(); } [Test] public virtual void TestSegmentReaderCloseReferencing() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); SegmentReader origSegmentReader = SegmentReader.GetOnlySegmentReader(dir1); origSegmentReader.DeleteDocument(1); origSegmentReader.SetNorm(4, "field1", 0.5f); SegmentReader clonedSegmentReader = (SegmentReader) origSegmentReader.Clone(); AssertDelDocsRefCountEquals(2, origSegmentReader); origSegmentReader.Close(); AssertDelDocsRefCountEquals(1, origSegmentReader); // check the norm refs Norm norm = clonedSegmentReader.norms_ForNUnit["field1"]; Assert.AreEqual(1, norm.BytesRef().RefCount()); clonedSegmentReader.Close(); dir1.Close(); } [Test] public virtual void TestSegmentReaderDelDocsReferenceCounting() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader origReader = IndexReader.Open(dir1, false); SegmentReader origSegmentReader = SegmentReader.GetOnlySegmentReader(origReader); // deletedDocsRef should be null because nothing has updated yet Assert.IsNull(origSegmentReader.deletedDocsRef_ForNUnit); // we deleted a document, so there is now a deletedDocs bitvector and a // reference to it origReader.DeleteDocument(1); AssertDelDocsRefCountEquals(1, origSegmentReader); // the cloned segmentreader should have 2 references, 1 to itself, and 1 to // the original segmentreader IndexReader clonedReader = (IndexReader) origReader.Clone(); SegmentReader clonedSegmentReader = SegmentReader.GetOnlySegmentReader(clonedReader); AssertDelDocsRefCountEquals(2, origSegmentReader); // deleting a document creates a new deletedDocs bitvector, the refs goes to // 1 clonedReader.DeleteDocument(2); AssertDelDocsRefCountEquals(1, origSegmentReader); AssertDelDocsRefCountEquals(1, clonedSegmentReader); // make sure the deletedocs objects are different (copy // on write) Assert.IsTrue(origSegmentReader.deletedDocs_ForNUnit != clonedSegmentReader.deletedDocs_ForNUnit); AssertDocDeleted(origSegmentReader, clonedSegmentReader, 1); Assert.IsTrue(!origSegmentReader.IsDeleted(2)); // doc 2 should not be deleted // in original segmentreader Assert.IsTrue(clonedSegmentReader.IsDeleted(2)); // doc 2 should be deleted in // cloned segmentreader // deleting a doc from the original segmentreader should throw an exception Assert.Throws<LockObtainFailedException>(() => origReader.DeleteDocument(4), "expected exception"); origReader.Close(); // try closing the original segment reader to see if it affects the // clonedSegmentReader clonedReader.DeleteDocument(3); clonedReader.Flush(); AssertDelDocsRefCountEquals(1, clonedSegmentReader); // test a reopened reader IndexReader reopenedReader = clonedReader.Reopen(); IndexReader cloneReader2 = (IndexReader) reopenedReader.Clone(); SegmentReader cloneSegmentReader2 = SegmentReader.GetOnlySegmentReader(cloneReader2); AssertDelDocsRefCountEquals(2, cloneSegmentReader2); clonedReader.Close(); reopenedReader.Close(); cloneReader2.Close(); dir1.Close(); } // LUCENE-1648 [Test] public virtual void TestCloneWithDeletes() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader origReader = IndexReader.Open(dir1, false); origReader.DeleteDocument(1); IndexReader clonedReader = (IndexReader) origReader.Clone(); origReader.Close(); clonedReader.Close(); IndexReader r = IndexReader.Open(dir1, false); Assert.IsTrue(r.IsDeleted(1)); r.Close(); dir1.Close(); } // LUCENE-1648 [Test] public virtual void TestCloneWithSetNorm() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader orig = IndexReader.Open(dir1, false); orig.SetNorm(1, "field1", 17.0f); byte encoded = Similarity.EncodeNorm(17.0f); Assert.AreEqual(encoded, orig.Norms("field1")[1]); // the cloned segmentreader should have 2 references, 1 to itself, and 1 to // the original segmentreader IndexReader clonedReader = (IndexReader) orig.Clone(); orig.Close(); clonedReader.Close(); IndexReader r = IndexReader.Open(dir1, false); Assert.AreEqual(encoded, r.Norms("field1")[1]); r.Close(); dir1.Close(); } private void AssertDocDeleted(SegmentReader reader, SegmentReader reader2, int doc) { Assert.AreEqual(reader.IsDeleted(doc), reader2.IsDeleted(doc)); } private void AssertDelDocsRefCountEquals(int refCount, SegmentReader reader) { Assert.AreEqual(refCount, reader.deletedDocsRef_ForNUnit.RefCount()); } [Test] public virtual void TestCloneSubreaders() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, true); IndexReader reader = IndexReader.Open(dir1, false); reader.DeleteDocument(1); // acquire write lock IndexReader[] subs = reader.GetSequentialSubReaders(); System.Diagnostics.Debug.Assert(subs.Length > 1); IndexReader[] clones = new IndexReader[subs.Length]; for (int x = 0; x < subs.Length; x++) { clones[x] = (IndexReader) subs[x].Clone(); } reader.Close(); for (int x = 0; x < subs.Length; x++) { clones[x].Close(); } dir1.Close(); } [Test] public virtual void TestLucene1516Bug() { Directory dir1 = new MockRAMDirectory(); TestIndexReaderReopen.CreateIndex(dir1, false); IndexReader r1 = IndexReader.Open(dir1, false); r1.IncRef(); IndexReader r2 = r1.Clone(false); r1.DeleteDocument(5); r1.DecRef(); r1.IncRef(); r2.Close(); r1.DecRef(); r1.Close(); dir1.Close(); } [Test] public virtual void TestCloseStoredFields() { Directory dir = new MockRAMDirectory(); IndexWriter w = new IndexWriter(dir, new SimpleAnalyzer(), IndexWriter.MaxFieldLength.UNLIMITED); w.UseCompoundFile = false; Document doc = new Document(); doc.Add(new Field("field", "yes it's stored", Field.Store.YES, Field.Index.ANALYZED)); w.AddDocument(doc); w.Close(); IndexReader r1 = IndexReader.Open(dir, false); IndexReader r2 = r1.Clone(false); r1.Close(); r2.Close(); dir.Close(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; namespace Internal.Runtime.Augments { using Interop = global::Interop; /// due to the existence of <see cref="Internal.Interop"/> using OSThreadPriority = Interop.mincore.ThreadPriority; public sealed partial class RuntimeThread { [ThreadStatic] private static int t_reentrantWaitSuppressionCount; [ThreadStatic] private static ApartmentType t_apartmentType; private object _threadStartArg; private SafeWaitHandle _osHandle; /// <summary> /// Used by <see cref="WaitHandle"/>'s multi-wait functions /// </summary> private WaitHandleArray<IntPtr> _waitedHandles; private void PlatformSpecificInitialize() { _waitedHandles = new WaitHandleArray<IntPtr>(elementInitializer: null); } internal IntPtr[] GetWaitedHandleArray(int requiredCapacity) { Debug.Assert(this == CurrentThread); _waitedHandles.EnsureCapacity(requiredCapacity); return _waitedHandles.Items; } private void PlatformSpecificInitializeExistingThread() { _osHandle = GetOSHandleForCurrentThread(); _priority = MapFromOSPriority(Interop.mincore.GetThreadPriority(_osHandle)); } private static SafeWaitHandle GetOSHandleForCurrentThread() { IntPtr currentProcHandle = Interop.mincore.GetCurrentProcess(); IntPtr currentThreadHandle = Interop.mincore.GetCurrentThread(); SafeWaitHandle threadHandle; if (Interop.mincore.DuplicateHandle(currentProcHandle, currentThreadHandle, currentProcHandle, out threadHandle, 0, false, (uint)Interop.Constants.DuplicateSameAccess)) { return threadHandle; } // Throw an ApplicationException for compatibility with CoreCLR. First save the error code. int errorCode = Marshal.GetLastWin32Error(); var ex = new ApplicationException(); ex.SetErrorCode(errorCode); throw ex; } private static ThreadPriority MapFromOSPriority(OSThreadPriority priority) { if (priority <= OSThreadPriority.Lowest) { // OS thread priorities in the [Idle,Lowest] range are mapped to ThreadPriority.Lowest return ThreadPriority.Lowest; } switch (priority) { case OSThreadPriority.BelowNormal: return ThreadPriority.BelowNormal; case OSThreadPriority.Normal: return ThreadPriority.Normal; case OSThreadPriority.AboveNormal: return ThreadPriority.AboveNormal; case OSThreadPriority.ErrorReturn: Debug.Fail("GetThreadPriority failed"); return ThreadPriority.Normal; } // Handle OSThreadPriority.ErrorReturn value before this check! if (priority >= OSThreadPriority.Highest) { // OS thread priorities in the [Highest,TimeCritical] range are mapped to ThreadPriority.Highest return ThreadPriority.Highest; } Debug.Fail("Unreachable"); return ThreadPriority.Normal; } private static OSThreadPriority MapToOSPriority(ThreadPriority priority) { switch (priority) { case ThreadPriority.Lowest: return OSThreadPriority.Lowest; case ThreadPriority.BelowNormal: return OSThreadPriority.BelowNormal; case ThreadPriority.Normal: return OSThreadPriority.Normal; case ThreadPriority.AboveNormal: return OSThreadPriority.AboveNormal; case ThreadPriority.Highest: return OSThreadPriority.Highest; default: Debug.Fail("Unreachable"); return OSThreadPriority.Normal; } } private ThreadPriority GetPriority() { if (_osHandle.IsInvalid) { // The thread has not been started yet; return the value assigned to the Priority property. // Race condition with setting the priority or starting the thread is OK, we may return an old value. return _priority; } // The priority might have been changed by external means. Obtain the actual value from the OS // rather than using the value saved in _priority. OSThreadPriority osPriority = Interop.mincore.GetThreadPriority(_osHandle); return MapFromOSPriority(osPriority); } private bool SetPriority(ThreadPriority priority) { if (_osHandle.IsInvalid) { Debug.Assert(GetThreadStateBit(ThreadState.Unstarted)); // We will set the priority (saved in _priority) when we create an OS thread return true; } return Interop.mincore.SetThreadPriority(_osHandle, (int)MapToOSPriority(priority)); } /// <summary> /// Checks if the underlying OS thread has finished execution. /// </summary> /// <remarks> /// Use this method only on started threads and threads being started in StartCore. /// </remarks> private bool HasFinishedExecution() { // If an external thread dies and its Thread object is resurrected, _osHandle will be finalized, i.e. invalid if (_osHandle.IsInvalid) { return true; } uint result = Interop.mincore.WaitForSingleObject(_osHandle, dwMilliseconds: 0); return result == (uint)Interop.Constants.WaitObject0; } private bool JoinCore(int millisecondsTimeout) { SafeWaitHandle waitHandle = _osHandle; int result; waitHandle.DangerousAddRef(); try { result = WaitHandle.WaitForSingleObject(waitHandle.DangerousGetHandle(), millisecondsTimeout); } finally { waitHandle.DangerousRelease(); } return result == (int)Interop.Constants.WaitObject0; } private void StartCore(object parameter) { using (LockHolder.Hold(_lock)) { if (!GetThreadStateBit(ThreadState.Unstarted)) { throw new ThreadStateException(SR.ThreadState_AlreadyStarted); } const int AllocationGranularity = (int)0x10000; // 64k int stackSize = _maxStackSize; if ((0 < stackSize) && (stackSize < AllocationGranularity)) { // If StackSizeParamIsAReservation flag is set and the reserve size specified by CreateThread's // dwStackSize parameter is less than or equal to the initially committed stack size specified in // the executable header, the reserve size will be set to the initially committed size rounded up // to the nearest multiple of 1 MiB. In all cases the reserve size is rounded up to the nearest // multiple of the system's allocation granularity (typically 64 KiB). // // To prevent overreservation of stack memory for small stackSize values, we increase stackSize to // the allocation granularity. We assume that the SizeOfStackCommit field of IMAGE_OPTIONAL_HEADER // is strictly smaller than the allocation granularity (the field's default value is 4 KiB); // otherwise, at least 1 MiB of memory will be reserved. Note that the desktop CLR increases // stackSize to 256 KiB if it is smaller than that. stackSize = AllocationGranularity; } bool waitingForThreadStart = false; GCHandle threadHandle = GCHandle.Alloc(this); _threadStartArg = parameter; uint threadId; try { _osHandle = Interop.mincore.CreateThread(IntPtr.Zero, (IntPtr)stackSize, AddrofIntrinsics.AddrOf<Interop.mincore.ThreadProc>(StartThread), (IntPtr)threadHandle, (uint)(Interop.Constants.CreateSuspended | Interop.Constants.StackSizeParamIsAReservation), out threadId); // CoreCLR ignores OS errors while setting the priority, so do we SetPriority(_priority); Interop.mincore.ResumeThread(_osHandle); // Skip cleanup if any asynchronous exception happens while waiting for the thread start waitingForThreadStart = true; // Wait until the new thread either dies or reports itself as started while (GetThreadStateBit(ThreadState.Unstarted) && !HasFinishedExecution()) { Yield(); } waitingForThreadStart = false; } finally { Debug.Assert(!waitingForThreadStart, "Leaked threadHandle"); if (!waitingForThreadStart) { threadHandle.Free(); _threadStartArg = null; } } if (GetThreadStateBit(ThreadState.Unstarted)) { // Lack of memory is the only expected reason for thread creation failure throw new ThreadStartException(new OutOfMemoryException()); } } } [NativeCallable(CallingConvention = CallingConvention.StdCall)] private static uint StartThread(IntPtr parameter) { GCHandle threadHandle = (GCHandle)parameter; RuntimeThread thread = (RuntimeThread)threadHandle.Target; Delegate threadStart = thread._threadStart; // Get the value before clearing the ThreadState.Unstarted bit object threadStartArg = thread._threadStartArg; try { t_currentThread = thread; System.Threading.ManagedThreadId.SetForCurrentThread(thread._managedThreadId); } catch (OutOfMemoryException) { // Terminate the current thread. The creator thread will throw a ThreadStartException. return 0; } // Report success to the creator thread, which will free threadHandle and _threadStartArg thread.ClearThreadStateBit(ThreadState.Unstarted); try { // The Thread cannot be started more than once, so we may clean up the delegate thread._threadStart = null; #if ENABLE_WINRT // If this call fails, COM and WinRT calls on this thread will fail with CO_E_NOTINITIALIZED. // We may continue and fail on the actual call. Interop.WinRT.RoInitialize(Interop.WinRT.RO_INIT_TYPE.RO_INIT_MULTITHREADED); #endif ParameterizedThreadStart paramThreadStart = threadStart as ParameterizedThreadStart; if (paramThreadStart != null) { paramThreadStart(threadStartArg); } else { ((ThreadStart)threadStart)(); } } finally { thread.SetThreadStateBit(ThreadState.Stopped); } return 0; } public ApartmentState GetApartmentState() { throw null; } public bool TrySetApartmentState(ApartmentState state) { throw null; } public void DisableComObjectEagerCleanup() { throw null; } public void Interrupt() { throw null; } internal static void UninterruptibleSleep0() { Interop.mincore.Sleep(0); } private static void SleepCore(int millisecondsTimeout) { Debug.Assert(millisecondsTimeout >= -1); Interop.mincore.Sleep((uint)millisecondsTimeout); } // // Suppresses reentrant waits on the current thread, until a matching call to RestoreReentrantWaits. // This should be used by code that's expected to be called inside the STA message pump, so that it won't // reenter itself. In an ASTA, this should only be the CCW implementations of IUnknown and IInspectable. // internal static void SuppressReentrantWaits() { t_reentrantWaitSuppressionCount++; } internal static void RestoreReentrantWaits() { Debug.Assert(t_reentrantWaitSuppressionCount > 0); t_reentrantWaitSuppressionCount--; } internal static bool ReentrantWaitsEnabled => GetCurrentApartmentType() == ApartmentType.STA && t_reentrantWaitSuppressionCount == 0; internal static ApartmentType GetCurrentApartmentType() { ApartmentType currentThreadType = t_apartmentType; if (currentThreadType != ApartmentType.Unknown) return currentThreadType; Interop._APTTYPE aptType; Interop._APTTYPEQUALIFIER aptTypeQualifier; int result = Interop.mincore.CoGetApartmentType(out aptType, out aptTypeQualifier); ApartmentType type = ApartmentType.Unknown; switch ((Interop.Constants)result) { case Interop.Constants.CoENotInitialized: type = ApartmentType.None; break; case Interop.Constants.SOk: switch (aptType) { case Interop._APTTYPE.APTTYPE_STA: case Interop._APTTYPE.APTTYPE_MAINSTA: type = ApartmentType.STA; break; case Interop._APTTYPE.APTTYPE_MTA: type = ApartmentType.MTA; break; case Interop._APTTYPE.APTTYPE_NA: switch (aptTypeQualifier) { case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MTA: case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_IMPLICIT_MTA: type = ApartmentType.MTA; break; case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_STA: case Interop._APTTYPEQUALIFIER.APTTYPEQUALIFIER_NA_ON_MAINSTA: type = ApartmentType.STA; break; default: Debug.Assert(false, "NA apartment without NA qualifier"); break; } break; } break; default: Debug.Assert(false, "bad return from CoGetApartmentType"); break; } if (type != ApartmentType.Unknown) t_apartmentType = type; return type; } internal enum ApartmentType { Unknown = 0, None, STA, MTA } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Animation.Int16KeyFrameCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Animation { public partial class Int16KeyFrameCollection : System.Windows.Freezable, System.Collections.IList, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public int Add(Int16KeyFrame keyFrame) { return default(int); } public void Clear() { } public System.Windows.Media.Animation.Int16KeyFrameCollection Clone() { return default(System.Windows.Media.Animation.Int16KeyFrameCollection); } protected override void CloneCore(System.Windows.Freezable sourceFreezable) { } protected override void CloneCurrentValueCore(System.Windows.Freezable sourceFreezable) { } public bool Contains(Int16KeyFrame keyFrame) { return default(bool); } public void CopyTo(Int16KeyFrame[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } protected override bool FreezeCore(bool isChecking) { return default(bool); } protected override void GetAsFrozenCore(System.Windows.Freezable sourceFreezable) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable sourceFreezable) { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public int IndexOf(Int16KeyFrame keyFrame) { return default(int); } public void Insert(int index, Int16KeyFrame keyFrame) { } public Int16KeyFrameCollection() { } public void Remove(Int16KeyFrame keyFrame) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(Array array, int index) { } int System.Collections.IList.Add(Object keyFrame) { return default(int); } bool System.Collections.IList.Contains(Object keyFrame) { return default(bool); } int System.Collections.IList.IndexOf(Object keyFrame) { return default(int); } void System.Collections.IList.Insert(int index, Object keyFrame) { } void System.Collections.IList.Remove(Object keyFrame) { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public static System.Windows.Media.Animation.Int16KeyFrameCollection Empty { get { return default(System.Windows.Media.Animation.Int16KeyFrameCollection); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public bool IsSynchronized { get { return default(bool); } } public Int16KeyFrame this [int index] { get { return default(Int16KeyFrame); } set { } } public Object SyncRoot { get { return default(Object); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using MindTouch.Deki.Data; using MindTouch.Deki.Logic; using MindTouch.Dream; using MindTouch.Xml; namespace MindTouch.Deki.Export { [Flags] public enum ExportExcludeType { NONE = 0x0000, FILES = 0x0001, PROPS = 0x0002, TAGS = 0x0004, TALK = 0x0008, ALL = FILES | PROPS | TAGS | TALK }; internal class SiteExportBuilder { //--- Fields --- Dictionary<XUri, object> _uris; uint _id; XDoc _requestDoc; XDoc _manifestDoc; Title _relToTitle; //--- Constructors --- public SiteExportBuilder(Title relToTitle) { _uris = new Dictionary<XUri, object>(); _id = 0; _requestDoc = new XDoc("requests"); _manifestDoc = new XDoc("manifest"); _relToTitle = relToTitle; } //--- Methods --- public void Append(XDoc exportDoc) { _manifestDoc.Attr("date.created", DateTime.UtcNow).Attr("preserve-local", false); foreach(XDoc exportXml in exportDoc.Elements) { // Retrieve the current page try { if(exportXml.HasName("page")) { // Generate the manifest and request needed to export the page PageBE page = null; if(!exportXml["@id"].IsEmpty) { uint pageId = DbUtils.Convert.To<uint>(exportXml["@id"].Contents, 0); if(0 < pageId) { page = PageBL.GetPageById(pageId); } } else if(!exportXml["@path"].IsEmpty) { page = PageBL.GetPageByTitle(Title.FromPrefixedDbPath(exportXml["@path"].Contents, null)); } if((null == page) || (0 == page.ID)) { throw new DreamNotFoundException(DekiResources.CANNOT_FIND_REQUESTED_PAGE); } // Check whether to exclude subpages, files, and/or properties bool recursive = exportXml["@recursive"].AsBool ?? false; ExportExcludeType exclude = ExportExcludeType.NONE; if(!exportXml["@exclude"].IsEmpty) { exclude = SysUtil.ChangeType<ExportExcludeType>(exportXml["@exclude"].Contents); } // Export the page PageExport(recursive, exclude, page); } else if(exportXml.HasName("file")) { // Generate the manifest and request needed to export the file AttachmentBE file = null; if(!exportXml["@id"].IsEmpty) { uint fileId = DbUtils.Convert.To<uint>(exportXml["@id"].Contents, 0); if(0 < fileId) { uint resourceId = ResourceMapBL.GetResourceIdByFileId(fileId) ?? 0; if(resourceId > 0) { file = AttachmentBL.Instance.GetResource(resourceId, AttachmentBE.HEADREVISION); } } } if(null == file) { throw new DreamNotFoundException(DekiResources.COULD_NOT_FIND_FILE); } // Check whether to exclude properties ExportExcludeType exclude = ExportExcludeType.NONE; if(!exportXml["@exclude"].IsEmpty) { exclude = SysUtil.ChangeType<ExportExcludeType>(exportXml["@exclude"].Contents); } // Perform the file export PageBE page = PageBL.GetPageById(file.ParentPageId); page = PageBL.AuthorizePage(DekiContext.Current.User, Permissions.READ, page, false); AttachmentExport(exclude, page, file); } else { throw new DreamResponseException(DreamMessage.NotImplemented(exportXml.Name)); } } catch(DreamAbortException e) { AddError(e.Message, (int)e.Response.Status, exportXml); } catch(Exception e) { AddError(e.Message, (int)DreamStatus.InternalError, exportXml); } } } private void PageExport(bool recursive, ExportExcludeType exclude, PageBE page) { // Validate the page export page = PageBL.AuthorizePage(DekiContext.Current.User, Permissions.READ, page, false); if(page.IsRedirect) { throw new DreamBadRequestException(DekiResources.INVALID_REDIRECT_OPERATION); } // Export the page XUri uri = PageBL.GetUriCanonical(page).At("contents") .With("mode", "edit") .With("reltopath", _relToTitle.AsPrefixedDbPath()) .With("format", "xhtml"); if(!_uris.ContainsKey(uri)) { _uris.Add(uri, null); var dateModified = page.TimeStamp; var lastImport = PropertyBL.Instance.GetResource((uint)page.ID, ResourceBE.Type.PAGE, SiteImportBuilder.LAST_IMPORT); if(lastImport != null) { var content = lastImport.Content; var importDoc = XDocFactory.From(content.ToStream(), content.MimeType); if(importDoc["etag"].AsText.EqualsInvariant(page.Etag)) { dateModified = importDoc["date.modified"].AsDate ?? DateTime.MinValue; } } var manifestDoc = new XDoc("page").Elem("title", page.Title.DisplayName) .Elem("path", page.Title.AsRelativePath(_relToTitle)) .Elem("language", page.Language) .Elem("etag", page.Etag) .Elem("date.modified", dateModified.ToSafeUniversalTime()) .Start("contents").Attr("type", page.ContentType).End(); Add(uri, manifestDoc); } // Export page tags (if not excluded) if(ExportExcludeType.NONE == (ExportExcludeType.TAGS & exclude)) { XUri tagUri = PageBL.GetUriCanonical(page).At("tags"); if(!_uris.ContainsKey(tagUri)) { _uris.Add(tagUri, null); XDoc manifestDoc = new XDoc("tags").Elem("path", page.Title.AsRelativePath(_relToTitle)); Add(tagUri, manifestDoc); } } // Export page properties (if not excluded) if(ExportExcludeType.NONE == (ExportExcludeType.PROPS & exclude)) { IList<PropertyBE> properties = PropertyBL.Instance.GetResources((uint)page.ID, ResourceBE.Type.PAGE, null, DeletionFilter.ACTIVEONLY); foreach(PropertyBE property in properties) { if(property.Name.EqualsInvariant(SiteImportBuilder.LAST_IMPORT)) { continue; } PropertyExport(page, null, property); } } // Export page files (if not excluded) if(ExportExcludeType.NONE == (ExportExcludeType.FILES & exclude)) { IList<AttachmentBE> files = AttachmentBL.Instance.GetResources(page, DeletionFilter.ACTIVEONLY); foreach(AttachmentBE file in files) { AttachmentExport(exclude, page, file); } } // Export talk page (if not excluded) if((ExportExcludeType.NONE == (ExportExcludeType.TALK & exclude)) && (!page.Title.IsTalk)) { PageBE talkPage = PageBL.GetPageByTitle(page.Title.AsTalk()); if((null != talkPage) && (0 < talkPage.ID)) { PageExport(false, exclude, talkPage); } } // Export subpages (if not excluded) if(recursive) { ICollection<PageBE> children = PageBL.GetChildren(page, true); children = PermissionsBL.FilterDisallowed(DekiContext.Current.User, PageBL.GetChildren(page, true), false, Permissions.READ); if(children != null) { foreach(PageBE child in children) { PageExport(recursive, exclude, child); } } } } private void AttachmentExport(ExportExcludeType exclude, PageBE page, AttachmentBE file) { // Export the file if(!_uris.ContainsKey(AttachmentBL.Instance.GetUriContent(file))) { _uris.Add(AttachmentBL.Instance.GetUriContent(file), null); XDoc manifestDoc = new XDoc("file").Elem("filename", file.Name) .Elem("path", page.Title.AsRelativePath(_relToTitle)) .Start("contents").Attr("type", file.MimeType.ToString()).End(); Add(AttachmentBL.Instance.GetUriContent(file), manifestDoc); } // Export the file properties (if not excluded) if(ExportExcludeType.NONE == (ExportExcludeType.PROPS & exclude)) { IList<PropertyBE> properties = PropertyBL.Instance.GetResources(file.ResourceId, ResourceBE.Type.FILE, null, DeletionFilter.ACTIVEONLY); foreach(PropertyBE property in properties) { PropertyExport(page, file, property); } } } private void PropertyExport(PageBE page, AttachmentBE file, PropertyBE property) { // Export the property XUri propertyUri = null; string filename = null; if(null != file) { propertyUri = property.UriContent(AttachmentBL.Instance.GetUri(file)); filename = file.Name; } else { propertyUri = property.UriContent(PageBL.GetUriCanonical(page)); } if(!_uris.ContainsKey(propertyUri)) { _uris.Add(propertyUri, null); XDoc manifestDoc = new XDoc("property").Elem("name", property.Name) .Elem("filename", filename) .Elem("path", page.Title.AsRelativePath(_relToTitle)) .Start("contents").Attr("type", property.MimeType.ToString()).End(); Add(propertyUri, manifestDoc); } } private void Add(XUri href, XDoc manifestXml) { string data = Convert.ToString(_id++); AddRequest("GET", href, data); manifestXml.Attr("dataid", data); _manifestDoc.Add(manifestXml); } private void AddRequest(string method, XUri href, string data) { _requestDoc.Start("request") .Attr("method", method) .Attr("href", href.ToString()) .Attr("dataid", data) .End(); } private void AddError(string reason, int status, XDoc doc) { _requestDoc.Start("warning").Attr("reason", reason).Attr("status", status).Add(doc).End(); } public XDoc ToDocument() { return new XDoc("export").Add(_requestDoc).Add(_manifestDoc); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B02_Continent (editable child object).<br/> /// This is a generated base class of <see cref="B02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="B03_SubContinentObjects"/> of type <see cref="B03_SubContinentColl"/> (1:M relation to <see cref="B04_SubContinent"/>)<br/> /// This class is an item of <see cref="B01_ContinentColl"/> collection. /// </remarks> [Serializable] public partial class B02_Continent : BusinessBase<B02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continent ID"); /// <summary> /// Gets the Continent ID. /// </summary> /// <value>The Continent ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continent Name"); /// <summary> /// Gets or sets the Continent Name. /// </summary> /// <value>The Continent Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_Child> B03_Continent_SingleObjectProperty = RegisterProperty<B03_Continent_Child>(p => p.B03_Continent_SingleObject, "B03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent Single Object ("parent load" child property). /// </summary> /// <value>The B03 Continent Single Object.</value> public B03_Continent_Child B03_Continent_SingleObject { get { return GetProperty(B03_Continent_SingleObjectProperty); } private set { LoadProperty(B03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<B03_Continent_ReChild> B03_Continent_ASingleObjectProperty = RegisterProperty<B03_Continent_ReChild>(p => p.B03_Continent_ASingleObject, "B03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the B03 Continent ASingle Object ("parent load" child property). /// </summary> /// <value>The B03 Continent ASingle Object.</value> public B03_Continent_ReChild B03_Continent_ASingleObject { get { return GetProperty(B03_Continent_ASingleObjectProperty); } private set { LoadProperty(B03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="B03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<B03_SubContinentColl> B03_SubContinentObjectsProperty = RegisterProperty<B03_SubContinentColl>(p => p.B03_SubContinentObjects, "B03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the B03 Sub Continent Objects ("parent load" child property). /// </summary> /// <value>The B03 Sub Continent Objects.</value> public B03_SubContinentColl B03_SubContinentObjects { get { return GetProperty(B03_SubContinentObjectsProperty); } private set { LoadProperty(B03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="B02_Continent"/> object.</returns> internal static B02_Continent NewB02_Continent() { return DataPortal.CreateChild<B02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="B02_Continent"/> object.</returns> internal static B02_Continent GetB02_Continent(SafeDataReader dr) { B02_Continent obj = new B02_Continent(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.LoadProperty(B03_SubContinentObjectsProperty, B03_SubContinentColl.NewB03_SubContinentColl()); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B02_Continent() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(B03_Continent_SingleObjectProperty, DataPortal.CreateChild<B03_Continent_Child>()); LoadProperty(B03_Continent_ASingleObjectProperty, DataPortal.CreateChild<B03_Continent_ReChild>()); LoadProperty(B03_SubContinentObjectsProperty, DataPortal.CreateChild<B03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> internal void FetchChildren(SafeDataReader dr) { dr.NextResult(); while (dr.Read()) { var child = B03_Continent_Child.GetB03_Continent_Child(dr); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID1); obj.LoadProperty(B03_Continent_SingleObjectProperty, child); } dr.NextResult(); while (dr.Read()) { var child = B03_Continent_ReChild.GetB03_Continent_ReChild(dr); var obj = ((B01_ContinentColl)Parent).FindB02_ContinentByParentProperties(child.continent_ID2); obj.LoadProperty(B03_Continent_ASingleObjectProperty, child); } dr.NextResult(); var b03_SubContinentColl = B03_SubContinentColl.GetB03_SubContinentColl(dr); b03_SubContinentColl.LoadItems((B01_ContinentColl)Parent); dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_Child.GetB05_SubContinent_Child(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B05_SubContinent_ReChild.GetB05_SubContinent_ReChild(dr); var obj = b03_SubContinentColl.FindB04_SubContinentByParentProperties(child.subContinent_ID2); obj.LoadChild(child); } dr.NextResult(); var b05_CountryColl = B05_CountryColl.GetB05_CountryColl(dr); b05_CountryColl.LoadItems(b03_SubContinentColl); dr.NextResult(); while (dr.Read()) { var child = B07_Country_Child.GetB07_Country_Child(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B07_Country_ReChild.GetB07_Country_ReChild(dr); var obj = b05_CountryColl.FindB06_CountryByParentProperties(child.country_ID2); obj.LoadChild(child); } dr.NextResult(); var b07_RegionColl = B07_RegionColl.GetB07_RegionColl(dr); b07_RegionColl.LoadItems(b05_CountryColl); dr.NextResult(); while (dr.Read()) { var child = B09_Region_Child.GetB09_Region_Child(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B09_Region_ReChild.GetB09_Region_ReChild(dr); var obj = b07_RegionColl.FindB08_RegionByParentProperties(child.region_ID2); obj.LoadChild(child); } dr.NextResult(); var b09_CityColl = B09_CityColl.GetB09_CityColl(dr); b09_CityColl.LoadItems(b07_RegionColl); dr.NextResult(); while (dr.Read()) { var child = B11_City_Child.GetB11_City_Child(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID1); obj.LoadChild(child); } dr.NextResult(); while (dr.Read()) { var child = B11_City_ReChild.GetB11_City_ReChild(dr); var obj = b09_CityColl.FindB10_CityByParentProperties(child.city_ID2); obj.LoadChild(child); } dr.NextResult(); var b11_CityRoadColl = B11_CityRoadColl.GetB11_CityRoadColl(dr); b11_CityRoadColl.LoadItems(b09_CityColl); } /// <summary> /// Inserts a new <see cref="B02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddB02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="B02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateB02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="B02_Continent"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteB02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(B03_Continent_SingleObjectProperty, DataPortal.CreateChild<B03_Continent_Child>()); LoadProperty(B03_Continent_ASingleObjectProperty, DataPortal.CreateChild<B03_Continent_ReChild>()); LoadProperty(B03_SubContinentObjectsProperty, DataPortal.CreateChild<B03_SubContinentColl>()); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <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); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Threading; using System.Threading.Tasks; using System.Runtime.ExceptionServices; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; namespace System.Net.Security { /* An authenticated stream based on NEGO SSP. The class that can be used by client and server side applications - to transfer Identities across the stream - to encrypt data based on NEGO SSP package In most cases the innerStream will be of type NetworkStream. On Win9x data encryption is not available and both sides have to explicitly drop SecurityLevel and MuatualAuth requirements. This is a simple wrapper class. All real work is done by internal NegoState class and the other partial implementation files. */ public partial class NegotiateStream : AuthenticatedStream { private readonly NegoState _negoState; private readonly string _package; private IIdentity _remoteIdentity; public NegotiateStream(Stream innerStream) : this(innerStream, false) { } public NegotiateStream(Stream innerStream, bool leaveInnerStreamOpen) : base(innerStream, leaveInnerStreamOpen) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState = new NegoState(innerStream); _package = NegoState.DefaultPackage; InitializeStreamPart(); #if DEBUG } #endif } public virtual IAsyncResult BeginAuthenticateAsClient(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel); LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback); _negoState.ProcessAuthentication(result); return result; #if DEBUG } #endif } public virtual void EndAuthenticateAsClient(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #if DEBUG } #endif } public virtual void AuthenticateAsServer() { AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsServer(ExtendedProtectionPolicy policy) { AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsServer(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { AuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel); } public virtual void AuthenticateAsServer(NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel); _negoState.ProcessAuthentication(null); #if DEBUG } #endif } public virtual IAsyncResult BeginAuthenticateAsServer(AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, null, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer(ExtendedProtectionPolicy policy, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, policy, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { return BeginAuthenticateAsServer(credential, null, requiredProtectionLevel, requiredImpersonationLevel, asyncCallback, asyncState); } public virtual IAsyncResult BeginAuthenticateAsServer( NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.ValidateCreateContext(_package, credential, string.Empty, policy, requiredProtectionLevel, requiredImpersonationLevel); LazyAsyncResult result = new LazyAsyncResult(_negoState, asyncState, asyncCallback); _negoState.ProcessAuthentication(result); return result; #if DEBUG } #endif } // public virtual void EndAuthenticateAsServer(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.EndProcessAuthentication(asyncResult); #if DEBUG } #endif } public virtual void AuthenticateAsClient() { AuthenticateAsClient((NetworkCredential)CredentialCache.DefaultCredentials, null, string.Empty, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient(NetworkCredential credential, string targetName) { AuthenticateAsClient(credential, null, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient(NetworkCredential credential, ChannelBinding binding, string targetName) { AuthenticateAsClient(credential, binding, targetName, ProtectionLevel.EncryptAndSign, TokenImpersonationLevel.Identification); } public virtual void AuthenticateAsClient( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { AuthenticateAsClient(credential, null, targetName, requiredProtectionLevel, allowedImpersonationLevel); } public virtual void AuthenticateAsClient( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.ValidateCreateContext(_package, false, credential, targetName, binding, requiredProtectionLevel, allowedImpersonationLevel); _negoState.ProcessAuthentication(null); #if DEBUG } #endif } public virtual Task AuthenticateAsClientAsync() { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, string targetName) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, targetName, null); } public virtual Task AuthenticateAsClientAsync( NetworkCredential credential, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsClientAsync(NetworkCredential credential, ChannelBinding binding, string targetName) { return Task.Factory.FromAsync(BeginAuthenticateAsClient, EndAuthenticateAsClient, credential, binding, targetName, null); } public virtual Task AuthenticateAsClientAsync( NetworkCredential credential, ChannelBinding binding, string targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsClient(credential, binding, targetName, requiredProtectionLevel, allowedImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public virtual Task AuthenticateAsServerAsync() { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, null); } public virtual Task AuthenticateAsServerAsync(ExtendedProtectionPolicy policy) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, policy, null); } public virtual Task AuthenticateAsServerAsync(NetworkCredential credential, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { return Task.Factory.FromAsync(BeginAuthenticateAsServer, EndAuthenticateAsServer, credential, requiredProtectionLevel, requiredImpersonationLevel, null); } public virtual Task AuthenticateAsServerAsync( NetworkCredential credential, ExtendedProtectionPolicy policy, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel requiredImpersonationLevel) { return Task.Factory.FromAsync((callback, state) => BeginAuthenticateAsServer(credential, policy, requiredProtectionLevel, requiredImpersonationLevel, callback, state), EndAuthenticateAsClient, null); } public override bool IsAuthenticated { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsAuthenticated; #if DEBUG } #endif } } public override bool IsMutuallyAuthenticated { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsMutuallyAuthenticated; #if DEBUG } #endif } } public override bool IsEncrypted { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsEncrypted; #if DEBUG } #endif } } public override bool IsSigned { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsSigned; #if DEBUG } #endif } } public override bool IsServer { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.IsServer; #if DEBUG } #endif } } public virtual TokenImpersonationLevel ImpersonationLevel { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif return _negoState.AllowedImpersonation; #if DEBUG } #endif } } public virtual IIdentity RemoteIdentity { get { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif if (_remoteIdentity == null) { _remoteIdentity = _negoState.GetIdentity(); } return _remoteIdentity; #if DEBUG } #endif } } // // Stream contract implementation // public override bool CanSeek { get { return false; } } public override bool CanRead { get { return IsAuthenticated && InnerStream.CanRead; } } public override bool CanTimeout { get { return InnerStream.CanTimeout; } } public override bool CanWrite { get { return IsAuthenticated && InnerStream.CanWrite; } } public override int ReadTimeout { get { return InnerStream.ReadTimeout; } set { InnerStream.ReadTimeout = value; } } public override int WriteTimeout { get { return InnerStream.WriteTimeout; } set { InnerStream.WriteTimeout = value; } } public override long Length { get { return InnerStream.Length; } } public override long Position { get { return InnerStream.Position; } set { throw new NotSupportedException(SR.net_noseek); } } public override void SetLength(long value) { InnerStream.SetLength(value); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.net_noseek); } public override void Flush() { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif InnerStream.Flush(); #if DEBUG } #endif } public override Task FlushAsync(CancellationToken cancellationToken) { return InnerStream.FlushAsync(cancellationToken); } protected override void Dispose(bool disposing) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif try { _negoState.Close(); } finally { base.Dispose(disposing); } #if DEBUG } #endif } public override async ValueTask DisposeAsync() { try { _negoState.Close(); } finally { await base.DisposeAsync().ConfigureAwait(false); } } public override int Read(byte[] buffer, int offset, int count) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return InnerStream.Read(buffer, offset, count); } return ProcessRead(buffer, offset, count, null); #if DEBUG } #endif } public override void Write(byte[] buffer, int offset, int count) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { InnerStream.Write(buffer, offset, count); return; } ProcessWrite(buffer, offset, count, null); #if DEBUG } #endif } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.Begin(InnerStream.ReadAsync(buffer, offset, count), asyncCallback, asyncState); } BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessRead(buffer, offset, count, asyncRequest); return bufferResult; #if DEBUG } #endif } public override int EndRead(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.End<int>(asyncResult); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _NestedRead, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception e) { if (e is IOException) { ExceptionDispatchInfo.Throw(e); } throw new IOException(SR.net_io_read, e); } return bufferResult.Int32Result; #if DEBUG } #endif } // // public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { return TaskToApm.Begin(InnerStream.WriteAsync(buffer, offset, count), asyncCallback, asyncState); } BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessWrite(buffer, offset, count, asyncRequest); return bufferResult; #if DEBUG } #endif } public override void EndWrite(IAsyncResult asyncResult) { #if DEBUG using (DebugThreadTracking.SetThreadKind(ThreadKinds.User)) { #endif _negoState.CheckThrow(true); if (!_negoState.CanGetSecureStream) { TaskToApm.End(asyncResult); return; } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult)); } if (Interlocked.Exchange(ref _NestedWrite, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception e) { if (e is IOException) { ExceptionDispatchInfo.Throw(e); } throw new IOException(SR.net_io_write, e); } #if DEBUG } #endif } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Internal.Resources.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Internal.Resources { /// <summary> /// Operations for managing preview features. /// </summary> internal partial class Features : IServiceOperations<FeatureClient>, IFeatures { /// <summary> /// Initializes a new instance of the Features class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal Features(FeatureClient client) { this._client = client; } private FeatureClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Internal.Resources.FeatureClient. /// </summary> public FeatureClient Client { get { return this._client; } } /// <summary> /// Get all features under the subscription. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Previewed feature information. /// </returns> public async Task<FeatureResponse> GetAsync(string resourceProviderNamespace, string featureName, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (featureName == null) { throw new ArgumentNullException("featureName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("featureName", featureName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Features/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/features/"; url = url + Uri.EscapeDataString(featureName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-08-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); result.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); result.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); result.Type = typeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. The namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of previewed features. /// </returns> public async Task<FeatureOperationsListResult> ListAsync(string resourceProviderNamespace, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Features/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/features"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-08-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureOperationsListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { FeatureResponse featureResponseInstance = new FeatureResponse(); result.Features.Add(featureResponseInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); featureResponseInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); featureResponseInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); featureResponseInstance.Id = idInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); featureResponseInstance.Type = typeInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of previewed features for all the providers in the /// current subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of previewed features. /// </returns> public async Task<FeatureOperationsListResult> ListAllAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Features/features"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-08-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureOperationsListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { FeatureResponse featureResponseInstance = new FeatureResponse(); result.Features.Add(featureResponseInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); featureResponseInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); featureResponseInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); featureResponseInstance.Id = idInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); featureResponseInstance.Type = typeInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of previewed features of a subscription. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of previewed features. /// </returns> public async Task<FeatureOperationsListResult> ListAllNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListAllNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureOperationsListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { FeatureResponse featureResponseInstance = new FeatureResponse(); result.Features.Add(featureResponseInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); featureResponseInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); featureResponseInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); featureResponseInstance.Id = idInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); featureResponseInstance.Type = typeInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of previewed features. /// </returns> public async Task<FeatureOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureOperationsListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { FeatureResponse featureResponseInstance = new FeatureResponse(); result.Features.Add(featureResponseInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); featureResponseInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); featureResponseInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); featureResponseInstance.Id = idInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); featureResponseInstance.Type = typeInstance; } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Registers for a previewed feature of a resource provider. /// </summary> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Previewed feature information. /// </returns> public async Task<FeatureResponse> RegisterAsync(string resourceProviderNamespace, string featureName, CancellationToken cancellationToken) { // Validate if (resourceProviderNamespace == null) { throw new ArgumentNullException("resourceProviderNamespace"); } if (featureName == null) { throw new ArgumentNullException("featureName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace); tracingParameters.Add("featureName", featureName); TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Features/providers/"; url = url + Uri.EscapeDataString(resourceProviderNamespace); url = url + "/features/"; url = url + Uri.EscapeDataString(featureName); url = url + "/register"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-08-01-preview"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result FeatureResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new FeatureResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { FeatureProperties propertiesInstance = new FeatureProperties(); result.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); result.Id = idInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); result.Type = typeInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using static OneOf.Functions; namespace OneOf { public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly T12 _value12; readonly T13 _value13; readonly T14 _value14; readonly int _index; protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> input) { _index = input.Index; switch (_index) { case 0: _value0 = input.AsT0; break; case 1: _value1 = input.AsT1; break; case 2: _value2 = input.AsT2; break; case 3: _value3 = input.AsT3; break; case 4: _value4 = input.AsT4; break; case 5: _value5 = input.AsT5; break; case 6: _value6 = input.AsT6; break; case 7: _value7 = input.AsT7; break; case 8: _value8 = input.AsT8; break; case 9: _value9 = input.AsT9; break; case 10: _value10 = input.AsT10; break; case 11: _value11 = input.AsT11; break; case 12: _value12 = input.AsT12; break; case 13: _value13 = input.AsT13; break; case 14: _value14 = input.AsT14; break; default: throw new InvalidOperationException(); } } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, 12 => _value12, 13 => _value13, 14 => _value14, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public bool IsT12 => _index == 12; public bool IsT13 => _index == 13; public bool IsT14 => _index == 14; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public T12 AsT12 => _index == 12 ? _value12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}"); public T13 AsT13 => _index == 13 ? _value13 : throw new InvalidOperationException($"Cannot return as T13 as result is T{_index}"); public T14 AsT14 => _index == 14 ? _value14 : throw new InvalidOperationException($"Cannot return as T14 as result is T{_index}"); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12, Action<T13> f13, Action<T14> f14) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } if (_index == 12 && f12 != null) { f12(_value12); return; } if (_index == 13 && f13 != null) { f13(_value13); return; } if (_index == 14 && f14 != null) { f14(_value14); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12, Func<T13, TResult> f13, Func<T14, TResult> f14) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } if (_index == 12 && f12 != null) { return f12(_value12); } if (_index == 13 && f13 != null) { return f13(_value13); } if (_index == 14 && f14 != null) { return f14(_value14); } throw new InvalidOperationException(); } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12, T13, T14> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12, T13, T14> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12, T13, T14> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12, T13, T14> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12, T13, T14> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, 12 => AsT12, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT11; } public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T13, T14> remainder) { value = IsT12 ? AsT12 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => default, 13 => AsT13, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT12; } public bool TryPickT13(out T13 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T14> remainder) { value = IsT13 ? AsT13 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => default, 14 => AsT14, _ => throw new InvalidOperationException() }; return this.IsT13; } public bool TryPickT14(out T14 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> remainder) { value = IsT14 ? AsT14 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, 13 => AsT13, 14 => default, _ => throw new InvalidOperationException() }; return this.IsT14; } bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), 12 => Equals(_value12, other._value12), 13 => Equals(_value13, other._value13), 14 => Equals(_value14, other._value14), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), 12 => FormatValue(_value12), 13 => FormatValue(_value13), 14 => FormatValue(_value14), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), 12 => _value12?.GetHashCode(), 13 => _value13?.GetHashCode(), 14 => _value14?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Ploeh.AutoFixture.Kernel { /// <summary> /// Base class for recursion handling. Tracks requests and reacts when a recursion point in the /// specimen creation process is detected. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The main responsibility of this class isn't to be a 'collection' (which, by the way, it isn't - it's just an Iterator).")] public class RecursionGuard : ISpecimenBuilderNode { private readonly ISpecimenBuilder builder; private readonly IRecursionHandler recursionHandler; private readonly IEqualityComparer comparer; private readonly ConcurrentDictionary<Thread, Stack<object>> _requestsByThread = new ConcurrentDictionary<Thread, Stack<object>>(); private Stack<object> GetMonitoredRequestsForCurrentThread() { return _requestsByThread.GetOrAdd(Thread.CurrentThread, _ => new Stack<object>()); } private readonly int recursionDepth; /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard"/> class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> [Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler) instead.")] public RecursionGuard(ISpecimenBuilder builder) : this(builder, EqualityComparer<object>.Default) { } /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard" /> /// class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> /// <param name="recursionHandler"> /// An <see cref="IRecursionHandler" /> that will handle a recursion /// situation, if one is detected. /// </param> public RecursionGuard( ISpecimenBuilder builder, IRecursionHandler recursionHandler) : this( builder, recursionHandler, EqualityComparer<object>.Default, 1) { } /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard" /> /// class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> /// <param name="recursionHandler"> /// An <see cref="IRecursionHandler" /> that will handle a recursion /// situation, if one is detected. /// </param> /// <param name="recursionDepth">The recursion depth at which the request will be treated as a recursive /// request</param> public RecursionGuard( ISpecimenBuilder builder, IRecursionHandler recursionHandler, int recursionDepth) : this( builder, recursionHandler, EqualityComparer<object>.Default, recursionDepth) { } /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard"/> class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> /// <param name="comparer"> /// An IEqualityComparer implementation to use when comparing requests to determine recursion. /// </param> [Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer, int) instead.")] public RecursionGuard(ISpecimenBuilder builder, IEqualityComparer comparer) { if (builder == null) { throw new ArgumentNullException("builder"); } if (comparer == null) { throw new ArgumentNullException("comparer"); } this.builder = builder; this.comparer = comparer; this.recursionDepth = 1; } /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard" /> /// class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> /// <param name="recursionHandler"> /// An <see cref="IRecursionHandler" /> that will handle a recursion /// situation, if one is detected. /// </param> /// <param name="comparer"> /// An <see cref="IEqualityComparer" /> implementation to use when /// comparing requests to determine recursion. /// </param> /// <exception cref="System.ArgumentNullException"> /// builder /// or /// recursionHandler /// or /// comparer /// </exception> [Obsolete("This constructor overload is obsolete and will be removed in a future version of AutoFixture. Please use RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer, int) instead.")] public RecursionGuard( ISpecimenBuilder builder, IRecursionHandler recursionHandler, IEqualityComparer comparer) : this( builder, recursionHandler, comparer, 1) { } /// <summary> /// Initializes a new instance of the <see cref="RecursionGuard" /> /// class. /// </summary> /// <param name="builder">The intercepted builder to decorate.</param> /// <param name="recursionHandler"> /// An <see cref="IRecursionHandler" /> that will handle a recursion /// situation, if one is detected. /// </param> /// <param name="comparer"> /// An <see cref="IEqualityComparer" /> implementation to use when /// comparing requests to determine recursion. /// </param> /// <param name="recursionDepth">The recursion depth at which the request will be treated as a recursive /// request.</param> /// <exception cref="System.ArgumentNullException"> /// builder /// or /// recursionHandler /// or /// comparer /// </exception> /// <exception cref="System.ArgumentOutOfRangeException">recursionDepth is less than one.</exception> public RecursionGuard( ISpecimenBuilder builder, IRecursionHandler recursionHandler, IEqualityComparer comparer, int recursionDepth) { if (builder == null) throw new ArgumentNullException("builder"); if (recursionHandler == null) throw new ArgumentNullException("recursionHandler"); if (comparer == null) throw new ArgumentNullException("comparer"); if (recursionDepth < 1) throw new ArgumentOutOfRangeException("recursionDepth", "Recursion depth must be greater than 0."); this.builder = builder; this.recursionHandler = recursionHandler; this.comparer = comparer; this.recursionDepth = recursionDepth; } /// <summary> /// Gets the decorated builder supplied via the constructor. /// </summary> /// <seealso cref="RecursionGuard(ISpecimenBuilder)"/> /// <seealso cref="RecursionGuard(ISpecimenBuilder, IEqualityComparer)" /> public ISpecimenBuilder Builder { get { return this.builder; } } /// <summary> /// Gets the recursion handler originally supplied as a constructor /// argument. /// </summary> /// <value> /// The recursion handler used to handle recursion situations. /// </value> /// <seealso cref="RecursionGuard(ISpecimenBuilder, IRecursionHandler)" /> /// <seealso cref="RecursionGuard(ISpecimenBuilder, IRecursionHandler, IEqualityComparer)" /> public IRecursionHandler RecursionHandler { get { return this.recursionHandler; } } /// <summary> /// The recursion depth at which the request will be treated as a /// recursive request /// </summary> public int RecursionDepth { get { return recursionDepth; } } /// <summary>Gets the comparer supplied via the constructor.</summary> /// <seealso cref="RecursionGuard(ISpecimenBuilder, IEqualityComparer)" /> public IEqualityComparer Comparer { get { return this.comparer; } } /// <summary> /// Gets the recorded requests so far. /// </summary> protected IEnumerable RecordedRequests { get { return GetMonitoredRequestsForCurrentThread(); } } /// <summary> /// Handles a request that would cause recursion. /// </summary> /// <param name="request">The recursion causing request.</param> /// <returns>The specimen to return.</returns> [Obsolete("This method will be removed in a future version of AutoFixture. Use IRecursionHandler.HandleRecursiveRequest instead.")] public virtual object HandleRecursiveRequest(object request) { return this.recursionHandler.HandleRecursiveRequest( request, GetMonitoredRequestsForCurrentThread()); } /// <summary> /// Creates a new specimen based on a request. /// </summary> /// <param name="request">The request that describes what to create.</param> /// <param name="context">A container that can be used to create other specimens.</param> /// <returns> /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance. /// </returns> /// <remarks> /// <para> /// The <paramref name="request"/> can be any object, but will often be a /// <see cref="Type"/> or other <see cref="System.Reflection.MemberInfo"/> instances. /// </para> /// </remarks> public object Create(object request, ISpecimenContext context) { var requestsForCurrentThread = GetMonitoredRequestsForCurrentThread(); if (requestsForCurrentThread.Count > 0) { // This is performance-sensitive code when used repeatedly over many requests. // See discussion at https://github.com/AutoFixture/AutoFixture/pull/218 var requestsArray = requestsForCurrentThread.ToArray(); int numRequestsSameAsThisOne = 0; for (int i = 0; i < requestsArray.Length; i++) { var existingRequest = requestsArray[i]; if (this.comparer.Equals(existingRequest, request)) { numRequestsSameAsThisOne++; } if (numRequestsSameAsThisOne >= this.RecursionDepth) { #pragma warning disable 618 return this.HandleRecursiveRequest(request); #pragma warning restore 618 } } } requestsForCurrentThread.Push(request); try { return this.builder.Create(request, context); } finally { requestsForCurrentThread.Pop(); } } /// <summary>Composes the supplied builders.</summary> /// <param name="builders">The builders to compose.</param> /// <returns>A <see cref="ISpecimenBuilderNode" /> instance.</returns> /// <remarks> /// <para> /// Note to implementers: /// </para> /// <para> /// The intent of this method is to compose the supplied /// <paramref name="builders" /> into a new instance of the type /// implementing <see cref="ISpecimenBuilderNode" />. Thus, the /// concrete return type is expected to the same type as the type /// implementing the method. However, it is not considered a failure to /// deviate from this idiom - it would just not be a mainstream /// implementation. /// </para> /// <para> /// The returned instance is normally expected to contain the builders /// supplied as an argument, but again this is not strictly required. /// The implementation may decide to filter the sequence or add to it /// during composition. /// </para> /// </remarks> public virtual ISpecimenBuilderNode Compose( IEnumerable<ISpecimenBuilder> builders) { var composedBuilder = CompositeSpecimenBuilder.ComposeIfMultiple( builders); return new RecursionGuard( composedBuilder, this.recursionHandler, this.comparer, this.RecursionDepth); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{ISpecimenBuilder}" /> that can be used to /// iterate through the collection. /// </returns> public virtual IEnumerator<ISpecimenBuilder> GetEnumerator() { yield return this.builder; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #if FEATURE_CORECLR namespace System.Reflection.Emit { using System; using System.Security; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics.SymbolStore; //----------------------------------------------------------------------------------- // On Telesto, we don't ship the ISymWrapper.dll assembly. However, ReflectionEmit // relies on that assembly to write out managed PDBs. // // This file implements the minimum subset of ISymWrapper.dll required to restore // that functionality. Namely, the SymWriter and SymDocumentWriter objects. // // Ideally we wouldn't need ISymWrapper.dll on desktop either - it's an ugly piece // of legacy. We could just use this (or COM-interop code) everywhere, but we might // have to worry about compatibility. // // We've now got a real implementation even when no debugger is attached. It's // up to the runtime to ensure it doesn't provide us with an insecure writer // (eg. diasymreader) in the no-trust scenarios (no debugger, partial-trust code). //----------------------------------------------------------------------------------- //------------------------------------------------------------------------------ // SymWrapperCore is never instantiated and is used as an encapsulation class. // It is our "ISymWrapper.dll" assembly within an assembly. //------------------------------------------------------------------------------ class SymWrapperCore { //------------------------------------------------------------------------------ // Block instantiation //------------------------------------------------------------------------------ private SymWrapperCore() { } //------------------------------------------------------------------------------ // Implements Telesto's version of SymDocumentWriter (in the desktop world, // this type is exposed from ISymWrapper.dll.) // // The only thing user code can do with this wrapper is to receive it from // SymWriter.DefineDocument and pass it back to SymWriter.DefineSequencePoints. //------------------------------------------------------------------------------ private unsafe class SymDocumentWriter : ISymbolDocumentWriter { //------------------------------------------------------------------------------ // Ctor //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal SymDocumentWriter(PunkSafeHandle pDocumentWriterSafeHandle) { m_pDocumentWriterSafeHandle = pDocumentWriterSafeHandle; // The handle is actually a pointer to a native ISymUnmanagedDocumentWriter. m_pDocWriter = (ISymUnmanagedDocumentWriter *)m_pDocumentWriterSafeHandle.DangerousGetHandle(); m_vtable = (ISymUnmanagedDocumentWriterVTable)(Marshal.PtrToStructure(m_pDocWriter->m_unmanagedVTable, typeof(ISymUnmanagedDocumentWriterVTable))); } //------------------------------------------------------------------------------ // Returns the underlying ISymUnmanagedDocumentWriter* (as a safehandle.) //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal PunkSafeHandle GetUnmanaged() { return m_pDocumentWriterSafeHandle; } //========================================================================================= // Public interface methods start here. (Well actually, they're all NotSupported // stubs since that's what they are on the real ISymWrapper.dll.) //========================================================================================= //------------------------------------------------------------------------------ // SetSource() wrapper //------------------------------------------------------------------------------ void ISymbolDocumentWriter.SetSource(byte[] source) { throw new NotSupportedException(); // Intentionally not supported to match desktop CLR } //------------------------------------------------------------------------------ // SetCheckSum() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif void ISymbolDocumentWriter.SetCheckSum(Guid algorithmId, byte [] checkSum) { int hr = m_vtable.SetCheckSum(m_pDocWriter, algorithmId, (uint)checkSum.Length, checkSum); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } [System.Security.SecurityCritical] private delegate int DSetCheckSum(ISymUnmanagedDocumentWriter * pThis, Guid algorithmId, uint checkSumSize, [In] byte[] checkSum); //------------------------------------------------------------------------------ // This layout must match the unmanaged ISymUnmanagedDocumentWriter* COM vtable // exactly. If a member is declared as an IntPtr rather than a delegate, it means // we don't call that particular member. //------------------------------------------------------------------------------ [System.Security.SecurityCritical] [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedDocumentWriterVTable { internal IntPtr QueryInterface; internal IntPtr AddRef; internal IntPtr Release; internal IntPtr SetSource; #if FEATURE_CORECLR [System.Security.SecurityCritical] #endif internal DSetCheckSum SetCheckSum; } //------------------------------------------------------------------------------ // This layout must match the (start) of the unmanaged ISymUnmanagedDocumentWriter // COM object. //------------------------------------------------------------------------------ [System.Security.SecurityCritical] [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedDocumentWriter { internal IntPtr m_unmanagedVTable; } //------------------------------------------------------------------------------ // Stores underlying ISymUnmanagedDocumentWriter* pointer (wrapped in a safehandle.) //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif private PunkSafeHandle m_pDocumentWriterSafeHandle; [SecurityCritical] private ISymUnmanagedDocumentWriter * m_pDocWriter; //------------------------------------------------------------------------------ // Stores the "managed vtable" (actually a structure full of delegates that // P/Invoke to the corresponding unmanaged COM methods.) //------------------------------------------------------------------------------ [SecurityCritical] private ISymUnmanagedDocumentWriterVTable m_vtable; } // class SymDocumentWriter //------------------------------------------------------------------------------ // Implements Telesto's version of SymWriter (in the desktop world, // this type is expored from ISymWrapper.dll.) //------------------------------------------------------------------------------ internal unsafe class SymWriter : ISymbolWriter { //------------------------------------------------------------------------------ // Creates a SymWriter. The SymWriter is a managed wrapper around the unmanaged // symbol writer provided by the runtime (ildbsymlib or diasymreader.dll). //------------------------------------------------------------------------------ internal static ISymbolWriter CreateSymWriter() { return new SymWriter(); } //------------------------------------------------------------------------------ // Basic ctor. You'd think this ctor would take the unmanaged symwriter object as an argument // but to fit in with existing desktop code, the unmanaged writer is passed in // through a subsequent call to InternalSetUnderlyingWriter //------------------------------------------------------------------------------ private SymWriter() { } //========================================================================================= // Public interface methods start here. //========================================================================================= //------------------------------------------------------------------------------ // Initialize() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.Initialize(IntPtr emitter, String filename, bool fFullBuild) { int hr = m_vtable.Initialize(m_pWriter, emitter, filename, (IntPtr)0, fFullBuild); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // DefineDocument() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif ISymbolDocumentWriter ISymbolWriter.DefineDocument(String url, Guid language, Guid languageVendor, Guid documentType) { PunkSafeHandle psymUnmanagedDocumentWriter = new PunkSafeHandle(); int hr = m_vtable.DefineDocument(m_pWriter, url, ref language, ref languageVendor, ref documentType, out psymUnmanagedDocumentWriter); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } if (psymUnmanagedDocumentWriter.IsInvalid) { return null; } return new SymDocumentWriter(psymUnmanagedDocumentWriter); } //------------------------------------------------------------------------------ // SetUserEntryPoint() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.SetUserEntryPoint(SymbolToken entryMethod) { int hr = m_vtable.SetUserEntryPoint(m_pWriter, entryMethod.GetToken()); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // OpenMethod() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.OpenMethod(SymbolToken method) { int hr = m_vtable.OpenMethod(m_pWriter, method.GetToken()); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // CloseMethod() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.CloseMethod() { int hr = m_vtable.CloseMethod(m_pWriter); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // DefineSequencePoints() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.DefineSequencePoints(ISymbolDocumentWriter document, int[] offsets, int[] lines, int[] columns, int[] endLines, int[] endColumns) { int spCount = 0; if (offsets != null) { spCount = offsets.Length; } else if (lines != null) { spCount = lines.Length; } else if (columns != null) { spCount = columns.Length; } else if (endLines != null) { spCount = endLines.Length; } else if (endColumns != null) { spCount = endColumns.Length; } if (spCount == 0) { return; } if ( (offsets != null && offsets.Length != spCount) || (lines != null && lines.Length != spCount) || (columns != null && columns.Length != spCount) || (endLines != null && endLines.Length != spCount) || (endColumns != null && endColumns.Length != spCount) ) { throw new ArgumentException(); } // Sure, claim to accept any type that implements ISymbolDocumentWriter but the only one that actually // works is the one returned by DefineDocument. The desktop ISymWrapper commits the same signature fraud. // Ideally we'd just return a sealed opaque cookie type, which had an internal accessor to // get the writer out. // Regardless, this cast is important for security - we cannot allow our caller to provide // arbitrary instances of this interface. SymDocumentWriter docwriter = (SymDocumentWriter)document; int hr = m_vtable.DefineSequencePoints(m_pWriter, docwriter.GetUnmanaged(), spCount, offsets, lines, columns, endLines, endColumns); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // OpenScope() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif int ISymbolWriter.OpenScope(int startOffset) { int ret; int hr = m_vtable.OpenScope(m_pWriter, startOffset, out ret); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } return ret; } //------------------------------------------------------------------------------ // CloseScope() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.CloseScope(int endOffset) { int hr = m_vtable.CloseScope(m_pWriter, endOffset); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // SetScopeRange() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.SetScopeRange(int scopeID, int startOffset, int endOffset) { int hr = m_vtable.SetScopeRange(m_pWriter, scopeID, startOffset, endOffset); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // DefineLocalVariable() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.DefineLocalVariable(String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset) { int hr = m_vtable.DefineLocalVariable(m_pWriter, name, (int)attributes, signature.Length, signature, (int)addrKind, addr1, addr2, addr3, startOffset, endOffset); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // DefineParameter() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.DefineParameter(String name, ParameterAttributes attributes, int sequence, SymAddressKind addrKind, int addr1, int addr2, int addr3) { throw new NotSupportedException(); // Intentionally not supported to match desktop CLR } //------------------------------------------------------------------------------ // DefineField() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.DefineField(SymbolToken parent, String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { throw new NotSupportedException(); // Intentionally not supported to match desktop CLR } //------------------------------------------------------------------------------ // DefineGlobalVariable() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.DefineGlobalVariable(String name, FieldAttributes attributes, byte[] signature, SymAddressKind addrKind, int addr1, int addr2, int addr3) { throw new NotSupportedException(); // Intentionally not supported to match desktop CLR } //------------------------------------------------------------------------------ // Close() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.Close() { int hr = m_vtable.Close(m_pWriter); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // SetSymAttribute() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.SetSymAttribute(SymbolToken parent, String name, byte[] data) { int hr = m_vtable.SetSymAttribute(m_pWriter, parent.GetToken(), name, data.Length, data); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // OpenNamespace() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.OpenNamespace(String name) { int hr = m_vtable.OpenNamespace(m_pWriter, name); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // CloseNamespace() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.CloseNamespace() { int hr = m_vtable.CloseNamespace(m_pWriter); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // UsingNamespace() wrapper //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif void ISymbolWriter.UsingNamespace(String name) { int hr = m_vtable.UsingNamespace(m_pWriter, name); if (hr < 0) { throw Marshal.GetExceptionForHR(hr); } } //------------------------------------------------------------------------------ // SetMethodSourceRange() wrapper //------------------------------------------------------------------------------ void ISymbolWriter.SetMethodSourceRange(ISymbolDocumentWriter startDoc, int startLine, int startColumn, ISymbolDocumentWriter endDoc, int endLine, int endColumn) { throw new NotSupportedException(); // Intentionally not supported to match desktop CLR } //------------------------------------------------------------------------------ // SetUnderlyingWriter() wrapper. //------------------------------------------------------------------------------ void ISymbolWriter.SetUnderlyingWriter(IntPtr ppUnderlyingWriter) { throw new NotSupportedException(); // Intentionally not supported on Telesto as it's a very unsafe api } //------------------------------------------------------------------------------ // InternalSetUnderlyingWriter() wrapper. // // Furnishes the native ISymUnmanagedWriter* pointer. // // The parameter is actually a pointer to a pointer to an ISymUnmanagedWriter. As // with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on pointers // furnished through SetUnderlyingWriter. Lifetime management is entirely up to the caller. //------------------------------------------------------------------------------ #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal void InternalSetUnderlyingWriter(IntPtr ppUnderlyingWriter) { m_pWriter = *((ISymUnmanagedWriter**)ppUnderlyingWriter); m_vtable = (ISymUnmanagedWriterVTable) (Marshal.PtrToStructure(m_pWriter->m_unmanagedVTable, typeof(ISymUnmanagedWriterVTable))); } //------------------------------------------------------------------------------ // Define delegates for the unmanaged COM methods we invoke. //------------------------------------------------------------------------------ [System.Security.SecurityCritical] private delegate int DInitialize(ISymUnmanagedWriter* pthis, IntPtr emitter, //IUnknown* [MarshalAs(UnmanagedType.LPWStr)] String filename, //WCHAR* IntPtr pIStream, //IStream* [MarshalAs(UnmanagedType.Bool)] bool fFullBuild ); [System.Security.SecurityCritical] private delegate int DDefineDocument(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String url, [In] ref Guid language, [In] ref Guid languageVender, [In] ref Guid documentType, [Out] out PunkSafeHandle ppsymUnmanagedDocumentWriter ); [System.Security.SecurityCritical] private delegate int DSetUserEntryPoint(ISymUnmanagedWriter* pthis, int entryMethod); [System.Security.SecurityCritical] private delegate int DOpenMethod(ISymUnmanagedWriter* pthis, int entryMethod); [System.Security.SecurityCritical] private delegate int DCloseMethod(ISymUnmanagedWriter* pthis); [System.Security.SecurityCritical] private delegate int DDefineSequencePoints(ISymUnmanagedWriter* pthis, PunkSafeHandle document, int spCount, [In] int[] offsets, [In] int[] lines, [In] int[] columns, [In] int[] endLines, [In] int[] endColumns); [System.Security.SecurityCritical] private delegate int DOpenScope(ISymUnmanagedWriter* pthis, int startOffset, [Out] out int pretval); [System.Security.SecurityCritical] private delegate int DCloseScope(ISymUnmanagedWriter* pthis, int endOffset); [System.Security.SecurityCritical] private delegate int DSetScopeRange(ISymUnmanagedWriter* pthis, int scopeID, int startOffset, int endOffset); [System.Security.SecurityCritical] private delegate int DDefineLocalVariable(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name, int attributes, int cSig, [In] byte[] signature, int addrKind, int addr1, int addr2, int addr3, int startOffset, int endOffset ); [System.Security.SecurityCritical] private delegate int DClose(ISymUnmanagedWriter* pthis); [System.Security.SecurityCritical] private delegate int DSetSymAttribute(ISymUnmanagedWriter* pthis, int parent, [MarshalAs(UnmanagedType.LPWStr)] String name, int cData, [In] byte[] data ); [System.Security.SecurityCritical] private delegate int DOpenNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name); [System.Security.SecurityCritical] private delegate int DCloseNamespace(ISymUnmanagedWriter* pthis); [System.Security.SecurityCritical] private delegate int DUsingNamespace(ISymUnmanagedWriter* pthis, [MarshalAs(UnmanagedType.LPWStr)] String name); //------------------------------------------------------------------------------ // This layout must match the unmanaged ISymUnmanagedWriter* COM vtable // exactly. If a member is declared as an IntPtr rather than a delegate, it means // we don't call that particular member. //------------------------------------------------------------------------------ [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedWriterVTable { internal IntPtr QueryInterface; internal IntPtr AddRef; internal IntPtr Release; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DDefineDocument DefineDocument; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DSetUserEntryPoint SetUserEntryPoint; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DOpenMethod OpenMethod; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DCloseMethod CloseMethod; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DOpenScope OpenScope; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DCloseScope CloseScope; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DSetScopeRange SetScopeRange; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DDefineLocalVariable DefineLocalVariable; internal IntPtr DefineParameter; internal IntPtr DefineField; internal IntPtr DefineGlobalVariable; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DClose Close; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DSetSymAttribute SetSymAttribute; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DOpenNamespace OpenNamespace; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DCloseNamespace CloseNamespace; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DUsingNamespace UsingNamespace; internal IntPtr SetMethodSourceRange; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DInitialize Initialize; internal IntPtr GetDebugInfo; #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal DDefineSequencePoints DefineSequencePoints; } //------------------------------------------------------------------------------ // This layout must match the (start) of the unmanaged ISymUnmanagedWriter // COM object. //------------------------------------------------------------------------------ [StructLayout(LayoutKind.Sequential)] private struct ISymUnmanagedWriter { internal IntPtr m_unmanagedVTable; } //------------------------------------------------------------------------------ // Stores native ISymUnmanagedWriter* pointer. // // As with the real ISymWrapper.dll, ISymWrapper performs *no* Release (or AddRef) on this pointer. // Managing lifetime is up to the caller (coreclr.dll). //------------------------------------------------------------------------------ [SecurityCritical] private ISymUnmanagedWriter *m_pWriter; //------------------------------------------------------------------------------ // Stores the "managed vtable" (actually a structure full of delegates that // P/Invoke to the corresponding unmanaged COM methods.) //------------------------------------------------------------------------------ private ISymUnmanagedWriterVTable m_vtable; } // class SymWriter } //class SymWrapperCore //-------------------------------------------------------------------------------------- // SafeHandle for RAW MTA IUnknown's. // // ! Because the Release occurs in the finalizer thread, this safehandle really takes // ! an ostrich approach to apartment issues. We only tolerate this here because we're emulating // ! the desktop CLR's use of ISymWrapper which also pays lip service to COM apartment rules. // ! // ! However, think twice about pulling this safehandle out for other uses. // // Had to make this a non-nested class since FCall's don't like to bind to nested classes. //-------------------------------------------------------------------------------------- #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif sealed class PunkSafeHandle : SafeHandle { #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal PunkSafeHandle() : base((IntPtr)0, true) { } [SecurityCritical] override protected bool ReleaseHandle() { m_Release(handle); return true; } public override bool IsInvalid { [SecurityCritical] get { return handle == ((IntPtr)0); } } private delegate void DRelease(IntPtr punk); // Delegate type for P/Invoking to coreclr.dll and doing an IUnknown::Release() private static DRelease m_Release; [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern IntPtr nGetDReleaseTarget(); // FCall gets us the native DRelease target (so we don't need named dllexport from coreclr.dll) #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif static PunkSafeHandle() { m_Release = (DRelease)(Marshal.GetDelegateForFunctionPointer(nGetDReleaseTarget(), typeof(DRelease))); m_Release((IntPtr)0); // make one call to make sure the delegate is fully prepped before we're in the critical finalizer situation. } } // PunkSafeHandle } //namespace System.Reflection.Emit #endif //FEATURE_CORECLR
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Net; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.InterfaceCommander; using OpenSim.Region.CoreModules.World.Terrain.FileLoaders; using OpenSim.Region.CoreModules.World.Terrain.FloodBrushes; using OpenSim.Region.CoreModules.World.Terrain.PaintBrushes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Terrain { public class TerrainModule : INonSharedRegionModule, ICommandableModule, ITerrainModule { #region StandardTerrainEffects enum /// <summary> /// A standard set of terrain brushes and effects recognised by viewers /// </summary> public enum StandardTerrainEffects : byte { Flatten = 0, Raise = 1, Lower = 2, Smooth = 3, Noise = 4, Revert = 5, // Extended brushes Erode = 255, Weather = 254, Olsen = 253 } #endregion private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private readonly Commander m_commander = new Commander("terrain"); private readonly Dictionary<StandardTerrainEffects, ITerrainFloodEffect> m_floodeffects = new Dictionary<StandardTerrainEffects, ITerrainFloodEffect>(); private readonly Dictionary<string, ITerrainLoader> m_loaders = new Dictionary<string, ITerrainLoader>(); private readonly Dictionary<StandardTerrainEffects, ITerrainPaintableEffect> m_painteffects = new Dictionary<StandardTerrainEffects, ITerrainPaintableEffect>(); private ITerrainChannel m_channel; private Dictionary<string, ITerrainEffect> m_plugineffects; private ITerrainChannel m_revert; private Scene m_scene; private volatile bool m_tainted; private readonly UndoStack<LandUndoState> m_undo = new UndoStack<LandUndoState>(5); #region ICommandableModule Members public ICommander CommandInterface { get { return m_commander; } } #endregion #region INonSharedRegionModule Members /// <summary> /// Creates and initialises a terrain module for a region /// </summary> /// <param name="scene">Region initialising</param> /// <param name="config">Config for the region</param> public void Initialise(IConfigSource config) { } public void AddRegion(Scene scene) { m_scene = scene; // Install terrain module in the simulator lock (m_scene) { if (m_scene.Heightmap == null) { m_channel = new TerrainChannel(); m_scene.Heightmap = m_channel; m_revert = new TerrainChannel(); UpdateRevertMap(); } else { m_channel = m_scene.Heightmap; m_revert = new TerrainChannel(); UpdateRevertMap(); } m_scene.RegisterModuleInterface<ITerrainModule>(this); m_scene.EventManager.OnNewClient += EventManager_OnNewClient; m_scene.EventManager.OnPluginConsole += EventManager_OnPluginConsole; m_scene.EventManager.OnTerrainTick += EventManager_OnTerrainTick; } InstallDefaultEffects(); LoadPlugins(); } public void RegionLoaded(Scene scene) { //Do this here to give file loaders time to initialize and //register their supported file extensions and file formats. InstallInterfaces(); } public void RemoveRegion(Scene scene) { lock (m_scene) { // remove the commands m_scene.UnregisterModuleCommander(m_commander.Name); // remove the event-handlers m_scene.EventManager.OnTerrainTick -= EventManager_OnTerrainTick; m_scene.EventManager.OnPluginConsole -= EventManager_OnPluginConsole; m_scene.EventManager.OnNewClient -= EventManager_OnNewClient; // remove the interface m_scene.UnregisterModuleInterface<ITerrainModule>(this); } } public void Close() { } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "TerrainModule"; } } #endregion #region ITerrainModule Members public void UndoTerrain(ITerrainChannel channel) { m_channel = channel; } /// <summary> /// Loads a terrain file from disk and installs it in the scene. /// </summary> /// <param name="filename">Filename to terrain file. Type is determined by extension.</param> public void LoadFromFile(string filename) { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { try { ITerrainChannel channel = loader.Value.LoadFile(filename); if (channel.Width != Constants.RegionSize || channel.Height != Constants.RegionSize) { // TerrainChannel expects a RegionSize x RegionSize map, currently throw new ArgumentException(String.Format("wrong size, use a file with size {0} x {1}", Constants.RegionSize, Constants.RegionSize)); } m_log.DebugFormat("[TERRAIN]: Loaded terrain, wd/ht: {0}/{1}", channel.Width, channel.Height); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } catch (NotImplementedException) { m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value + " parser does not support file loading. (May be save only)"); throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value)); } catch (FileNotFoundException) { m_log.Error( "[TERRAIN]: Unable to load heightmap, file not found. (A directory permissions error may also cause this)"); throw new TerrainException( String.Format("unable to load heightmap: file {0} not found (or permissions do not allow access", filename)); } catch (ArgumentException e) { m_log.ErrorFormat("[TERRAIN]: Unable to load heightmap: {0}", e.Message); throw new TerrainException( String.Format("Unable to load heightmap: {0}", e.Message)); } } CheckForTerrainUpdates(); m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully"); return; } } m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format."); throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename)); } /// <summary> /// Saves the current heightmap to a specified file. /// </summary> /// <param name="filename">The destination filename</param> public void SaveToFile(string filename) { try { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { loader.Value.SaveFile(filename, m_channel); return; } } } catch (NotImplementedException) { m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented."); throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented")); } catch (IOException ioe) { m_log.Error(String.Format("[TERRAIN]: Unable to save to {0}, {1}", filename, ioe.Message)); throw new TerrainException(String.Format("Unable to save heightmap: {0}", ioe.Message)); } } /// <summary> /// Loads a terrain file from the specified URI /// </summary> /// <param name="filename">The name of the terrain to load</param> /// <param name="pathToTerrainHeightmap">The URI to the terrain height map</param> public void LoadFromStream(string filename, Uri pathToTerrainHeightmap) { LoadFromStream(filename, URIFetch(pathToTerrainHeightmap)); } /// <summary> /// Loads a terrain file from a stream and installs it in the scene. /// </summary> /// <param name="filename">Filename to terrain file. Type is determined by extension.</param> /// <param name="stream"></param> public void LoadFromStream(string filename, Stream stream) { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { try { ITerrainChannel channel = loader.Value.LoadStream(stream); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } catch (NotImplementedException) { m_log.Error("[TERRAIN]: Unable to load heightmap, the " + loader.Value + " parser does not support file loading. (May be save only)"); throw new TerrainException(String.Format("unable to load heightmap: parser {0} does not support loading", loader.Value)); } } CheckForTerrainUpdates(); m_log.Info("[TERRAIN]: File (" + filename + ") loaded successfully"); return; } } m_log.Error("[TERRAIN]: Unable to load heightmap, no file loader available for that format."); throw new TerrainException(String.Format("unable to load heightmap from file {0}: no loader available for that format", filename)); } private static Stream URIFetch(Uri uri) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); // request.Credentials = credentials; request.ContentLength = 0; request.KeepAlive = false; WebResponse response = request.GetResponse(); Stream file = response.GetResponseStream(); if (response.ContentLength == 0) throw new Exception(String.Format("{0} returned an empty file", uri.ToString())); // return new BufferedStream(file, (int) response.ContentLength); return new BufferedStream(file, 1000000); } /// <summary> /// Modify Land /// </summary> /// <param name="pos">Land-position (X,Y,0)</param> /// <param name="size">The size of the brush (0=small, 1=medium, 2=large)</param> /// <param name="action">0=LAND_LEVEL, 1=LAND_RAISE, 2=LAND_LOWER, 3=LAND_SMOOTH, 4=LAND_NOISE, 5=LAND_REVERT</param> /// <param name="agentId">UUID of script-owner</param> public void ModifyTerrain(UUID user, Vector3 pos, byte size, byte action, UUID agentId) { float duration = 0.25f; if (action == 0) duration = 4.0f; client_OnModifyTerrain(user, (float)pos.Z, duration, size, action, pos.Y, pos.X, pos.Y, pos.X, agentId); } /// <summary> /// Saves the current heightmap to a specified stream. /// </summary> /// <param name="filename">The destination filename. Used here only to identify the image type</param> /// <param name="stream"></param> public void SaveToStream(string filename, Stream stream) { try { foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { loader.Value.SaveStream(stream, m_channel); return; } } } catch (NotImplementedException) { m_log.Error("Unable to save to " + filename + ", saving of this file format has not been implemented."); throw new TerrainException(String.Format("Unable to save heightmap: saving of this file format not implemented")); } } public void TaintTerrain () { CheckForTerrainUpdates(); } #region Plugin Loading Methods private void LoadPlugins() { m_plugineffects = new Dictionary<string, ITerrainEffect>(); string plugineffectsPath = "Terrain"; // Load the files in the Terrain/ dir if (!Directory.Exists(plugineffectsPath)) return; string[] files = Directory.GetFiles(plugineffectsPath); foreach (string file in files) { m_log.Info("Loading effects in " + file); try { Assembly library = Assembly.LoadFrom(file); foreach (Type pluginType in library.GetTypes()) { try { if (pluginType.IsAbstract || pluginType.IsNotPublic) continue; string typeName = pluginType.Name; if (pluginType.GetInterface("ITerrainEffect", false) != null) { ITerrainEffect terEffect = (ITerrainEffect) Activator.CreateInstance(library.GetType(pluginType.ToString())); InstallPlugin(typeName, terEffect); } else if (pluginType.GetInterface("ITerrainLoader", false) != null) { ITerrainLoader terLoader = (ITerrainLoader) Activator.CreateInstance(library.GetType(pluginType.ToString())); m_loaders[terLoader.FileExtension] = terLoader; m_log.Info("L ... " + typeName); } } catch (AmbiguousMatchException) { } } } catch (BadImageFormatException) { } } } public void InstallPlugin(string pluginName, ITerrainEffect effect) { lock (m_plugineffects) { if (!m_plugineffects.ContainsKey(pluginName)) { m_plugineffects.Add(pluginName, effect); m_log.Info("E ... " + pluginName); } else { m_plugineffects[pluginName] = effect; m_log.Warn("E ... " + pluginName + " (Replaced)"); } } } #endregion #endregion /// <summary> /// Installs into terrain module the standard suite of brushes /// </summary> private void InstallDefaultEffects() { // Draggable Paint Brush Effects m_painteffects[StandardTerrainEffects.Raise] = new RaiseSphere(); m_painteffects[StandardTerrainEffects.Lower] = new LowerSphere(); m_painteffects[StandardTerrainEffects.Smooth] = new SmoothSphere(); m_painteffects[StandardTerrainEffects.Noise] = new NoiseSphere(); m_painteffects[StandardTerrainEffects.Flatten] = new FlattenSphere(); m_painteffects[StandardTerrainEffects.Revert] = new RevertSphere(m_revert); m_painteffects[StandardTerrainEffects.Erode] = new ErodeSphere(); m_painteffects[StandardTerrainEffects.Weather] = new WeatherSphere(); m_painteffects[StandardTerrainEffects.Olsen] = new OlsenSphere(); // Area of effect selection effects m_floodeffects[StandardTerrainEffects.Raise] = new RaiseArea(); m_floodeffects[StandardTerrainEffects.Lower] = new LowerArea(); m_floodeffects[StandardTerrainEffects.Smooth] = new SmoothArea(); m_floodeffects[StandardTerrainEffects.Noise] = new NoiseArea(); m_floodeffects[StandardTerrainEffects.Flatten] = new FlattenArea(); m_floodeffects[StandardTerrainEffects.Revert] = new RevertArea(m_revert); // Filesystem load/save loaders m_loaders[".r32"] = new RAW32(); m_loaders[".f32"] = m_loaders[".r32"]; m_loaders[".ter"] = new Terragen(); m_loaders[".raw"] = new LLRAW(); m_loaders[".jpg"] = new JPEG(); m_loaders[".jpeg"] = m_loaders[".jpg"]; m_loaders[".bmp"] = new BMP(); m_loaders[".png"] = new PNG(); m_loaders[".gif"] = new GIF(); m_loaders[".tif"] = new TIFF(); m_loaders[".tiff"] = m_loaders[".tif"]; } /// <summary> /// Saves the current state of the region into the revert map buffer. /// </summary> public void UpdateRevertMap() { int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { m_revert[x, y] = m_channel[x, y]; } } } /// <summary> /// Loads a tile from a larger terrain file and installs it into the region. /// </summary> /// <param name="filename">The terrain file to load</param> /// <param name="fileWidth">The width of the file in units</param> /// <param name="fileHeight">The height of the file in units</param> /// <param name="fileStartX">Where to begin our slice</param> /// <param name="fileStartY">Where to begin our slice</param> public void LoadFromFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY) { int offsetX = (int) m_scene.RegionInfo.RegionLocX - fileStartX; int offsetY = (int) m_scene.RegionInfo.RegionLocY - fileStartY; if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight) { // this region is included in the tile request foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { ITerrainChannel channel = loader.Value.LoadFile(filename, offsetX, offsetY, fileWidth, fileHeight, (int) Constants.RegionSize, (int) Constants.RegionSize); m_scene.Heightmap = channel; m_channel = channel; UpdateRevertMap(); } return; } } } } /// <summary> /// Saves the terrain to a larger terrain file. /// </summary> /// <param name="filename">The terrain file to save</param> /// <param name="fileWidth">The width of the file in units</param> /// <param name="fileHeight">The height of the file in units</param> /// <param name="fileStartX">Where to begin our slice</param> /// <param name="fileStartY">Where to begin our slice</param> public void SaveToFile(string filename, int fileWidth, int fileHeight, int fileStartX, int fileStartY) { int offsetX = (int)m_scene.RegionInfo.RegionLocX - fileStartX; int offsetY = (int)m_scene.RegionInfo.RegionLocY - fileStartY; if (offsetX >= 0 && offsetX < fileWidth && offsetY >= 0 && offsetY < fileHeight) { // this region is included in the tile request foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { if (filename.EndsWith(loader.Key)) { lock (m_scene) { loader.Value.SaveFile(m_channel, filename, offsetX, offsetY, fileWidth, fileHeight, (int)Constants.RegionSize, (int)Constants.RegionSize); } return; } } } } /// <summary> /// Performs updates to the region periodically, synchronising physics and other heightmap aware sections /// </summary> private void EventManager_OnTerrainTick() { if (m_tainted) { m_tainted = false; m_scene.PhysicsScene.SetTerrain(m_channel.GetFloatsSerialised()); m_scene.SaveTerrain(); // Clients who look at the map will never see changes after they looked at the map, so i've commented this out. //m_scene.CreateTerrainTexture(true); } } /// <summary> /// Processes commandline input. Do not call directly. /// </summary> /// <param name="args">Commandline arguments</param> private void EventManager_OnPluginConsole(string[] args) { if (args[0] == "terrain") { if (args.Length == 1) { m_commander.ProcessConsoleCommand("help", new string[0]); return; } string[] tmpArgs = new string[args.Length - 2]; int i; for (i = 2; i < args.Length; i++) tmpArgs[i - 2] = args[i]; m_commander.ProcessConsoleCommand(args[1], tmpArgs); } } /// <summary> /// Installs terrain brush hook to IClientAPI /// </summary> /// <param name="client"></param> private void EventManager_OnNewClient(IClientAPI client) { client.OnModifyTerrain += client_OnModifyTerrain; client.OnBakeTerrain += client_OnBakeTerrain; client.OnLandUndo += client_OnLandUndo; client.OnUnackedTerrain += client_OnUnackedTerrain; } /// <summary> /// Checks to see if the terrain has been modified since last check /// but won't attempt to limit those changes to the limits specified in the estate settings /// currently invoked by the command line operations in the region server only /// </summary> private void CheckForTerrainUpdates() { CheckForTerrainUpdates(false); } /// <summary> /// Checks to see if the terrain has been modified since last check. /// If it has been modified, every all the terrain patches are sent to the client. /// If the call is asked to respect the estate settings for terrain_raise_limit and /// terrain_lower_limit, it will clamp terrain updates between these values /// currently invoked by client_OnModifyTerrain only and not the Commander interfaces /// <param name="respectEstateSettings">should height map deltas be limited to the estate settings limits</param> /// </summary> private void CheckForTerrainUpdates(bool respectEstateSettings) { bool shouldTaint = false; float[] serialised = m_channel.GetFloatsSerialised(); int x; for (x = 0; x < m_channel.Width; x += Constants.TerrainPatchSize) { int y; for (y = 0; y < m_channel.Height; y += Constants.TerrainPatchSize) { if (m_channel.Tainted(x, y)) { // if we should respect the estate settings then // fixup and height deltas that don't respect them if (respectEstateSettings && LimitChannelChanges(x, y)) { // this has been vetoed, so update // what we are going to send to the client serialised = m_channel.GetFloatsSerialised(); } SendToClients(serialised, x, y); shouldTaint = true; } } } if (shouldTaint) { m_tainted = true; } } /// <summary> /// Checks to see height deltas in the tainted terrain patch at xStart ,yStart /// are all within the current estate limits /// <returns>true if changes were limited, false otherwise</returns> /// </summary> private bool LimitChannelChanges(int xStart, int yStart) { bool changesLimited = false; double minDelta = m_scene.RegionInfo.RegionSettings.TerrainLowerLimit; double maxDelta = m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit; // loop through the height map for this patch and compare it against // the revert map for (int x = xStart; x < xStart + Constants.TerrainPatchSize; x++) { for (int y = yStart; y < yStart + Constants.TerrainPatchSize; y++) { double requestedHeight = m_channel[x, y]; double bakedHeight = m_revert[x, y]; double requestedDelta = requestedHeight - bakedHeight; if (requestedDelta > maxDelta) { m_channel[x, y] = bakedHeight + maxDelta; changesLimited = true; } else if (requestedDelta < minDelta) { m_channel[x, y] = bakedHeight + minDelta; //as lower is a -ve delta changesLimited = true; } } } return changesLimited; } private void client_OnLandUndo(IClientAPI client) { lock (m_undo) { if (m_undo.Count > 0) { LandUndoState goback = m_undo.Pop(); if (goback != null) goback.PlaybackState(); } } } /// <summary> /// Sends a copy of the current terrain to the scenes clients /// </summary> /// <param name="serialised">A copy of the terrain as a 1D float array of size w*h</param> /// <param name="x">The patch corner to send</param> /// <param name="y">The patch corner to send</param> private void SendToClients(float[] serialised, int x, int y) { m_scene.ForEachClient( delegate(IClientAPI controller) { controller.SendLayerData( x / Constants.TerrainPatchSize, y / Constants.TerrainPatchSize, serialised); } ); } private void client_OnModifyTerrain(UUID user, float height, float seconds, byte size, byte action, float north, float west, float south, float east, UUID agentId) { bool god = m_scene.Permissions.IsGod(user); bool allowed = false; if (north == south && east == west) { if (m_painteffects.ContainsKey((StandardTerrainEffects) action)) { bool[,] allowMask = new bool[m_channel.Width,m_channel.Height]; allowMask.Initialize(); int n = size + 1; if (n > 2) n = 4; int zx = (int) (west + 0.5); int zy = (int) (north + 0.5); int dx; for (dx=-n; dx<=n; dx++) { int dy; for (dy=-n; dy<=n; dy++) { int x = zx + dx; int y = zy + dy; if (x>=0 && y>=0 && x<m_channel.Width && y<m_channel.Height) { if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0))) { allowMask[x, y] = true; allowed = true; } } } } if (allowed) { StoreUndoState(); m_painteffects[(StandardTerrainEffects) action].PaintEffect( m_channel, allowMask, west, south, height, size, seconds); CheckForTerrainUpdates(!god); //revert changes outside estate limits } } else { m_log.Debug("Unknown terrain brush type " + action); } } else { if (m_floodeffects.ContainsKey((StandardTerrainEffects) action)) { bool[,] fillArea = new bool[m_channel.Width,m_channel.Height]; fillArea.Initialize(); int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { if (x < east && x > west) { if (y < north && y > south) { if (m_scene.Permissions.CanTerraformLand(agentId, new Vector3(x,y,0))) { fillArea[x, y] = true; allowed = true; } } } } } if (allowed) { StoreUndoState(); m_floodeffects[(StandardTerrainEffects) action].FloodEffect( m_channel, fillArea, size); CheckForTerrainUpdates(!god); //revert changes outside estate limits } } else { m_log.Debug("Unknown terrain flood type " + action); } } } private void client_OnBakeTerrain(IClientAPI remoteClient) { // Not a good permissions check (see client_OnModifyTerrain above), need to check the entire area. // for now check a point in the centre of the region if (m_scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, true)) { InterfaceBakeTerrain(null); //bake terrain does not use the passed in parameter } } protected void client_OnUnackedTerrain(IClientAPI client, int patchX, int patchY) { //m_log.Debug("Terrain packet unacked, resending patch: " + patchX + " , " + patchY); client.SendLayerData(patchX, patchY, m_scene.Heightmap.GetFloatsSerialised()); } private void StoreUndoState() { lock (m_undo) { if (m_undo.Count > 0) { LandUndoState last = m_undo.Peek(); if (last != null) { if (last.Compare(m_channel)) return; } } LandUndoState nUndo = new LandUndoState(this, m_channel); m_undo.Push(nUndo); } } #region Console Commands private void InterfaceLoadFile(Object[] args) { LoadFromFile((string) args[0]); CheckForTerrainUpdates(); } private void InterfaceLoadTileFile(Object[] args) { LoadFromFile((string) args[0], (int) args[1], (int) args[2], (int) args[3], (int) args[4]); CheckForTerrainUpdates(); } private void InterfaceSaveFile(Object[] args) { SaveToFile((string) args[0]); } private void InterfaceSaveTileFile(Object[] args) { SaveToFile((string)args[0], (int)args[1], (int)args[2], (int)args[3], (int)args[4]); } private void InterfaceBakeTerrain(Object[] args) { UpdateRevertMap(); } private void InterfaceRevertTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] = m_revert[x, y]; CheckForTerrainUpdates(); } private void InterfaceFlipTerrain(Object[] args) { String direction = (String)args[0]; if (direction.ToLower().StartsWith("y")) { for (int x = 0; x < Constants.RegionSize; x++) { for (int y = 0; y < Constants.RegionSize / 2; y++) { double height = m_channel[x, y]; double flippedHeight = m_channel[x, (int)Constants.RegionSize - 1 - y]; m_channel[x, y] = flippedHeight; m_channel[x, (int)Constants.RegionSize - 1 - y] = height; } } } else if (direction.ToLower().StartsWith("x")) { for (int y = 0; y < Constants.RegionSize; y++) { for (int x = 0; x < Constants.RegionSize / 2; x++) { double height = m_channel[x, y]; double flippedHeight = m_channel[(int)Constants.RegionSize - 1 - x, y]; m_channel[x, y] = flippedHeight; m_channel[(int)Constants.RegionSize - 1 - x, y] = height; } } } else { m_log.Error("Unrecognised direction - need x or y"); } CheckForTerrainUpdates(); } private void InterfaceRescaleTerrain(Object[] args) { double desiredMin = (double)args[0]; double desiredMax = (double)args[1]; // determine desired scaling factor double desiredRange = desiredMax - desiredMin; //m_log.InfoFormat("Desired {0}, {1} = {2}", new Object[] { desiredMin, desiredMax, desiredRange }); if (desiredRange == 0d) { // delta is zero so flatten at requested height InterfaceFillTerrain(new Object[] { args[1] }); } else { //work out current heightmap range double currMin = double.MaxValue; double currMax = double.MinValue; int width = m_channel.Width; int height = m_channel.Height; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double currHeight = m_channel[x, y]; if (currHeight < currMin) { currMin = currHeight; } else if (currHeight > currMax) { currMax = currHeight; } } } double currRange = currMax - currMin; double scale = desiredRange / currRange; //m_log.InfoFormat("Current {0}, {1} = {2}", new Object[] { currMin, currMax, currRange }); //m_log.InfoFormat("Scale = {0}", scale); // scale the heightmap accordingly for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { double currHeight = m_channel[x, y] - currMin; m_channel[x, y] = desiredMin + (currHeight * scale); } } CheckForTerrainUpdates(); } } private void InterfaceElevateTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] += (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceMultiplyTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] *= (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceLowerTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] -= (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceFillTerrain(Object[] args) { int x, y; for (x = 0; x < m_channel.Width; x++) for (y = 0; y < m_channel.Height; y++) m_channel[x, y] = (double) args[0]; CheckForTerrainUpdates(); } private void InterfaceShowDebugStats(Object[] args) { double max = Double.MinValue; double min = double.MaxValue; double sum = 0; int x; for (x = 0; x < m_channel.Width; x++) { int y; for (y = 0; y < m_channel.Height; y++) { sum += m_channel[x, y]; if (max < m_channel[x, y]) max = m_channel[x, y]; if (min > m_channel[x, y]) min = m_channel[x, y]; } } double avg = sum / (m_channel.Height * m_channel.Width); m_log.Info("Channel " + m_channel.Width + "x" + m_channel.Height); m_log.Info("max/min/avg/sum: " + max + "/" + min + "/" + avg + "/" + sum); } private void InterfaceEnableExperimentalBrushes(Object[] args) { if ((bool) args[0]) { m_painteffects[StandardTerrainEffects.Revert] = new WeatherSphere(); m_painteffects[StandardTerrainEffects.Flatten] = new OlsenSphere(); m_painteffects[StandardTerrainEffects.Smooth] = new ErodeSphere(); } else { InstallDefaultEffects(); } } private void InterfaceRunPluginEffect(Object[] args) { if ((string) args[0] == "list") { m_log.Info("List of loaded plugins"); foreach (KeyValuePair<string, ITerrainEffect> kvp in m_plugineffects) { m_log.Info(kvp.Key); } return; } if ((string) args[0] == "reload") { LoadPlugins(); return; } if (m_plugineffects.ContainsKey((string) args[0])) { m_plugineffects[(string) args[0]].RunEffect(m_channel); CheckForTerrainUpdates(); } else { m_log.Warn("No such plugin effect loaded."); } } private void InstallInterfaces() { // Load / Save string supportedFileExtensions = ""; string supportedFilesSeparator = ""; foreach (KeyValuePair<string, ITerrainLoader> loader in m_loaders) { supportedFileExtensions += supportedFilesSeparator + loader.Key + " (" + loader.Value + ")"; supportedFilesSeparator = ", "; } Command loadFromFileCommand = new Command("load", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadFile, "Loads a terrain from a specified file."); loadFromFileCommand.AddArgument("filename", "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " + supportedFileExtensions, "String"); Command saveToFileCommand = new Command("save", CommandIntentions.COMMAND_NON_HAZARDOUS, InterfaceSaveFile, "Saves the current heightmap to a specified file."); saveToFileCommand.AddArgument("filename", "The destination filename for your heightmap, the file extension determines the format to save in. Supported extensions include: " + supportedFileExtensions, "String"); Command loadFromTileCommand = new Command("load-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLoadTileFile, "Loads a terrain from a section of a larger file."); loadFromTileCommand.AddArgument("filename", "The file you wish to load from, the file extension determines the loader to be used. Supported extensions include: " + supportedFileExtensions, "String"); loadFromTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer"); loadFromTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer"); loadFromTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file", "Integer"); loadFromTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file", "Integer"); Command saveToTileCommand = new Command("save-tile", CommandIntentions.COMMAND_HAZARDOUS, InterfaceSaveTileFile, "Saves the current heightmap to the larger file."); saveToTileCommand.AddArgument("filename", "The file you wish to save to, the file extension determines the loader to be used. Supported extensions include: " + supportedFileExtensions, "String"); saveToTileCommand.AddArgument("file width", "The width of the file in tiles", "Integer"); saveToTileCommand.AddArgument("file height", "The height of the file in tiles", "Integer"); saveToTileCommand.AddArgument("minimum X tile", "The X region coordinate of the first section on the file", "Integer"); saveToTileCommand.AddArgument("minimum Y tile", "The Y region coordinate of the first section on the file", "Integer"); // Terrain adjustments Command fillRegionCommand = new Command("fill", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFillTerrain, "Fills the current heightmap with a specified value."); fillRegionCommand.AddArgument("value", "The numeric value of the height you wish to set your region to.", "Double"); Command elevateCommand = new Command("elevate", CommandIntentions.COMMAND_HAZARDOUS, InterfaceElevateTerrain, "Raises the current heightmap by the specified amount."); elevateCommand.AddArgument("amount", "The amount of height to add to the terrain in meters.", "Double"); Command lowerCommand = new Command("lower", CommandIntentions.COMMAND_HAZARDOUS, InterfaceLowerTerrain, "Lowers the current heightmap by the specified amount."); lowerCommand.AddArgument("amount", "The amount of height to remove from the terrain in meters.", "Double"); Command multiplyCommand = new Command("multiply", CommandIntentions.COMMAND_HAZARDOUS, InterfaceMultiplyTerrain, "Multiplies the heightmap by the value specified."); multiplyCommand.AddArgument("value", "The value to multiply the heightmap by.", "Double"); Command bakeRegionCommand = new Command("bake", CommandIntentions.COMMAND_HAZARDOUS, InterfaceBakeTerrain, "Saves the current terrain into the regions revert map."); Command revertRegionCommand = new Command("revert", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRevertTerrain, "Loads the revert map terrain into the regions heightmap."); Command flipCommand = new Command("flip", CommandIntentions.COMMAND_HAZARDOUS, InterfaceFlipTerrain, "Flips the current terrain about the X or Y axis"); flipCommand.AddArgument("direction", "[x|y] the direction to flip the terrain in", "String"); Command rescaleCommand = new Command("rescale", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRescaleTerrain, "Rescales the current terrain to fit between the given min and max heights"); rescaleCommand.AddArgument("min", "min terrain height after rescaling", "Double"); rescaleCommand.AddArgument("max", "max terrain height after rescaling", "Double"); // Debug Command showDebugStatsCommand = new Command("stats", CommandIntentions.COMMAND_STATISTICAL, InterfaceShowDebugStats, "Shows some information about the regions heightmap for debugging purposes."); Command experimentalBrushesCommand = new Command("newbrushes", CommandIntentions.COMMAND_HAZARDOUS, InterfaceEnableExperimentalBrushes, "Enables experimental brushes which replace the standard terrain brushes. WARNING: This is a debug setting and may be removed at any time."); experimentalBrushesCommand.AddArgument("Enabled?", "true / false - Enable new brushes", "Boolean"); //Plugins Command pluginRunCommand = new Command("effect", CommandIntentions.COMMAND_HAZARDOUS, InterfaceRunPluginEffect, "Runs a specified plugin effect"); pluginRunCommand.AddArgument("name", "The plugin effect you wish to run, or 'list' to see all plugins", "String"); m_commander.RegisterCommand("load", loadFromFileCommand); m_commander.RegisterCommand("load-tile", loadFromTileCommand); m_commander.RegisterCommand("save", saveToFileCommand); m_commander.RegisterCommand("save-tile", saveToTileCommand); m_commander.RegisterCommand("fill", fillRegionCommand); m_commander.RegisterCommand("elevate", elevateCommand); m_commander.RegisterCommand("lower", lowerCommand); m_commander.RegisterCommand("multiply", multiplyCommand); m_commander.RegisterCommand("bake", bakeRegionCommand); m_commander.RegisterCommand("revert", revertRegionCommand); m_commander.RegisterCommand("newbrushes", experimentalBrushesCommand); m_commander.RegisterCommand("stats", showDebugStatsCommand); m_commander.RegisterCommand("effect", pluginRunCommand); m_commander.RegisterCommand("flip", flipCommand); m_commander.RegisterCommand("rescale", rescaleCommand); // Add this to our scene so scripts can call these functions m_scene.RegisterModuleCommander(m_commander); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.IO; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.Win32.SafeHandles; namespace System.Text { // Our input file data structures look like: // // Header structure looks like: // struct NLSPlusHeader // { // WORD[16] filename; // 32 bytes // WORD[4] version; // 8 bytes = 40 // e.g.: 3, 2, 0, 0 // WORD count; // 2 bytes = 42 // Number of code page indexes that will follow // } // // Each code page section looks like: // struct NLSCodePageIndex // { // WORD[16] codePageName; // 32 bytes // WORD codePage; // +2 bytes = 34 // WORD byteCount; // +2 bytes = 36 // DWORD offset; // +4 bytes = 40 // Bytes from beginning of FILE. // } // // Each code page then has its own header // struct NLSCodePage // { // WORD[16] codePageName; // 32 bytes // WORD[4] version; // 8 bytes = 40 // e.g.: 3.2.0.0 // WORD codePage; // 2 bytes = 42 // WORD byteCount; // 2 bytes = 44 // 1 or 2 byte code page (SBCS or DBCS) // WORD unicodeReplace; // 2 bytes = 46 // default replacement unicode character // WORD byteReplace; // 2 bytes = 48 // default replacement byte(s) // BYTE[] data; // data section // } internal abstract class BaseCodePageEncoding : EncodingNLS { internal const String CODE_PAGE_DATA_FILE_NAME = "codepages.nlp"; protected int dataTableCodePage; // Variables to help us allocate/mark our memory section correctly protected int iExtraBytes = 0; // Our private unicode-to-bytes best-fit-array, and vice versa. protected char[] arrayUnicodeBestFit = null; protected char[] arrayBytesBestFit = null; [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage) : this(codepage, codepage) { } [System.Security.SecurityCritical] // auto-generated internal BaseCodePageEncoding(int codepage, int dataCodePage) : base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null)) { SetFallbackEncoding(); // Remember number of code pages that we'll be using the table for. dataTableCodePage = dataCodePage; LoadCodePageTables(); } internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec) : base(codepage, enc, dec) { // Remember number of code pages that we'll be using the table for. dataTableCodePage = dataCodePage; LoadCodePageTables(); } // Just a helper as we cannot use 'this' when calling 'base(...)' private void SetFallbackEncoding() { (EncoderFallback as InternalEncoderBestFitFallback).encoding = this; (DecoderFallback as InternalDecoderBestFitFallback).encoding = this; } // // This is the header for the native data table that we load from CODE_PAGE_DATA_FILE_NAME. // // Explicit layout is used here since a syntax like char[16] can not be used in sequential layout. [StructLayout(LayoutKind.Explicit)] internal struct CodePageDataFileHeader { [FieldOffset(0)] internal char TableName; // WORD[16] [FieldOffset(0x20)] internal ushort Version; // WORD[4] [FieldOffset(0x28)] internal short CodePageCount; // WORD [FieldOffset(0x2A)] internal short unused1; // Add an unused WORD so that CodePages is aligned with DWORD boundary. } private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44; [StructLayout(LayoutKind.Explicit, Pack = 2)] internal unsafe struct CodePageIndex { [FieldOffset(0)] internal char CodePageName; // WORD[16] [FieldOffset(0x20)] internal short CodePage; // WORD [FieldOffset(0x22)] internal short ByteCount; // WORD [FieldOffset(0x24)] internal int Offset; // DWORD } [StructLayout(LayoutKind.Explicit)] internal unsafe struct CodePageHeader { [FieldOffset(0)] internal char CodePageName; // WORD[16] [FieldOffset(0x20)] internal ushort VersionMajor; // WORD [FieldOffset(0x22)] internal ushort VersionMinor; // WORD [FieldOffset(0x24)] internal ushort VersionRevision;// WORD [FieldOffset(0x26)] internal ushort VersionBuild; // WORD [FieldOffset(0x28)] internal short CodePage; // WORD [FieldOffset(0x2a)] internal short ByteCount; // WORD // 1 or 2 byte code page (SBCS or DBCS) [FieldOffset(0x2c)] internal char UnicodeReplace; // WORD // default replacement unicode character [FieldOffset(0x2e)] internal ushort ByteReplace; // WORD // default replacement bytes } private const int CODEPAGE_HEADER_SIZE = 48; // Initialize our global stuff private static byte[] s_codePagesDataHeader = new byte[CODEPAGE_DATA_FILE_HEADER_SIZE]; protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream(CODE_PAGE_DATA_FILE_NAME); protected static readonly Object s_streamLock = new Object(); // this lock used when reading from s_codePagesEncodingDataStream // Real variables protected byte[] m_codePageHeader = new byte[CODEPAGE_HEADER_SIZE]; protected int m_firstDataWordOffset; protected int m_dataSize; // Safe handle wrapper around section map view [System.Security.SecurityCritical] // auto-generated protected SafeAllocHHandle safeNativeMemoryHandle = null; internal static Stream GetEncodingDataStream(String tableName) { Debug.Assert(tableName != null, "table name can not be null"); // NOTE: We must reflect on a public type that is exposed in the contract here // (i.e. CodePagesEncodingProvider), otherwise we will not get a reference to // the right assembly. Stream stream = typeof(CodePagesEncodingProvider).GetTypeInfo().Assembly.GetManifestResourceStream(tableName); if (stream == null) { // We can not continue if we can't get the resource. throw new InvalidOperationException(); } // Read the header stream.Read(s_codePagesDataHeader, 0, s_codePagesDataHeader.Length); return stream; } // We need to load tables for our code page [System.Security.SecurityCritical] // auto-generated private unsafe void LoadCodePageTables() { if (!FindCodePage(dataTableCodePage)) { // Didn't have one throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, CodePage)); } // We had it, so load it LoadManagedCodePage(); } // Look up the code page pointer [System.Security.SecurityCritical] // auto-generated private unsafe bool FindCodePage(int codePage) { Debug.Assert(m_codePageHeader != null && m_codePageHeader.Length == CODEPAGE_HEADER_SIZE, "m_codePageHeader expected to match in size the struct CodePageHeader"); // Loop through all of the m_pCodePageIndex[] items to find our code page byte[] codePageIndex = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { // seek to the first CodePageIndex entry s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin); int codePagesCount; fixed (byte* pBytes = s_codePagesDataHeader) { CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes; codePagesCount = pDataHeader->CodePageCount; } fixed (byte* pBytes = codePageIndex) { CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes; for (int i = 0; i < codePagesCount; i++) { s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length); if (pCodePageIndex->CodePage == codePage) { // Found it! long position = s_codePagesEncodingDataStream.Position; s_codePagesEncodingDataStream.Seek((long)pCodePageIndex->Offset, SeekOrigin.Begin); s_codePagesEncodingDataStream.Read(m_codePageHeader, 0, m_codePageHeader.Length); m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position; // stream now pointing to the codepage data if (i == codePagesCount - 1) // last codepage { m_dataSize = (int)(s_codePagesEncodingDataStream.Length - pCodePageIndex->Offset - m_codePageHeader.Length); } else { // Read Next codepage data to get the offset and then calculate the size s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin); int currentOffset = pCodePageIndex->Offset; s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length); m_dataSize = pCodePageIndex->Offset - currentOffset - m_codePageHeader.Length; } return true; } } } } // Couldn't find it return false; } // Get our code page byte count [System.Security.SecurityCritical] // auto-generated internal static unsafe int GetCodePageByteSize(int codePage) { // Loop through all of the m_pCodePageIndex[] items to find our code page byte[] codePageIndex = new byte[sizeof(CodePageIndex)]; lock (s_streamLock) { // seek to the first CodePageIndex entry s_codePagesEncodingDataStream.Seek(CODEPAGE_DATA_FILE_HEADER_SIZE, SeekOrigin.Begin); int codePagesCount; fixed (byte* pBytes = s_codePagesDataHeader) { CodePageDataFileHeader* pDataHeader = (CodePageDataFileHeader*)pBytes; codePagesCount = pDataHeader->CodePageCount; } fixed (byte* pBytes = codePageIndex) { CodePageIndex* pCodePageIndex = (CodePageIndex*)pBytes; for (int i = 0; i < codePagesCount; i++) { s_codePagesEncodingDataStream.Read(codePageIndex, 0, codePageIndex.Length); if (pCodePageIndex->CodePage == codePage) { Debug.Assert(pCodePageIndex->ByteCount == 1 || pCodePageIndex->ByteCount == 2, "[BaseCodePageEncoding] Code page (" + codePage + ") has invalid byte size (" + pCodePageIndex->ByteCount + ") in table"); // Return what it says for byte count return pCodePageIndex->ByteCount; } } } } // Couldn't find it return 0; } // We have a managed code page entry, so load our tables [System.Security.SecurityCritical] protected abstract unsafe void LoadManagedCodePage(); // Allocate memory to load our code page [System.Security.SecurityCritical] // auto-generated protected unsafe byte* GetNativeMemory(int iSize) { if (safeNativeMemoryHandle == null) { byte* pNativeMemory = (byte*)Marshal.AllocHGlobal(iSize); Debug.Assert(pNativeMemory != null); safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)pNativeMemory); } return (byte*)safeNativeMemoryHandle.DangerousGetHandle(); } [System.Security.SecurityCritical] protected abstract unsafe void ReadBestFitTable(); [System.Security.SecuritySafeCritical] internal char[] GetBestFitUnicodeToBytesData() { // Read in our best fit table if necessary if (arrayUnicodeBestFit == null) ReadBestFitTable(); Debug.Assert(arrayUnicodeBestFit != null, "[BaseCodePageEncoding.GetBestFitUnicodeToBytesData]Expected non-null arrayUnicodeBestFit"); // Normally we don't have any best fit data. return arrayUnicodeBestFit; } [System.Security.SecuritySafeCritical] internal char[] GetBestFitBytesToUnicodeData() { // Read in our best fit table if necessary if (arrayBytesBestFit == null) ReadBestFitTable(); Debug.Assert(arrayBytesBestFit != null, "[BaseCodePageEncoding.GetBestFitBytesToUnicodeData]Expected non-null arrayBytesBestFit"); // Normally we don't have any best fit data. return arrayBytesBestFit; } // During the AppDomain shutdown the Encoding class may have already finalized, making the memory section // invalid. We detect that by validating the memory section handle then re-initializing the memory // section by calling LoadManagedCodePage() method and eventually the mapped file handle and // the memory section pointer will get finalized one more time. [System.Security.SecurityCritical] // auto-generated internal unsafe void CheckMemorySection() { if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero) { LoadManagedCodePage(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using NUnit.Framework; using SIL.Base32; namespace SIL.Tests.Base32Tests { [TestFixture] public class Base32Tests { static private string Encode (string s) { return Base32Convert.ToBase32String(Encoding.UTF7.GetBytes(s), Base32FormattingOptions.InsertTrailingPadding); } static private string EncodeOmitPadding(string s) { return Base32Convert.ToBase32String(Encoding.UTF7.GetBytes(s), Base32FormattingOptions.None); } static private string Decode(string s) { byte[] bytes = Base32Convert.FromBase32String(s, Base32FormattingOptions.InsertTrailingPadding); return Encoding.UTF7.GetString(bytes); } static private string DecodeOmitPadding(string s) { byte[] bytes = Base32Convert.FromBase32String(s, Base32FormattingOptions.None); return Encoding.UTF7.GetString(bytes); } [Test] public void Encode_EmptyString_EmptyString() { Assert.AreEqual(string.Empty, Encode("")); } [Test] public void Encode_null_throws() { Assert.Throws<ArgumentNullException>( () => Base32Convert.ToBase32String(null, Base32FormattingOptions.InsertTrailingPadding)); } [Test] public void Encode_rfc4648() { Assert.AreEqual("MY======", Encode("f")); Assert.AreEqual("MZXQ====", Encode("fo")); Assert.AreEqual("MZXW6===", Encode("foo")); Assert.AreEqual("MZXW6YQ=", Encode("foob")); Assert.AreEqual("MZXW6YTB", Encode("fooba")); Assert.AreEqual("MZXW6YTBOI======", Encode("foobar")); } [Test] public void EncodeOmitPadding_EmptyString_EmptyString() { Assert.AreEqual(string.Empty, EncodeOmitPadding("")); } [Test] public void EncodeOmitPadding_null_throws() { Assert.Throws<ArgumentNullException>( () => Base32Convert.ToBase32String(null, Base32FormattingOptions.None)); } [Test] public void EncodeOmitPadding_rfc4648() { Assert.AreEqual("MY", EncodeOmitPadding("f")); Assert.AreEqual("MZXQ", EncodeOmitPadding("fo")); Assert.AreEqual("MZXW6", EncodeOmitPadding("foo")); Assert.AreEqual("MZXW6YQ", EncodeOmitPadding("foob")); Assert.AreEqual("MZXW6YTB", EncodeOmitPadding("fooba")); Assert.AreEqual("MZXW6YTBOI", EncodeOmitPadding("foobar")); } [Test] public void Decode_EmptyString_EmptyString() { Assert.AreEqual(string.Empty, Decode("")); } [Test] public void Decode_null_throws() { Assert.Throws<ArgumentNullException>( () => Base32Convert.FromBase32String(null, Base32FormattingOptions.InsertTrailingPadding)); } [Test] public void Decode_wholealphabet() { Assert.AreEqual(36, Decode("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ234567======").Length); } [Test] public void DecodeOmitPadding_wholealphabet() { Assert.AreEqual(36, DecodeOmitPadding("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ234567").Length); } [Test] public void Decode_rfc4648() { Assert.AreEqual("f", Decode("MY======")); Assert.AreEqual("fo", Decode("MZXQ====")); Assert.AreEqual("foo", Decode("MZXW6===")); Assert.AreEqual("foob", Decode("MZXW6YQ=")); Assert.AreEqual("fooba", Decode("MZXW6YTB")); Assert.AreEqual("foobar", Decode("MZXW6YTBOI======")); } [Test] public void Decode_rfc4648_lowercase() { Assert.AreEqual("f", Decode("my======")); Assert.AreEqual("fo", Decode("mzxq====")); Assert.AreEqual("foo", Decode("mzxw6===")); Assert.AreEqual("foob", Decode("mzxw6yq=")); Assert.AreEqual("fooba", Decode("mzxw6ytb")); Assert.AreEqual("foobar", Decode("mzxw6ytboi======")); } [Test] public void Decode_CharacterNotInAlphabet_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("#y======", Base32FormattingOptions.InsertTrailingPadding)); } [Test] public void Decode_MisplacedPaddingCharacter_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("m=y======", Base32FormattingOptions.InsertTrailingPadding)); } [Test] public void Decode_WrongNumberOfPaddingCharacters_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("my=====", Base32FormattingOptions.InsertTrailingPadding)); } [Test] public void DecodeOmitPadding_EmptyString_EmptyString() { Assert.AreEqual(string.Empty, DecodeOmitPadding("")); } [Test] public void DecodeOmitPadding_null_throws() { Assert.Throws<ArgumentNullException>( () => Base32Convert.FromBase32String(null, Base32FormattingOptions.None)); } [Test] public void DecodeOmitPadding_rfc4648() { Assert.AreEqual("f", DecodeOmitPadding("MY")); Assert.AreEqual("fo", DecodeOmitPadding("MZXQ")); Assert.AreEqual("foo", DecodeOmitPadding("MZXW6")); Assert.AreEqual("foob", DecodeOmitPadding("MZXW6YQ")); Assert.AreEqual("fooba", DecodeOmitPadding("MZXW6YTB")); Assert.AreEqual("foobar", DecodeOmitPadding("MZXW6YTBOI")); } [Test] public void DecodeOmitPadding_rfc4648_lowercase() { Assert.AreEqual("f", DecodeOmitPadding("my")); Assert.AreEqual("fo", DecodeOmitPadding("mzxq")); Assert.AreEqual("foo", DecodeOmitPadding("mzxw6")); Assert.AreEqual("foob", DecodeOmitPadding("mzxw6yq")); Assert.AreEqual("fooba", DecodeOmitPadding("mzxw6ytb")); Assert.AreEqual("foobar", DecodeOmitPadding("mzxw6ytboi")); } [Test] public void DecodeOmitPadding_CharacterNotInAlphabet_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("#y", Base32FormattingOptions.None)); } [Test] public void DecodeOmitPadding_PaddingCharacter_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("my======", Base32FormattingOptions.None)); } [Test] public void DecodeOmitPadding_WrongNumberOfCharacters_1_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("1", Base32FormattingOptions.None)); } [Test] public void DecodeOmitPadding_WrongNumberOfCharacters_3_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("123", Base32FormattingOptions.None)); } [Test] public void DecodeOmitPadding_WrongNumberOfCharacters_6_throws() { Assert.Throws<ArgumentException>( () => Base32Convert.FromBase32String("123456", Base32FormattingOptions.None)); } [Test] [NUnit.Framework.Category("Long Running")] // ~7 seconds public void EncodeThenDecode_Roundtrip() { byte[] bytes = new byte[] { 0, 1, 18, 62, 95, 100, 148, 201, 254, 255 }; Permuter.VisitAll(EncodeThenDecode, bytes); Permuter.VisitAll(EncodeThenDecode, bytes, bytes); Permuter.VisitAll(EncodeThenDecode, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecode, bytes, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecode, bytes, bytes, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecode, bytes, bytes, bytes, bytes, bytes, bytes); } [Test] [NUnit.Framework.Category("Long Running")] // ~7 seconds public void EncodeThenDecodeNoPadding_Roundtrip() { byte[] bytes = new byte[] { 0, 1, 18, 62, 95, 100, 148, 201, 254, 255 }; Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes); Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes, bytes); Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes, bytes, bytes, bytes, bytes); Permuter.VisitAll(EncodeThenDecodeNoPadding, bytes, bytes, bytes, bytes, bytes, bytes); } static public void EncodeThenDecode(IEnumerator[] a) { List<byte> octets = new List<byte>(); for (int j = 1; j < a.Length; j++) { octets.Add((byte)a[j].Current); } byte[] result = Base32Convert.FromBase32String(Base32Convert.ToBase32String(octets, Base32FormattingOptions.InsertTrailingPadding), Base32FormattingOptions.InsertTrailingPadding); Assert.IsTrue(SameContent(result, octets, Comparer<byte>.Default)); } static public void EncodeThenDecodeNoPadding(IEnumerator[] a) { List<byte> octets = new List<byte>(); for (int j = 1; j < a.Length; j++) { octets.Add((byte)a[j].Current); } byte[] result = Base32Convert.FromBase32String(Base32Convert.ToBase32String(octets, Base32FormattingOptions.None), Base32FormattingOptions.None); Assert.IsTrue(SameContent(result, octets, Comparer<byte>.Default)); } static public bool SameContent<T>(IEnumerable<T> first, IEnumerable<T> second, Comparer<T> comparer) { IEnumerator<T> enumerator1 = first.GetEnumerator(); IEnumerator<T> enumerator2 = second.GetEnumerator(); while (enumerator1.MoveNext()) { if(!enumerator2.MoveNext()) { return false; } if(comparer.Compare(enumerator1.Current, enumerator2.Current) != 0) { return false; } } if (enumerator2.MoveNext()) return false; else return true; } } }
/* * 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 2005 Sun Microsystems, Inc. All rights reserved. */ using System; using java = biz.ritter.javapi; using javax = biz.ritter.javapix; namespace biz.ritter.javapix.xml.crypto.dsig { //import javax.xml.crypto.dom.DOMStructure; //import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; //import javax.xml.crypto.dsig.spec.*; //import javax.xml.crypto.dsig.dom.DOMSignContext; /*import java.security.InvalidAlgorithmParameterException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.Provider; import java.security.Security; */ /** * A factory for creating {@link XMLSignature} objects from scratch or * for unmarshalling an <code>XMLSignature</code> object from a corresponding * XML representation. * * <h2>XMLSignatureFactory Type</h2> * * <p>Each instance of <code>XMLSignatureFactory</code> supports a specific * XML mechanism type. To create an <code>XMLSignatureFactory</code>, call one * of the static {@link #getInstance getInstance} methods, passing in the XML * mechanism type desired, for example: * * <blockquote><code> * XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM"); * </code></blockquote> * * <p>The objects that this factory produces will be based * on DOM and abide by the DOM interoperability requirements as defined in the * <a href="../../../../overview-summary.html#DOM Mechanism Requirements">DOM * Mechanism Requirements</a> section of the API overview. See the * <a href="../../../../overview-summary.html#Service Provider">Service * Providers</a> section of the API overview for a list of standard mechanism * types. * * <p><code>XMLSignatureFactory</code> implementations are registered and loaded * using the {@link java.security.Provider} mechanism. * For example, a service provider that supports the * DOM mechanism would be specified in the <code>Provider</code> subclass as: * <pre> * put("XMLSignatureFactory.DOM", "org.example.DOMXMLSignatureFactory"); * </pre> * * <p>An implementation MUST minimally support the default mechanism type: DOM. * * <p>Note that a caller must use the same <code>XMLSignatureFactory</code> * instance to create the <code>XMLStructure</code>s of a particular * <code>XMLSignature</code> that is to be generated. The behavior is * undefined if <code>XMLStructure</code>s from different providers or * different mechanism types are used together. * * <p>Also, the <code>XMLStructure</code>s that are created by this factory * may contain state specific to the <code>XMLSignature</code> and are not * intended to be reusable. * * <h2>Creating XMLSignatures from scratch</h2> * * <p>Once the <code>XMLSignatureFactory</code> has been created, objects * can be instantiated by calling the appropriate method. For example, a * {@link Reference} instance may be created by invoking one of the * {@link #newReference newReference} methods. * * <h2>Unmarshalling XMLSignatures from XML</h2> * * <p>Alternatively, an <code>XMLSignature</code> may be created from an * existing XML representation by invoking the {@link #unmarshalXMLSignature * unmarshalXMLSignature} method and passing it a mechanism-specific * {@link XMLValidateContext} instance containing the XML content: * * <pre> * DOMValidateContext context = new DOMValidateContext(key, signatureElement); * XMLSignature signature = factory.unmarshalXMLSignature(context); * </pre> * * Each <code>XMLSignatureFactory</code> must support the required * <code>XMLValidateContext</code> types for that factory type, but may support * others. A DOM <code>XMLSignatureFactory</code> must support {@link * javax.xml.crypto.dsig.dom.DOMValidateContext} objects. * * <h2>Signing and marshalling XMLSignatures to XML</h2> * * Each <code>XMLSignature</code> created by the factory can also be * marshalled to an XML representation and signed, by invoking the * {@link XMLSignature#sign sign} method of the * {@link XMLSignature} object and passing it a mechanism-specific * {@link XMLSignContext} object containing the signing key and * marshalling parameters (see {@link DOMSignContext}). * For example: * * <pre> * DOMSignContext context = new DOMSignContext(privateKey, document); * signature.sign(context); * </pre> * * <b>Concurrent Access</b> * <p>The static methods of this class are guaranteed to be thread-safe. * Multiple threads may concurrently invoke the static methods defined in this * class with no ill effects. * * <p>However, this is not true for the non-static methods defined by this * class. Unless otherwise documented by a specific provider, threads that * need to access a single <code>XMLSignatureFactory</code> instance * concurrently should synchronize amongst themselves and provide the * necessary locking. Multiple threads each manipulating a different * <code>XMLSignatureFactory</code> instance need not synchronize. * * @author Sean Mullan * @author JSR 105 Expert Group */ public abstract class XMLSignatureFactory { private String mechanismType; private java.security.Provider provider; /** * Default constructor, for invocation by subclasses. */ protected XMLSignatureFactory() {} /** * Returns an <code>XMLSignatureFactory</code> that supports the * specified XML processing mechanism and representation type (ex: "DOM"). * * <p>This method uses the standard JCA provider lookup mechanism to * locate and instantiate an <code>XMLSignatureFactory</code> * implementation of the desired mechanism type. It traverses the list of * registered security <code>Provider</code>s, starting with the most * preferred <code>Provider</code>. A new <code>XMLSignatureFactory</code> * object from the first <code>Provider</code> that supports the specified * mechanism is returned. * * <p>Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param mechanismType the type of the XML processing mechanism and * representation. See the <a * href="../../../../overview-summary.html#Service Provider">Service * Providers</a> section of the API overview for a list of standard * mechanism types. * @return a new <code>XMLSignatureFactory</code> * @throws NullPointerException if <code>mechanismType</code> is * <code>null</code> * @throws NoSuchMechanismException if no <code>Provider</code> supports an * <code>XMLSignatureFactory</code> implementation for the specified * mechanism * @see Provider */ public static XMLSignatureFactory getInstance(String mechanismType) { if (mechanismType == null) { throw new java.lang.NullPointerException("mechanismType cannot be null"); } return findInstance(mechanismType, null); } private static XMLSignatureFactory findInstance(String mechanismType, java.security.Provider provider) { if (provider == null) { provider = getProvider("XMLSignatureFactory", mechanismType); } java.security.Provider.Service ps = provider.getService("XMLSignatureFactory", mechanismType); if (ps == null) { throw new NoSuchMechanismException("Cannot find " + mechanismType + " mechanism type"); } try { XMLSignatureFactory fac = (XMLSignatureFactory)ps.newInstance(null); fac.mechanismType = mechanismType; fac.provider = provider; return fac; } catch (java.security.NoSuchAlgorithmException nsae) { throw new NoSuchMechanismException("Cannot find " + mechanismType + " mechanism type", nsae); } } private static java.security.Provider getProvider(String engine, String mech) { java.security.Provider[] providers = java.security.Security.getProviders(engine + "." + mech); if (providers == null) { throw new NoSuchMechanismException("Mechanism type " + mech + " not available"); } return providers[0]; } /** * Returns an <code>XMLSignatureFactory</code> that supports the * requested XML processing mechanism and representation type (ex: "DOM"), * as supplied by the specified provider. Note that the specified * <code>Provider</code> object does not have to be registered in the * provider list. * * @param mechanismType the type of the XML processing mechanism and * representation. See the <a * href="../../../../overview-summary.html#Service Provider">Service * Providers</a> section of the API overview for a list of standard * mechanism types. * @param provider the <code>Provider</code> object * @return a new <code>XMLSignatureFactory</code> * @throws NullPointerException if <code>provider</code> or * <code>mechanismType</code> is <code>null</code> * @throws NoSuchMechanismException if an <code>XMLSignatureFactory</code> * implementation for the specified mechanism is not available * from the specified <code>Provider</code> object * @see Provider */ public static XMLSignatureFactory getInstance(String mechanismType, java.security.Provider provider) { if (mechanismType == null) { throw new java.lang.NullPointerException("mechanismType cannot be null"); } else if (provider == null) { throw new java.lang.NullPointerException("provider cannot be null"); } return findInstance(mechanismType, provider); } /** * Returns an <code>XMLSignatureFactory</code> that supports the * requested XML processing mechanism and representation type (ex: "DOM"), * as supplied by the specified provider. The specified provider must be * registered in the security provider list. * * <p>Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @param mechanismType the type of the XML processing mechanism and * representation. See the <a * href="../../../../overview-summary.html#Service Provider">Service * Providers</a> section of the API overview for a list of standard * mechanism types. * @param provider the string name of the provider * @return a new <code>XMLSignatureFactory</code> * @throws NoSuchProviderException if the specified provider is not * registered in the security provider list * @throws NullPointerException if <code>provider</code> or * <code>mechanismType</code> is <code>null</code> * @throws NoSuchMechanismException if an <code>XMLSignatureFactory</code> * implementation for the specified mechanism is not * available from the specified provider * @see Provider */ public static XMLSignatureFactory getInstance(String mechanismType, String provider){// throws NoSuchProviderException { if (mechanismType == null) { throw new java.lang.NullPointerException("mechanismType cannot be null"); } else if (provider == null) { throw new java.lang.NullPointerException("provider cannot be null"); } java.security.Provider prov = java.security.Security.getProvider(provider); if (prov == null) { throw new java.security.NoSuchProviderException("cannot find provider named " + provider); } return findInstance(mechanismType, prov); } /** * Returns an <code>XMLSignatureFactory</code> that supports the * default XML processing mechanism and representation type ("DOM"). * * <p>This method uses the standard JCA provider lookup mechanism to * locate and instantiate an <code>XMLSignatureFactory</code> * implementation of the default mechanism type. It traverses the list of * registered security <code>Provider</code>s, starting with the most * preferred <code>Provider</code>. A new <code>XMLSignatureFactory</code> * object from the first <code>Provider</code> that supports the DOM * mechanism is returned. * * <p>Note that the list of registered providers may be retrieved via * the {@link Security#getProviders() Security.getProviders()} method. * * @return a new <code>XMLSignatureFactory</code> * @throws NoSuchMechanismException if no <code>Provider</code> supports an * <code>XMLSignatureFactory</code> implementation for the DOM * mechanism * @see Provider */ public static XMLSignatureFactory getInstance() { return getInstance("DOM"); } /** * Returns the type of the XML processing mechanism and representation * supported by this <code>XMLSignatureFactory</code> (ex: "DOM"). * * @return the XML processing mechanism type supported by this * <code>XMLSignatureFactory</code> */ public String getMechanismType() { return mechanismType; } /** * Returns the provider of this <code>XMLSignatureFactory</code>. * * @return the provider of this <code>XMLSignatureFactory</code> */ public java.security.Provider getProvider() { return provider; } /** * Creates an <code>XMLSignature</code> and initializes it with the contents * of the specified <code>SignedInfo</code> and <code>KeyInfo</code> * objects. * * @param si the signed info * @param ki the key info (may be <code>null</code>) * @return an <code>XMLSignature</code> * @throws NullPointerException if <code>si</code> is <code>null</code> */ public abstract XMLSignature newXMLSignature(SignedInfo si, javax.xml.crypto.dsig.keyinfo.KeyInfo ki); /** * Creates an <code>XMLSignature</code> and initializes it with the * specified parameters. * * @param si the signed info * @param ki the key info (may be <code>null</code>) * @param objects a list of {@link XMLObject}s (may be empty or * <code>null</code>) * @param id the Id (may be <code>null</code>) * @param signatureValueId the SignatureValue Id (may be <code>null</code>) * @return an <code>XMLSignature</code> * @throws NullPointerException if <code>si</code> is <code>null</code> * @throws ClassCastException if any of the <code>objects</code> are not of * type <code>XMLObject</code> */ public abstract XMLSignature newXMLSignature(SignedInfo si, javax.xml.crypto.dsig.keyinfo.KeyInfo ki, java.util.List<Object> objects, String id, String signatureValueId); /** * Creates a <code>Reference</code> with the specified URI and digest * method. * * @param uri the reference URI (may be <code>null</code>) * @param dm the digest method * @return a <code>Reference</code> * @throws IllegalArgumentException if <code>uri</code> is not RFC 2396 * compliant * @throws NullPointerException if <code>dm</code> is <code>null</code> */ public abstract Reference newReference(String uri, DigestMethod dm); /** * Creates a <code>Reference</code> with the specified parameters. * * @param uri the reference URI (may be <code>null</code>) * @param dm the digest method * @param transforms a list of {@link Transform}s. The list is defensively * copied to protect against subsequent modification. May be * <code>null</code> or empty. * @param type the reference type, as a URI (may be <code>null</code>) * @param id the reference ID (may be <code>null</code>) * @return a <code>Reference</code> * @throws ClassCastException if any of the <code>transforms</code> are * not of type <code>Transform</code> * @throws IllegalArgumentException if <code>uri</code> is not RFC 2396 * compliant * @throws NullPointerException if <code>dm</code> is <code>null</code> */ public abstract Reference newReference(String uri, DigestMethod dm, java.util.List<Object> transforms, String type, String id); /** * Creates a <code>Reference</code> with the specified parameters and * pre-calculated digest value. * * <p>This method is useful when the digest value of a * <code>Reference</code> has been previously computed. See for example, * the * <a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=dss"> * OASIS-DSS (Digital Signature Services)</a> specification. * * @param uri the reference URI (may be <code>null</code>) * @param dm the digest method * @param transforms a list of {@link Transform}s. The list is defensively * copied to protect against subsequent modification. May be * <code>null</code> or empty. * @param type the reference type, as a URI (may be <code>null</code>) * @param id the reference ID (may be <code>null</code>) * @param digestValue the digest value. The array is cloned to protect * against subsequent modification. * @return a <code>Reference</code> * @throws ClassCastException if any of the <code>transforms</code> are * not of type <code>Transform</code> * @throws IllegalArgumentException if <code>uri</code> is not RFC 2396 * compliant * @throws NullPointerException if <code>dm</code> or * <code>digestValue</code> is <code>null</code> */ public abstract Reference newReference(String uri, DigestMethod dm, java.util.List<Object> transforms, String type, String id, byte[] digestValue); /** * Creates a <code>Reference</code> with the specified parameters. * * <p>This method is useful when a list of transforms have already been * applied to the <code>Reference</code>. See for example, * the * <a href="http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=dss"> * OASIS-DSS (Digital Signature Services)</a> specification. * * <p>When an <code>XMLSignature</code> containing this reference is * generated, the specified <code>transforms</code> (if non-null) are * applied to the specified <code>result</code>. The * <code>Transforms</code> element of the resulting <code>Reference</code> * element is set to the concatenation of the * <code>appliedTransforms</code> and <code>transforms</code>. * * @param uri the reference URI (may be <code>null</code>) * @param dm the digest method * @param appliedTransforms a list of {@link Transform}s that have * already been applied. The list is defensively * copied to protect against subsequent modification. The list must * contain at least one entry. * @param result the result of processing the sequence of * <code>appliedTransforms</code> * @param transforms a list of {@link Transform}s that are to be applied * when generating the signature. The list is defensively copied to * protect against subsequent modification. May be <code>null</code> * or empty. * @param type the reference type, as a URI (may be <code>null</code>) * @param id the reference ID (may be <code>null</code>) * @return a <code>Reference</code> * @throws ClassCastException if any of the transforms (in either list) * are not of type <code>Transform</code> * @throws IllegalArgumentException if <code>uri</code> is not RFC 2396 * compliant or <code>appliedTransforms</code> is empty * @throws NullPointerException if <code>dm</code>, * <code>appliedTransforms</code> or <code>result</code> is * <code>null</code> */ public abstract Reference newReference(String uri, DigestMethod dm, java.util.List<Object> appliedTransforms, Data result, java.util.List<Object> transforms, String type, String id); /** * Creates a <code>SignedInfo</code> with the specified canonicalization * and signature methods, and list of one or more references. * * @param cm the canonicalization method * @param sm the signature method * @param references a list of one or more {@link Reference}s. The list is * defensively copied to protect against subsequent modification. * @return a <code>SignedInfo</code> * @throws ClassCastException if any of the references are not of * type <code>Reference</code> * @throws IllegalArgumentException if <code>references</code> is empty * @throws NullPointerException if any of the parameters * are <code>null</code> */ public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, java.util.List<Object> references); /** * Creates a <code>SignedInfo</code> with the specified parameters. * * @param cm the canonicalization method * @param sm the signature method * @param references a list of one or more {@link Reference}s. The list is * defensively copied to protect against subsequent modification. * @param id the id (may be <code>null</code>) * @return a <code>SignedInfo</code> * @throws ClassCastException if any of the references are not of * type <code>Reference</code> * @throws IllegalArgumentException if <code>references</code> is empty * @throws NullPointerException if <code>cm</code>, <code>sm</code>, or * <code>references</code> are <code>null</code> */ public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, java.util.List<Object> references, String id); // Object factory methods /** * Creates an <code>XMLObject</code> from the specified parameters. * * @param content a list of {@link XMLStructure}s. The list * is defensively copied to protect against subsequent modification. * May be <code>null</code> or empty. * @param id the Id (may be <code>null</code>) * @param mimeType the mime type (may be <code>null</code>) * @param encoding the encoding (may be <code>null</code>) * @return an <code>XMLObject</code> * @throws ClassCastException if <code>content</code> contains any * entries that are not of type {@link XMLStructure} */ public abstract XMLObject newXMLObject(java.util.List<Object> content, String id, String mimeType, String encoding); /** * Creates a <code>Manifest</code> containing the specified * list of {@link Reference}s. * * @param references a list of one or more <code>Reference</code>s. The list * is defensively copied to protect against subsequent modification. * @return a <code>Manifest</code> * @throws NullPointerException if <code>references</code> is * <code>null</code> * @throws IllegalArgumentException if <code>references</code> is empty * @throws ClassCastException if <code>references</code> contains any * entries that are not of type {@link Reference} */ public abstract Manifest newManifest(java.util.List<Object> references); /** * Creates a <code>Manifest</code> containing the specified * list of {@link Reference}s and optional id. * * @param references a list of one or more <code>Reference</code>s. The list * is defensively copied to protect against subsequent modification. * @param id the id (may be <code>null</code>) * @return a <code>Manifest</code> * @throws NullPointerException if <code>references</code> is * <code>null</code> * @throws IllegalArgumentException if <code>references</code> is empty * @throws ClassCastException if <code>references</code> contains any * entries that are not of type {@link Reference} */ public abstract Manifest newManifest(java.util.List<Object> references, String id); /** * Creates a <code>SignatureProperty</code> containing the specified * list of {@link XMLStructure}s, target URI and optional id. * * @param content a list of one or more <code>XMLStructure</code>s. The list * is defensively copied to protect against subsequent modification. * @param target the target URI of the Signature that this property applies * to * @param id the id (may be <code>null</code>) * @return a <code>SignatureProperty</code> * @throws NullPointerException if <code>content</code> or * <code>target</code> is <code>null</code> * @throws IllegalArgumentException if <code>content</code> is empty * @throws ClassCastException if <code>content</code> contains any * entries that are not of type {@link XMLStructure} */ public abstract SignatureProperty newSignatureProperty (java.util.List<Object> content, String target, String id); /** * Creates a <code>SignatureProperties</code> containing the specified * list of {@link SignatureProperty}s and optional id. * * @param properties a list of one or more <code>SignatureProperty</code>s. * The list is defensively copied to protect against subsequent * modification. * @param id the id (may be <code>null</code>) * @return a <code>SignatureProperties</code> * @throws NullPointerException if <code>properties</code> * is <code>null</code> * @throws IllegalArgumentException if <code>properties</code> is empty * @throws ClassCastException if <code>properties</code> contains any * entries that are not of type {@link SignatureProperty} */ public abstract SignatureProperties newSignatureProperties (java.util.List<Object> properties, String id); // Algorithm factory methods /** * Creates a <code>DigestMethod</code> for the specified algorithm URI * and parameters. * * @param algorithm the URI identifying the digest algorithm * @param params algorithm-specific digest parameters (may be * <code>null</code>) * @return the <code>DigestMethod</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract DigestMethod newDigestMethod(String algorithm, javax.xml.crypto.dsig.spec.DigestMethodParameterSpec paramsJ) ;//throws NoSuchAlgorithmException, //InvalidAlgorithmParameterException; /** * Creates a <code>SignatureMethod</code> for the specified algorithm URI * and parameters. * * @param algorithm the URI identifying the signature algorithm * @param params algorithm-specific signature parameters (may be * <code>null</code>) * @return the <code>SignatureMethod</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract SignatureMethod newSignatureMethod(String algorithm, javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec paramsJ) ;//throws NoSuchAlgorithmException, //InvalidAlgorithmParameterException; /** * Creates a <code>Transform</code> for the specified algorithm URI * and parameters. * * @param algorithm the URI identifying the transform algorithm * @param params algorithm-specific transform parameters (may be * <code>null</code>) * @return the <code>Transform</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract Transform newTransform(String algorithm, TransformParameterSpec paramsJ) ;//throws NoSuchAlgorithmException, //InvalidAlgorithmParameterException; /** * Creates a <code>Transform</code> for the specified algorithm URI * and parameters. The parameters are specified as a mechanism-specific * <code>XMLStructure</code> (ex: {@link DOMStructure}). This method is * useful when the parameters are in XML form or there is no standard * class for specifying the parameters. * * @param algorithm the URI identifying the transform algorithm * @param params a mechanism-specific XML structure from which to * unmarshal the parameters from (may be <code>null</code> if * not required or optional) * @return the <code>Transform</code> * @throws ClassCastException if the type of <code>params</code> is * inappropriate for this <code>XMLSignatureFactory</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract Transform newTransform(String algorithm, XMLStructure paramsJ) ;//throws NoSuchAlgorithmException, //InvalidAlgorithmParameterException; /** * Creates a <code>CanonicalizationMethod</code> for the specified * algorithm URI and parameters. * * @param algorithm the URI identifying the canonicalization algorithm * @param params algorithm-specific canonicalization parameters (may be * <code>null</code>) * @return the <code>CanonicalizationMethod</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract CanonicalizationMethod newCanonicalizationMethod( String algorithm, C14NMethodParameterSpec paramsJ);// //throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; /** * Creates a <code>CanonicalizationMethod</code> for the specified * algorithm URI and parameters. The parameters are specified as a * mechanism-specific <code>XMLStructure</code> (ex: {@link DOMStructure}). * This method is useful when the parameters are in XML form or there is * no standard class for specifying the parameters. * * @param algorithm the URI identifying the canonicalization algorithm * @param params a mechanism-specific XML structure from which to * unmarshal the parameters from (may be <code>null</code> if * not required or optional) * @return the <code>CanonicalizationMethod</code> * @throws ClassCastException if the type of <code>params</code> is * inappropriate for this <code>XMLSignatureFactory</code> * @throws InvalidAlgorithmParameterException if the specified parameters * are inappropriate for the requested algorithm * @throws NoSuchAlgorithmException if an implementation of the * specified algorithm cannot be found * @throws NullPointerException if <code>algorithm</code> is * <code>null</code> */ public abstract CanonicalizationMethod newCanonicalizationMethod( String algorithm, XMLStructure paramsJ); //throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; /** * Returns a <code>KeyInfoFactory</code> that creates <code>KeyInfo</code> * objects. The returned <code>KeyInfoFactory</code> has the same * mechanism type and provider as this <code>XMLSignatureFactory</code>. * * @return a <code>KeyInfoFactory</code> * @throws NoSuchMechanismException if a <code>KeyFactory</code> * implementation with the same mechanism type and provider * is not available */ public javax.xml.crypto.dsig.keyinfo.KeyInfoFactory getKeyInfoFactory() { return javax.xml.crypto.dsig.keyinfo.KeyInfoFactory.getInstance(getMechanismType(), getProvider()); } /** * Unmarshals a new <code>XMLSignature</code> instance from a * mechanism-specific <code>XMLValidateContext</code> instance. * * @param context a mechanism-specific context from which to unmarshal the * signature from * @return the <code>XMLSignature</code> * @throws NullPointerException if <code>context</code> is * <code>null</code> * @throws ClassCastException if the type of <code>context</code> is * inappropriate for this factory * @throws MarshalException if an unrecoverable exception occurs * during unmarshalling */ public abstract XMLSignature unmarshalXMLSignature (XMLValidateContext context) ;//throws MarshalException; /** * Unmarshals a new <code>XMLSignature</code> instance from a * mechanism-specific <code>XMLStructure</code> instance. * This method is useful if you only want to unmarshal (and not * validate) an <code>XMLSignature</code>. * * @param xmlStructure a mechanism-specific XML structure from which to * unmarshal the signature from * @return the <code>XMLSignature</code> * @throws NullPointerException if <code>xmlStructure</code> is * <code>null</code> * @throws ClassCastException if the type of <code>xmlStructure</code> is * inappropriate for this factory * @throws MarshalException if an unrecoverable exception occurs * during unmarshalling */ public abstract XMLSignature unmarshalXMLSignature (XMLStructure xmlStructure) ;//throws MarshalException; /** * Indicates whether a specified feature is supported. * * @param feature the feature name (as an absolute URI) * @return <code>true</code> if the specified feature is supported, * <code>false</code> otherwise * @throws NullPointerException if <code>feature</code> is <code>null</code> */ public abstract bool isFeatureSupported(String feature); /** * Returns a reference to the <code>URIDereferencer</code> that is used by * default to dereference URIs in {@link Reference} objects. * * @return a reference to the default <code>URIDereferencer</code> (never * <code>null</code>) */ public abstract URIDereferencer getURIDereferencer(); } }
using Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; namespace ShapingAPI.Entities { public partial class ChinookContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder options) { //options.UseSqlServer(@"Server=(localdb)\v11.0;Database=Chinook;Trusted_Connection=True;"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Album>(entity => { entity.HasIndex(e => e.ArtistId).HasName("IFK_AlbumArtistId"); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(160); entity.HasOne(d => d.Artist).WithMany(p => p.Album).HasForeignKey(d => d.ArtistId).OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<Artist>(entity => { entity.Property(e => e.Name).HasMaxLength(120); }); modelBuilder.Entity<Customer>(entity => { entity.HasIndex(e => e.SupportRepId).HasName("IFK_CustomerSupportRepId"); entity.Property(e => e.Address).HasMaxLength(70); entity.Property(e => e.City).HasMaxLength(40); entity.Property(e => e.Company).HasMaxLength(80); entity.Property(e => e.Country).HasMaxLength(40); entity.Property(e => e.Email) .IsRequired() .HasMaxLength(60); entity.Property(e => e.Fax).HasMaxLength(24); entity.Property(e => e.FirstName) .IsRequired() .HasMaxLength(40); entity.Property(e => e.LastName) .IsRequired() .HasMaxLength(20); entity.Property(e => e.Phone).HasMaxLength(24); entity.Property(e => e.PostalCode).HasMaxLength(10); entity.Property(e => e.State).HasMaxLength(40); entity.HasOne(d => d.SupportRep).WithMany(p => p.Customer).HasForeignKey(d => d.SupportRepId); }); modelBuilder.Entity<Employee>(entity => { entity.HasIndex(e => e.ReportsTo).HasName("IFK_EmployeeReportsTo"); entity.Property(e => e.Address).HasMaxLength(70); entity.Property(e => e.BirthDate).HasColumnType("datetime"); entity.Property(e => e.City).HasMaxLength(40); entity.Property(e => e.Country).HasMaxLength(40); entity.Property(e => e.Email).HasMaxLength(60); entity.Property(e => e.Fax).HasMaxLength(24); entity.Property(e => e.FirstName) .IsRequired() .HasMaxLength(20); entity.Property(e => e.HireDate).HasColumnType("datetime"); entity.Property(e => e.LastName) .IsRequired() .HasMaxLength(20); entity.Property(e => e.Phone).HasMaxLength(24); entity.Property(e => e.PostalCode).HasMaxLength(10); entity.Property(e => e.State).HasMaxLength(40); entity.Property(e => e.Title).HasMaxLength(30); entity.HasOne(d => d.ReportsToNavigation).WithMany(p => p.InverseReportsToNavigation).HasForeignKey(d => d.ReportsTo); }); modelBuilder.Entity<Genre>(entity => { entity.Property(e => e.Name).HasMaxLength(120); }); modelBuilder.Entity<Invoice>(entity => { entity.HasIndex(e => e.CustomerId).HasName("IFK_InvoiceCustomerId"); entity.Property(e => e.BillingAddress).HasMaxLength(70); entity.Property(e => e.BillingCity).HasMaxLength(40); entity.Property(e => e.BillingCountry).HasMaxLength(40); entity.Property(e => e.BillingPostalCode).HasMaxLength(10); entity.Property(e => e.BillingState).HasMaxLength(40); entity.Property(e => e.InvoiceDate).HasColumnType("datetime"); entity.Property(e => e.Total).HasColumnType("numeric"); entity.HasOne(d => d.Customer).WithMany(p => p.Invoice).HasForeignKey(d => d.CustomerId).OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<InvoiceLine>(entity => { entity.HasIndex(e => e.InvoiceId).HasName("IFK_InvoiceLineInvoiceId"); entity.HasIndex(e => e.TrackId).HasName("IFK_InvoiceLineTrackId"); entity.Property(e => e.UnitPrice).HasColumnType("numeric"); entity.HasOne(d => d.Invoice).WithMany(p => p.InvoiceLine).HasForeignKey(d => d.InvoiceId).OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.Track).WithMany(p => p.InvoiceLine).HasForeignKey(d => d.TrackId).OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<MediaType>(entity => { entity.Property(e => e.Name).HasMaxLength(120); }); modelBuilder.Entity<Playlist>(entity => { entity.Property(e => e.Name).HasMaxLength(120); }); modelBuilder.Entity<PlaylistTrack>(entity => { entity.HasKey(e => new { e.PlaylistId, e.TrackId }); entity.HasIndex(e => e.TrackId).HasName("IFK_PlaylistTrackTrackId"); entity.HasOne(d => d.Playlist).WithMany(p => p.PlaylistTrack).HasForeignKey(d => d.PlaylistId).OnDelete(DeleteBehavior.Restrict); entity.HasOne(d => d.Track).WithMany(p => p.PlaylistTrack).HasForeignKey(d => d.TrackId).OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<Track>(entity => { entity.HasIndex(e => e.AlbumId).HasName("IFK_TrackAlbumId"); entity.HasIndex(e => e.GenreId).HasName("IFK_TrackGenreId"); entity.HasIndex(e => e.MediaTypeId).HasName("IFK_TrackMediaTypeId"); entity.Property(e => e.Composer).HasMaxLength(220); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(200); entity.Property(e => e.UnitPrice).HasColumnType("numeric"); entity.HasOne(d => d.Album).WithMany(p => p.Track).HasForeignKey(d => d.AlbumId); entity.HasOne(d => d.Genre).WithMany(p => p.Track).HasForeignKey(d => d.GenreId); entity.HasOne(d => d.MediaType).WithMany(p => p.Track).HasForeignKey(d => d.MediaTypeId).OnDelete(DeleteBehavior.Restrict); }); modelBuilder.Entity<sysdiagrams>(entity => { entity.HasKey(e => e.diagram_id); entity.Property(e => e.definition).HasColumnType("varbinary"); }); } public virtual DbSet<Album> Album { get; set; } public virtual DbSet<Artist> Artist { get; set; } public virtual DbSet<Customer> Customer { get; set; } public virtual DbSet<Employee> Employee { get; set; } public virtual DbSet<Genre> Genre { get; set; } public virtual DbSet<Invoice> Invoice { get; set; } public virtual DbSet<InvoiceLine> InvoiceLine { get; set; } public virtual DbSet<MediaType> MediaType { get; set; } public virtual DbSet<Playlist> Playlist { get; set; } public virtual DbSet<PlaylistTrack> PlaylistTrack { get; set; } public virtual DbSet<Track> Track { get; set; } public virtual DbSet<sysdiagrams> sysdiagrams { get; set; } } }
//Sony Computer Entertainment Confidential using System; using System.Collections.Generic; using System.IO; using Sce.Atf.Dom; namespace Sce.Atf.Obj { /// <summary> /// Object file</summary> public class ObjFile { /// <summary> /// Read object file</summary> /// <param name="strm">Stream to read data into</param> /// <param name="resolvedUri">URI representing object file</param> public void Read(Stream strm, Uri resolvedUri) { m_resolvedUri = resolvedUri; // Create an instance of StreamReader to read from a file Parse(new StreamReader(strm)); } /// <summary> /// Populates DomNode with data from stream data</summary> /// <param name="stream">Stream to read data into</param> /// <param name="node">Node to populate</param> /// <param name="resolvedUri">URI representing object file</param> public static void PopulateDomNode(Stream stream, ref DomNode node, Uri resolvedUri) { // Parse .obj file var obj = new ObjFile(); obj.Read(stream, resolvedUri); if (node == null) node = new DomNode(Schema.nodeType.Type); // Populate mesh var mesh = new DomNode(Schema.meshType.Type); mesh.SetAttribute(Schema.meshType.nameAttribute, Path.GetFileName(resolvedUri.LocalPath)); var vertexArray = new DomNode(Schema.meshType_vertexArray.Type); // Populate primitive data foreach (Group group in obj.m_groups.Values) foreach (FaceSet face in group.FaceSets.Values) { var primitive = new DomNode(Schema.vertexArray_primitives.Type); primitive.SetAttribute(Schema.vertexArray_primitives.indicesAttribute, face.Indices.ToArray()); primitive.SetAttribute(Schema.vertexArray_primitives.sizesAttribute, face.Sizes.ToArray()); primitive.SetAttribute(Schema.vertexArray_primitives.typeAttribute, "POLYGONS"); // Populate shader MaterialDef material; obj.m_mtl.Materials.TryGetValue(face.MaterialName, out material); if (material != null) { string texture = null; if (material.TextureName != null) texture = new Uri(resolvedUri, material.TextureName).AbsolutePath; var shader = new DomNode(Schema.shaderType.Type); shader.SetAttribute(Schema.shaderType.nameAttribute, material.Name); shader.SetAttribute(Schema.shaderType.ambientAttribute, material.Ambient); shader.SetAttribute(Schema.shaderType.diffuseAttribute, material.Diffuse); shader.SetAttribute(Schema.shaderType.shininessAttribute, material.Shininess); shader.SetAttribute(Schema.shaderType.specularAttribute, material.Specular); shader.SetAttribute(Schema.shaderType.textureAttribute, texture); primitive.SetChild(Schema.vertexArray_primitives.shaderChild, shader); } // Note: Bindings must be in the order: normal, map1, position DomNode binding; if (face.HasNormals) { binding = new DomNode(Schema.primitives_binding.Type); binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "normal"); primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding); } if (face.HasTexCoords) { binding = new DomNode(Schema.primitives_binding.Type); binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "map1"); primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding); } binding = new DomNode(Schema.primitives_binding.Type); binding.SetAttribute(Schema.primitives_binding.sourceAttribute, "position"); primitive.GetChildList(Schema.vertexArray_primitives.bindingChild).Add(binding); vertexArray.GetChildList(Schema.meshType_vertexArray.primitivesChild).Add(primitive); } // Populate array data DomNode array; if (obj.m_normals.Count > 0) { array = new DomNode(Schema.vertexArray_array.Type); array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_normals.ToArray()); array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_normals.Count / 3); array.SetAttribute(Schema.vertexArray_array.nameAttribute, "normal"); array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3); vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array); } if (obj.m_texcoords.Count > 0) { array = new DomNode(Schema.vertexArray_array.Type); array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_texcoords.ToArray()); array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_texcoords.Count / 2); array.SetAttribute(Schema.vertexArray_array.nameAttribute, "map1"); array.SetAttribute(Schema.vertexArray_array.strideAttribute, 2); vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array); } array = new DomNode(Schema.vertexArray_array.Type); array.SetAttribute(Schema.vertexArray_array.Attribute, obj.m_positions.ToArray()); array.SetAttribute(Schema.vertexArray_array.countAttribute, obj.m_positions.Count / 3); array.SetAttribute(Schema.vertexArray_array.nameAttribute, "position"); array.SetAttribute(Schema.vertexArray_array.strideAttribute, 3); vertexArray.GetChildList(Schema.meshType_vertexArray.arrayChild).Add(array); // Set mesh elements mesh.SetChild(Schema.meshType.vertexArrayChild, vertexArray); node.SetChild(Schema.nodeType.meshChild, mesh); } private void Parse(TextReader sr) { string buf; // Read lines from the file until EOF while ((buf = sr.ReadLine()) != null) { buf = buf.Trim(); if (string.IsNullOrEmpty(buf)) continue; if (buf[0] == '#') continue; string[] split = buf.Split(s_stringDelimiters, StringSplitOptions.RemoveEmptyEntries); switch (buf[0]) { case 'v': // vertex switch (buf[1]) { case ' ': case '\t': if (split.Length != 4) // v + 3 floats throw new ApplicationException("Parse: Vertex split.Length is invalid"); m_positions.Add(float.Parse(split[1])); m_positions.Add(float.Parse(split[2])); m_positions.Add(float.Parse(split[3])); break; case 'n': if (split.Length != 4) // vn + 3 floats throw new ApplicationException("Parse: Normal split.Length is invalid"); m_normals.Add(float.Parse(split[1])); m_normals.Add(float.Parse(split[2])); m_normals.Add(float.Parse(split[3])); break; case 't': if (split.Length != 3) // vt + 2 floats throw new ApplicationException("Parse: TexCoord split.Length is invalid"); m_texcoords.Add(float.Parse(split[1])); m_texcoords.Add(float.Parse(split[2])); break; default: break; } break; case 'f': // face if (split.Length < 4) // f v/vt/vn v/vt/vn v/vt/vn ... throw new ApplicationException("Parse: Face split.Length is invalid"); m_currentFaceSet.Sizes.Add(split.Length - 1); for (int vi = 1; vi < split.Length; vi++) { string[] ptn = split[vi].Split('/'); if (ptn.Length == 3) // v/vt/vn or v//vn { m_currentFaceSet.Indices.Add(int.Parse(ptn[2]) - 1); m_currentFaceSet.HasNormals = true; if (!string.IsNullOrEmpty(ptn[1])) { m_currentFaceSet.Indices.Add(int.Parse(ptn[1]) - 1); m_currentFaceSet.HasTexCoords = true; } } else if (ptn.Length == 2) // v/vt/ { m_currentFaceSet.Indices.Add(int.Parse(ptn[1]) - 1); m_currentFaceSet.HasTexCoords = true; } m_currentFaceSet.Indices.Add(int.Parse(ptn[0]) - 1); // v or v// or v/vt/vn } break; case 'm': // material if (split.Length == 2) { var uri = new Uri(m_resolvedUri, split[1]); string fullPath = Uri.UnescapeDataString(uri.AbsolutePath); m_mtl = new MtlFile { Name = Path.GetFileName(fullPath) }; m_mtl.Read(fullPath); } break; case 'g': // group case 'o': // object if (split.Length >= 2) // g + groupName + ... { string curMatName = m_currentFaceSet.MaterialName; // Find group, otherwise create new group if (!m_groups.TryGetValue(split[1], out m_currentGroup)) { m_currentGroup = new Group { Name = split[1] }; m_groups.Add(m_currentGroup.Name, m_currentGroup); m_currentFaceSet = new FaceSet(curMatName); m_currentGroup.FaceSets.Add(curMatName, m_currentFaceSet); } // Group exists else { // Find faceset with current material, otherwise create new faceset with current material if (!m_currentGroup.FaceSets.TryGetValue(curMatName, out m_currentFaceSet)) { m_currentFaceSet = new FaceSet(curMatName); m_currentGroup.FaceSets.Add(curMatName, m_currentFaceSet); } } } break; case 'u': if (split.Length != 2) // usemtl + mat name throw new ApplicationException("Parse: Usemtl split.Length is invalid"); string matName = split[1]; // Find material by name if (m_mtl.Materials.ContainsKey(matName)) { // Find faceset with current material, otherwise create new faceset with current material if (!m_currentGroup.FaceSets.TryGetValue(matName, out m_currentFaceSet)) { m_currentFaceSet = new FaceSet(matName); m_currentGroup.FaceSets.Add(matName, m_currentFaceSet); } } else Outputs.WriteLine(OutputMessageType.Warning, "Material not found: {0}", matName); break; default: break; } } if (m_groups.Count == 0) m_groups.Add(m_currentGroup.Name, m_currentGroup); if (m_currentGroup.FaceSets.Count == 0) m_currentGroup.FaceSets[m_currentFaceSet.MaterialName] = m_currentFaceSet; // Remove empty FaceSets and mark empty Groups var delGrpList = new List<string>(); foreach (Group grp in m_groups.Values) { var delList = new List<string>(); foreach (FaceSet fs in grp.FaceSets.Values) { if (fs.Indices.Count == 0) delList.Add(fs.MaterialName); } foreach (string fsName in delList) grp.FaceSets.Remove(fsName); if (grp.FaceSets.Count == 0) delGrpList.Add(grp.Name); } // Remove empty groups foreach (string grpn in delGrpList) m_groups.Remove(grpn); } private MtlFile m_mtl = new MtlFile(); private readonly Dictionary<string, Group> m_groups = new Dictionary<string, Group>(); private readonly List<float> m_positions = new List<float>(); private readonly List<float> m_normals = new List<float>(); private readonly List<float> m_texcoords = new List<float>(); private Group m_currentGroup = new Group(); private FaceSet m_currentFaceSet = new FaceSet(); private Uri m_resolvedUri; private static readonly char[] s_stringDelimiters = new[] { ' ', '\t' }; } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.PythonTools; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Project.ImportWizard; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; using TestUtilities.Python; namespace PythonToolsTests { [TestClass] public class ImportWizardTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); } private static string CreateRequestedProject(dynamic settings) { return Task.Run(async () => { return await await WpfProxy.FromObject((object)settings).InvokeAsync( async () => await (Task<string>)settings.CreateRequestedProjectAsync() ); }) .GetAwaiter() .GetResult(); } [TestMethod, Priority(UnitTestPriority.P0)] public void ImportWizardSimple() { using (var wpf = new WpfProxy()) { var root = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld")); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath1"), Path.Combine(root, "SearchPath1")); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath2"), Path.Combine(root, "SearchPath2")); var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld"); settings.Filters = "*.py;*.pyproj"; settings.SearchPaths = PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath1") + Environment.NewLine + PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath2"); settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj"); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual("4.0", proj.Descendant("Project").Attribute("ToolsVersion").Value); Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value); Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "Program.py"); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Content")).Select(x => x.Attribute("Include").Value), "HelloWorld.pyproj"); } } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardFiltered() { using (var wpf = new WpfProxy()) { var root = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld")); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath1"), Path.Combine(root, "SearchPath1")); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\SearchPath2"), Path.Combine(root, "SearchPath2")); var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld"); settings.Filters = "*.py"; settings.SearchPaths = PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath1") + Environment.NewLine + PathUtils.GetAbsoluteDirectoryPath(root, "SearchPath2"); settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj"); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual("..\\..\\HelloWorld\\", proj.Descendant("ProjectHome").Value); Assert.AreEqual("..\\SearchPath1\\;..\\SearchPath2\\", proj.Descendant("SearchPath").Value); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "Program.py"); Assert.AreEqual(0, proj.Descendants(proj.GetName("Content")).Count()); } } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardFolders() { using (var wpf = new WpfProxy()) { var root = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld2"), Path.Combine(root, "HelloWorld2")); var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld2"); settings.Filters = "*"; settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj"); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual("..\\..\\HelloWorld2\\", proj.Descendant("ProjectHome").Value); Assert.AreEqual("", proj.Descendant("SearchPath").Value); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "Program.py", "TestFolder\\SubItem.py", "TestFolder2\\SubItem.py", "TestFolder3\\SubItem.py"); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value), "TestFolder", "TestFolder2", "TestFolder3"); } } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardInterpreter() { using (var wpf = new WpfProxy()) { var root = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld")); var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld"); settings.Filters = "*.py;*.pyproj"; settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj"); var interpreter = new PythonInterpreterView("Test", "Test|Blah", null); settings.Dispatcher.Invoke((Action)(() => settings.AvailableInterpreters.Add(interpreter))); //settings.AddAvailableInterpreter(interpreter); settings.SelectedInterpreter = interpreter; string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual(interpreter.Id, proj.Descendant("InterpreterId").Value); var interp = proj.Descendant("InterpreterReference"); Assert.AreEqual(string.Format("{0}", interpreter.Id), interp.Attribute("Include").Value); } } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardStartupFile() { using (var wpf = new WpfProxy()) { var root = TestData.GetTempPath(); FileUtils.CopyDirectory(TestData.GetPath(@"TestData\HelloWorld"), Path.Combine(root, "HelloWorld")); var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = PathUtils.GetAbsoluteDirectoryPath(root, "HelloWorld"); settings.Filters = "*.py;*.pyproj"; settings.StartupFile = "Program.py"; settings.ProjectPath = PathUtils.GetAbsoluteFilePath(root, @"TestDestination\Subdirectory\ProjectName.pyproj"); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value); } } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardSemicolons() { // https://pytools.codeplex.com/workitem/2022 using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(null, null)); var sourcePath = TestData.GetTempPath(); // Create a fake set of files to import Directory.CreateDirectory(Path.Combine(sourcePath, "ABC")); File.WriteAllText(Path.Combine(sourcePath, "ABC", "a;b;c.py"), ""); Directory.CreateDirectory(Path.Combine(sourcePath, "A;B;C")); File.WriteAllText(Path.Combine(sourcePath, "A;B;C", "abc.py"), ""); settings.SourcePath = sourcePath; string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "ABC\\a%3bb%3bc.py", "A%3bB%3bC\\abc.py" ); AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value), "ABC", "A%3bB%3bC" ); } } private void ImportWizardVirtualEnvWorker( PythonVersion python, string venvModuleName, string expectedFile, bool brokenBaseInterpreter ) { var mockService = new MockInterpreterOptionsService(); mockService.AddProvider(new MockPythonInterpreterFactoryProvider("Test Provider", new MockPythonInterpreterFactory(python.Configuration) )); using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(null, mockService)); var sourcePath = TestData.GetTempPath(); // Create a fake set of files to import File.WriteAllText(Path.Combine(sourcePath, "main.py"), ""); Directory.CreateDirectory(Path.Combine(sourcePath, "A")); File.WriteAllText(Path.Combine(sourcePath, "A", "__init__.py"), ""); // Create a real virtualenv environment to import using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", venvModuleName, Path.Combine(sourcePath, "env"))) { Console.WriteLine(p.Arguments); p.Wait(); Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines))); Assert.AreEqual(0, p.ExitCode); } if (brokenBaseInterpreter) { var cfgPath = Path.Combine(sourcePath, "env", "Lib", "orig-prefix.txt"); if (File.Exists(cfgPath)) { File.WriteAllText(cfgPath, string.Format("C:\\{0:N}", Guid.NewGuid())); } else if (File.Exists((cfgPath = Path.Combine(sourcePath, "env", "pyvenv.cfg")))) { File.WriteAllLines(cfgPath, File.ReadAllLines(cfgPath) .Select(line => { if (line.StartsWith("home = ")) { return string.Format("home = C:\\{0:N}", Guid.NewGuid()); } return line; }) ); } } Console.WriteLine("All files:"); foreach (var f in Directory.EnumerateFiles(sourcePath, "*", SearchOption.AllDirectories)) { Console.WriteLine(PathUtils.GetRelativeFilePath(sourcePath, f)); } Assert.IsTrue( File.Exists(Path.Combine(sourcePath, "env", expectedFile)), "Virtualenv was not created correctly" ); settings.SourcePath = sourcePath; string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); var proj = XDocument.Load(path); // Does not include any .py files from the virtualenv AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Compile")).Select(x => x.Attribute("Include").Value), "main.py", "A\\__init__.py" ); // Does not contain 'env' AssertUtil.ContainsExactly(proj.Descendants(proj.GetName("Folder")).Select(x => x.Attribute("Include").Value), "A" ); var env = proj.Descendants(proj.GetName("Interpreter")).SingleOrDefault(); if (brokenBaseInterpreter) { Assert.IsNull(env); } else { Assert.AreEqual("env\\", env.Attribute("Include").Value); Assert.AreNotEqual("", env.Descendant("Id").Value); Assert.AreEqual(string.Format("env ({0})", python.Configuration.Description), env.Descendant("Description").Value); Assert.AreEqual("scripts\\python.exe", env.Descendant("InterpreterPath").Value, true); Assert.AreEqual("scripts\\pythonw.exe", env.Descendant("WindowsInterpreterPath").Value, true); Assert.AreEqual("PYTHONPATH", env.Descendant("PathEnvironmentVariable").Value, true); Assert.AreEqual(python.Configuration.Version.ToString(), env.Descendant("Version").Value, true); Assert.AreEqual(python.Configuration.Architecture.ToString("X"), env.Descendant("Architecture").Value, true); } } } [TestMethod, Priority(UnitTestPriority.P2)] public void ImportWizardVirtualEnv() { var python = PythonPaths.Versions.LastOrDefault(pv => pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "site-packages", "virtualenv.py")) && // CPython 3.3.4 does not work correctly with virtualenv, so // skip testing on 3.3 to avoid false failures pv.Version != PythonLanguageVersion.V33 ); ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", false); } [TestMethod, Priority(UnitTestPriority.P2)] public void ImportWizardVEnv() { var python = PythonPaths.Versions.LastOrDefault(pv => pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "venv", "__main__.py")) ); ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", false); } [TestMethod, Priority(UnitTestPriority.P2)] [TestCategory("10s")] public void ImportWizardBrokenVirtualEnv() { var python = PythonPaths.Versions.LastOrDefault(pv => pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "site-packages", "virtualenv.py")) && // CPython 3.3.4 does not work correctly with virtualenv, so // skip testing on 3.3 to avoid false failures pv.Version != PythonLanguageVersion.V33 ); ImportWizardVirtualEnvWorker(python, "virtualenv", "lib\\orig-prefix.txt", true); } [TestMethod, Priority(UnitTestPriority.P2)] [TestCategory("10s")] public void ImportWizardBrokenVEnv() { var python = PythonPaths.Versions.LastOrDefault(pv => pv.IsCPython && File.Exists(Path.Combine(pv.PrefixPath, "Lib", "venv", "__main__.py")) ); ImportWizardVirtualEnvWorker(python, "venv", "pyvenv.cfg", true); } private static void ImportWizardCustomizationsWorker(ProjectCustomization customization, Action<XDocument> verify) { using (var wpf = new WpfProxy()) { var settings = wpf.Create(() => new ImportSettings(null, null)); settings.SourcePath = TestData.GetPath("TestData\\HelloWorld\\"); settings.Filters = "*.py;*.pyproj"; settings.StartupFile = "Program.py"; settings.UseCustomization = true; settings.Customization = customization; settings.ProjectPath = Path.Combine(TestData.GetTempPath("ImportWizardCustomizations_" + customization.GetType().Name), "Project.pyproj"); Directory.CreateDirectory(Path.GetDirectoryName(settings.ProjectPath)); string path = CreateRequestedProject(settings); Assert.AreEqual(settings.ProjectPath, path); Console.WriteLine(File.ReadAllText(path)); var proj = XDocument.Load(path); verify(proj); } } [TestMethod, Priority(UnitTestPriority.P0)] public void ImportWizardCustomizations() { ImportWizardCustomizationsWorker(DefaultProjectCustomization.Instance, proj => { Assert.AreEqual("Program.py", proj.Descendant("StartupFile").Value); Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.targets")); Assert.AreEqual(0, proj.Descendants("UseCustomServer").Count()); }); ImportWizardCustomizationsWorker(BottleProjectCustomization.Instance, proj => { Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("e614c764-6d9e-4607-9337-b7073809a0bd", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets")); Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value); Assert.AreEqual("True", proj.Descendant("UseCustomServer").Value); }); ImportWizardCustomizationsWorker(DjangoProjectCustomization.Instance, proj => { Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("5F0BE9CA-D677-4A4D-8806-6076C0FAAD37", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Django.targets")); Assert.AreEqual("Django launcher", proj.Descendant("LaunchProvider").Value); Assert.AreEqual("True", proj.Descendant("UseCustomServer").Value); }); ImportWizardCustomizationsWorker(FlaskProjectCustomization.Instance, proj => { Assert.AreNotEqual(-1, proj.Descendant("ProjectTypeGuids").Value.IndexOf("789894c7-04a9-4a11-a6b5-3f4435165112", StringComparison.OrdinalIgnoreCase)); Assert.IsTrue(proj.Descendants(proj.GetName("Import")).Any(d => d.Attribute("Project").Value == @"$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Python Tools\Microsoft.PythonTools.Web.targets")); Assert.AreEqual("Web launcher", proj.Descendant("LaunchProvider").Value); Assert.AreEqual("True", proj.Descendant("UseCustomServer").Value); }); } static T Wait<T>(Task<T> task) { task.Wait(); return task.Result; } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardCandidateStartupFiles() { var sourcePath = TestData.GetTempPath(); // Create a fake set of files to import File.WriteAllText(Path.Combine(sourcePath, "a.py"), ""); File.WriteAllText(Path.Combine(sourcePath, "b.py"), ""); File.WriteAllText(Path.Combine(sourcePath, "c.py"), ""); File.WriteAllText(Path.Combine(sourcePath, "a.pyw"), ""); File.WriteAllText(Path.Combine(sourcePath, "b.pyw"), ""); File.WriteAllText(Path.Combine(sourcePath, "c.pyw"), ""); File.WriteAllText(Path.Combine(sourcePath, "a.txt"), ""); File.WriteAllText(Path.Combine(sourcePath, "b.txt"), ""); File.WriteAllText(Path.Combine(sourcePath, "c.txt"), ""); AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "")), "a.py", "b.py", "c.py" ); AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.pyw")), "a.py", "b.py", "c.py", "a.pyw", "b.pyw", "c.pyw" ); AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "b.pyw")), "a.py", "b.py", "c.py", "b.pyw" ); AssertUtil.ContainsExactly(Wait(ImportSettings.GetCandidateStartupFiles(sourcePath, "*.txt")), "a.py", "b.py", "c.py" ); } [TestMethod, Priority(UnitTestPriority.P1)] public void ImportWizardDefaultStartupFile() { var files = new[] { "a.py", "b.py", "c.py" }; var expectedDefault = files[0]; Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, null)); Assert.AreEqual(expectedDefault, ImportSettings.SelectDefaultStartupFile(files, "not in list")); Assert.AreEqual("b.py", ImportSettings.SelectDefaultStartupFile(files, "b.py")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Text; using Android.App; using Android.Bluetooth; using Android.Bluetooth.LE; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Javax.Security.Auth; using Plugin.CurrentActivity; using ReactiveBluetooth.Android.Common; using ReactiveBluetooth.Android.Extensions; using ReactiveBluetooth.Android.Peripheral.GattServer; using ReactiveBluetooth.Core; using ReactiveBluetooth.Core.Central; using ReactiveBluetooth.Core.Exceptions; using ReactiveBluetooth.Core.Peripheral; using ReactiveBluetooth.Core.Types; using ICharacteristic = ReactiveBluetooth.Core.Peripheral.ICharacteristic; using IDevice = ReactiveBluetooth.Core.Peripheral.IDevice; using IService = ReactiveBluetooth.Core.Peripheral.IService; namespace ReactiveBluetooth.Android.Peripheral { public class PeripheralManager : IPeripheralManager, IDisposable { private BroadcastListener _broadcastListener; private readonly BluetoothAdapter _bluetoothAdapter; private BluetoothLeAdvertiser _bluetoothLeAdvertiser; private readonly IServerCallback _serverCallback; private BluetoothGattServer _gattServer; private IObservable<bool> _startAdvertisingObservable; private ManagerState _lastState; public PeripheralManager() : this(null, null) { } public PeripheralManager(IServerCallback serverCallback = null, IBluetoothAbstractFactory bluetoothAbstractFactory = null) { _serverCallback = serverCallback ?? new ServerCallback(); Factory = bluetoothAbstractFactory ?? new AbstractFactory(_serverCallback); _bluetoothAdapter = BluetoothAdapter.DefaultAdapter; _broadcastListener = new BroadcastListener(); } public IBluetoothAbstractFactory Factory { get; } public IObservable<ManagerState> State() => _broadcastListener.StateUpdatedSubject.Select(x => { if (x != ManagerState.PoweredOn) return x; return _bluetoothAdapter?.BluetoothLeAdvertiser == null ? ManagerState.Unsupported : x; }).AsObservable(); public void Dispose() { _gattServer?.Close(); _broadcastListener?.Dispose(); _broadcastListener = null; } public IObservable<bool> Advertise(AdvertisingOptions advertisingOptions, IList<IService> services) { if (_startAdvertisingObservable != null) { return _startAdvertisingObservable; } var advertiseObservable = Observable.Create<bool>(observer => { var bluetoothManager = (BluetoothManager)Application.Context.GetSystemService(Context.BluetoothService); _gattServer = bluetoothManager.OpenGattServer(CrossCurrentActivity.Current.Activity, (BluetoothGattServerCallback)_serverCallback); if (_bluetoothAdapter.State.ToManagerState() == ManagerState.PoweredOff) { observer.OnError(new Exception("Device is off")); return Disposable.Empty; } _bluetoothLeAdvertiser = _bluetoothAdapter.BluetoothLeAdvertiser; if (_bluetoothLeAdvertiser == null) { observer.OnError(new AdvertisingNotSupportedException()); return Disposable.Empty; } if (advertisingOptions.LocalName != null) { _bluetoothAdapter.SetName(advertisingOptions.LocalName); } var settings = CreateAdvertiseSettings(advertisingOptions); var advertiseData = CreateAdvertiseData(advertisingOptions); var callback = new StartAdvertiseCallback(); var successDisposable = callback.AdvertiseSubject.Subscribe(advertiseSettings => { observer.OnNext(true); }, observer.OnError); if (services != null) { foreach (var service in services) { AddService(service); } } try { _bluetoothLeAdvertiser.StartAdvertising(settings, advertiseData, callback); } catch (Exception e) { observer.OnError(e); return Disposable.Empty; } return Disposable.Create(() => { successDisposable?.Dispose(); _gattServer?.Close(); _bluetoothLeAdvertiser?.StopAdvertising(callback); _startAdvertisingObservable = null; }); }) .Publish() .RefCount(); return advertiseObservable; } public AdvertiseData CreateAdvertiseData(AdvertisingOptions advertisingOptions) { var dataBuilder = new AdvertiseData.Builder(); if (advertisingOptions.ServiceUuids != null) { var parcelUuids = advertisingOptions.ServiceUuids.Select(x => ParcelUuid.FromString(x.ToString())); foreach (var parcelUuid in parcelUuids) { dataBuilder.AddServiceUuid(parcelUuid); } } dataBuilder.SetIncludeDeviceName(advertisingOptions.LocalName != null); return dataBuilder.Build(); } public AdvertiseSettings CreateAdvertiseSettings(AdvertisingOptions advertisingOptions) { AdvertiseSettings.Builder settingsBuilder = new AdvertiseSettings.Builder(); settingsBuilder.SetAdvertiseMode(advertisingOptions.AdvertiseMode.ToAdvertiseMode()); settingsBuilder.SetConnectable(true); settingsBuilder.SetTxPowerLevel(advertisingOptions.AdvertiseTx.ToAdvertiseTx()); var settings = settingsBuilder.Build(); return settings; } public IObservable<bool> AddService(IService service) { var androidService = ((Service) service); if (androidService.Characteristics != null) foreach (var characteristic in androidService.Characteristics) { var androidCharacteristic = (Characteristic) characteristic; androidCharacteristic.GattServer = _gattServer; } var nativeService = androidService.GattService; var result = _gattServer?.AddService(nativeService); return Observable.Return(result ?? false); } public void RemoveService(IService service) { var nativeService = ((Service) service).GattService; _gattServer?.RemoveService(nativeService); } public void RemoveAllServices() { _gattServer?.ClearServices(); } public bool SendResponse(IAttRequest request, int offset, byte[] value) { AttRequest attRequest = (AttRequest) request; return _gattServer != null && _gattServer.SendResponse(attRequest.BluetoothDevice, attRequest.RequestId, GattStatus.Success, offset, value); } public bool Notify(IDevice device, ICharacteristic characteristic, byte[] value) { Device androidDevice = (Device) device; Characteristic androidCharacteristic = (Characteristic) characteristic; bool indicate = androidCharacteristic.Properties.HasFlag(CharacteristicProperty.Indicate); if (!indicate) { if (!androidCharacteristic.Properties.HasFlag(CharacteristicProperty.Notify)) { throw new NotSupportedException("Characteristic does not support Notify or Indicate"); } } var result = _gattServer.NotifyCharacteristicChanged(androidDevice.NativeDevice, androidCharacteristic.NativeCharacteristic, indicate); return result; } } }
//Matt Schoen //5-29-2013 // // This software is the copyrighted material of its author, Matt Schoen, and his company Defective Studios. // It is available for sale on the Unity Asset store and is subject to their restrictions and limitations, as well as // the following: You shall not reproduce or re-distribute this software without the express written (e-mail is fine) // permission of the author. If permission is granted, the code (this file and related files) must bear this license // in its entirety. Anyone who purchases the script is welcome to modify and re-use the code at their personal risk // and under the condition that it not be included in any distribution builds. The software is provided as-is without // warranty and the author bears no responsibility for damages or losses caused by the software. // This Agreement becomes effective from the day you have installed, copied, accessed, downloaded and/or otherwise used // the software. using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; using FoldoutDraw = ObjectMerge.EmptyVoid; namespace UniMerge { public static class Util { public static float TAB_SIZE = 15; public static void Foldout(ref bool open, string title, FoldoutDraw draw) { Foldout(ref open, new GUIContent(title), draw, null); } public static void Foldout(ref bool open, GUIContent content, FoldoutDraw draw) { Foldout(ref open, content, draw, null); } public static void Foldout(ref bool open, string title, FoldoutDraw draw, FoldoutDraw moreLabel) { Foldout(ref open, new GUIContent(title), draw, moreLabel); } public static void Foldout(ref bool open, GUIContent content, FoldoutDraw draw, FoldoutDraw moreLabel) { GUILayout.BeginHorizontal(); open = EditorGUILayout.Foldout(open, content); if(moreLabel != null) moreLabel.Invoke(); GUILayout.EndHorizontal(); if(open) { Indent(draw); } } public static void Indent(FoldoutDraw draw) { Indent(TAB_SIZE, draw); } public static void Indent(float width, FoldoutDraw draw) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(GUILayout.Width(width)); GUILayout.Label(""); EditorGUILayout.EndVertical(); EditorGUILayout.BeginVertical(); draw.Invoke(); EditorGUILayout.EndVertical(); EditorGUILayout.EndHorizontal(); } public static void Center(FoldoutDraw element) { GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); element(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } //Not used but a nice little gem :) public static void ClearLog() { Assembly assembly = Assembly.GetAssembly(typeof(SceneView)); System.Type type = assembly.GetType("UnityEditorInternal.LogEntries"); MethodInfo method = type.GetMethod("Clear"); method.Invoke(new object(), null); } public static void PingButton(string content, Object obj) { if(GUILayout.Button(content)) EditorGUIUtility.PingObject(obj); } //Looks like Unity already has one of these... doesn't work the way I want though public static IEnumerable<bool> PropEqual(SerializedProperty mine, SerializedProperty theirs, GameObject mineParent, GameObject theirsParent) { if(ObjectMerge.refreshWatch.Elapsed.TotalSeconds > ObjectMerge.maxFrameTime) { ObjectMerge.refreshWatch.Reset(); yield return false; ObjectMerge.refreshWatch.Start(); } if(mine != null && theirs != null) { if(mine.propertyType == theirs.propertyType) { switch(mine.propertyType) { case SerializedPropertyType.AnimationCurve: if(mine.animationCurveValue.keys.Length == theirs.animationCurveValue.keys.Length) { for(int i = 0; i < mine.animationCurveValue.keys.Length; i++) { if(mine.animationCurveValue.keys[i].inTangent != theirs.animationCurveValue.keys[i].inTangent) { yield return false; yield break; } if(mine.animationCurveValue.keys[i].outTangent != theirs.animationCurveValue.keys[i].outTangent){ yield return false; yield break; } if(mine.animationCurveValue.keys[i].time != theirs.animationCurveValue.keys[i].time){ yield return false; yield break; } if(mine.animationCurveValue.keys[i].value != theirs.animationCurveValue.keys[i].value){ yield return false; yield break; } } } else { yield return false; yield break; } yield return true; yield break; case SerializedPropertyType.ArraySize: //Haven't handled this one... not sure it will come up //Debug.LogWarning("Got ArraySize type"); break; case SerializedPropertyType.Boolean: yield return mine.boolValue == theirs.boolValue; yield break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Bounds: yield return mine.boundsValue == theirs.boundsValue; yield break; #endif case SerializedPropertyType.Character: //TODO: Character comparison Debug.LogWarning("Got Character type. Need to add comparison function"); break; case SerializedPropertyType.Color: yield return mine.colorValue == theirs.colorValue;yield break; case SerializedPropertyType.Enum: yield return mine.enumValueIndex == theirs.enumValueIndex;yield break; case SerializedPropertyType.Float: yield return mine.floatValue == theirs.floatValue;yield break; case SerializedPropertyType.Generic: //Override equivalence for some types that will never be equal switch(mine.type) { case "NetworkViewID": yield return true; yield break; case "GUIStyle": //Having trouble with this one yield return true; yield break; } #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) bool equal; if(mine.isArray) { if(mine.arraySize == theirs.arraySize) { for(int i = 0; i < mine.arraySize; i++) { equal = false; foreach(bool e in PropEqual(mine.GetArrayElementAtIndex(i), theirs.GetArrayElementAtIndex(i), mineParent, theirsParent)) { yield return e; equal = e; } if(!equal) yield break; } yield return true; yield break; } yield return false; yield break; } equal = false; foreach(var e in CheckChildren(mine, theirs, mineParent, theirsParent)) equal = e; if (!equal) yield break; #endif break; /* #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Gradient: Debug.LogWarning("Got Gradient type"); break; #endif * */ case SerializedPropertyType.Integer: yield return mine.intValue == theirs.intValue; yield break; case SerializedPropertyType.LayerMask: yield return mine.intValue == theirs.intValue; yield break; case SerializedPropertyType.ObjectReference: if(mine.objectReferenceValue && theirs.objectReferenceValue) { System.Type t = mine.objectReferenceValue.GetType(); //If the property is a gameObject or component, compare equivalence by comparing names, and whether they're both children of the same parent (from different sides) if(t == typeof(GameObject)) { if(theirs.objectReferenceValue.GetType() != t) { Debug.LogWarning("EH? two properties of different types?"); yield return false; yield break; } if(ChildOfParent((GameObject)mine.objectReferenceValue, mineParent) && ChildOfParent((GameObject)theirs.objectReferenceValue, theirsParent)) { yield return mine.objectReferenceValue.name == theirs.objectReferenceValue.name; yield break; } } if(t.IsSubclassOf(typeof(Component))) { if(theirs.objectReferenceValue.GetType() != t) { Debug.LogWarning("EH? two properties of different types?"); yield return false; yield break; } if(ChildOfParent(((Component)mine.objectReferenceValue).gameObject, mineParent) && ChildOfParent(((Component)theirs.objectReferenceValue).gameObject, theirsParent)) { yield return mine.objectReferenceValue.name == theirs.objectReferenceValue.name; yield break; } } } yield return mine.objectReferenceValue == theirs.objectReferenceValue; yield break; case SerializedPropertyType.Rect: yield return mine.rectValue == theirs.rectValue; yield break; case SerializedPropertyType.String: yield return mine.stringValue == theirs.stringValue; yield break; case SerializedPropertyType.Vector2: yield return mine.vector2Value == theirs.vector2Value; yield break; case SerializedPropertyType.Vector3: yield return mine.vector3Value == theirs.vector3Value; yield break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case (SerializedPropertyType)16: yield return mine.quaternionValue.Equals(theirs.quaternionValue); yield break; #endif default: Debug.LogWarning("Unknown SeralizedPropertyType encountered: " + mine.propertyType); break; } } else Debug.LogWarning("Not same type?"); } yield return true; } private static IEnumerable<bool> CheckChildren(SerializedProperty mine, SerializedProperty theirs, GameObject mineParent, GameObject theirsParent) { bool enter = true; if(mine == null && theirs == null) yield break; if(mine == null || theirs == null) { yield return false; yield break; } SerializedProperty mTmp = mine.Copy(); SerializedProperty tTmp = theirs.Copy(); //I'm really not sure what's going on here. This seems to work differently for different types of properties while(mTmp.Next(enter)) { tTmp.Next(enter); enter = false; //Maybe we want this? if(mTmp.depth != mine.depth) //Once we're back in the same depth, we've gone too far break; bool equal = false; foreach (bool e in PropEqual(mTmp, tTmp, mineParent, theirsParent)) { yield return e; equal = e; } if(!equal) yield break; } yield return true; } //U3: Had to define out some types of components. Default case will warn me about this //Looks like this is already implemented... public static void SetProperty(SerializedProperty from, SerializedProperty to) { switch(from.propertyType) { case SerializedPropertyType.AnimationCurve: to.animationCurveValue = from.animationCurveValue; break; case SerializedPropertyType.ArraySize: Debug.LogWarning("Got ArraySize type"); break; case SerializedPropertyType.Boolean: to.boolValue = from.boolValue; break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Bounds: to.boundsValue = from.boundsValue; break; #endif case SerializedPropertyType.Character: Debug.LogWarning("Got Character type"); break; case SerializedPropertyType.Color: to.colorValue = from.colorValue; break; case SerializedPropertyType.Enum: to.enumValueIndex = from.enumValueIndex; break; case SerializedPropertyType.Float: to.floatValue = from.floatValue; break; case SerializedPropertyType.Generic: #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 Debug.LogWarning("How to copy generic properties in Unity 3?"); #else to.serializedObject.CopyFromSerializedProperty(from); to.serializedObject.ApplyModifiedProperties(); #endif break; /* #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case SerializedPropertyType.Gradient: Debug.LogWarning("Got Gradient type"); break; #endif * */ case SerializedPropertyType.Integer: to.intValue = from.intValue; break; case SerializedPropertyType.LayerMask: to.intValue = from.intValue; break; case SerializedPropertyType.ObjectReference: Debug.Log("blah"); to.objectReferenceValue = from.objectReferenceValue; break; case SerializedPropertyType.Rect: to.rectValue = from.rectValue; break; case SerializedPropertyType.String: to.stringValue = from.stringValue; break; case SerializedPropertyType.Vector2: to.vector2Value = from.vector2Value; break; case SerializedPropertyType.Vector3: to.vector3Value = from.vector3Value; break; #if !(UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5) case (SerializedPropertyType)16: to.quaternionValue = from.quaternionValue; break; #endif default: Debug.LogWarning("Unknown SeralizedPropertyType encountered: " + to.propertyType); break; } } public static bool ChildOfParent(GameObject obj, GameObject parent) { while(true) { if(obj == parent) return true; if(obj.transform.parent == null) break; obj = obj.transform.parent.gameObject; } return false; } public static void GameObjectToList(GameObject obj, List<GameObject> list) { list.Add(obj); foreach(Transform t in obj.transform) GameObjectToList(t.gameObject, list); } /// <summary> /// Determine whether the object is part of a prefab, and if it is the root of the prefab tree /// </summary> /// <param name="g"></param> /// <returns></returns> public static bool IsPrefabParent(GameObject g) { #if UNITY_3_0 || UNITY_3_0_0 || UNITY_3_1 || UNITY_3_2 || UNITY_3_3 || UNITY_3_4 || UNITY_3_5 return EditorUtility.FindPrefabRoot(g) == g; #else return PrefabUtility.FindPrefabRoot(g) == g; #endif } } }
/////////////////////////////////////////////////////////////////////////// // Description: Data Access class for the table 'GroupPolicy' // Generated by LLBLGen v1.21.2003.712 Final on: 16 Oktober 2005, 1:22:11 // Because the Base Class already implements IDispose, this class doesn't. /////////////////////////////////////////////////////////////////////////// using System; using System.Data; using System.Data.SqlTypes; using System.Data.SqlClient; namespace BkNet.DataAccess { /// <summary> /// Purpose: Data Access class for the table 'GroupPolicy'. /// </summary> public class GroupPolicy : DBInteractionBase { #region Class Member Declarations private SqlInt32 _policyId, _policyIdOld, _groupId, _groupIdOld, _recordId; #endregion /// <summary> /// Purpose: Class constructor. /// </summary> public GroupPolicy() { // Nothing for now. } /// <summary> /// Purpose: Select method for a foreign key. This method will Select one or more rows from the database, based on the Foreign Key 'GroupId' /// </summary> /// <returns>DataTable object if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>GroupId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public DataTable SelectAllWGroupIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[GroupPolicy_SelectAllWGroupIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; DataTable toReturn = new DataTable("GroupPolicy"); SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute); // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _groupId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. adapter.Fill(toReturn); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'GroupPolicy_SelectAllWGroupIdLogic' reported the ErrorCode: " + _errorCode); } return toReturn; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("GroupPolicy::SelectAllWGroupIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); adapter.Dispose(); } } /// <summary> /// Purpose: UpdateData method. This method will Update one existing row in the database. /// </summary> /// <param name="IsCheck"></param> /// <returns>True if succeeded, otherwise an Exception is thrown. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>GroupId. May be SqlInt32.Null</LI> /// <LI>PolicyId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> /// public bool UpdateData(bool IsCheck) { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[GroupPolicy_UpdateData]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _groupId)); cmdToExecute.Parameters.Add(new SqlParameter("@PolicyId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _policyId)); cmdToExecute.Parameters.Add(new SqlParameter("@IsCheck", SqlDbType.Bit, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, IsCheck)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'GroupPolicy_UpdateData' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("GroupPolicy::UpdateData::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } /// <summary> /// Purpose: Delete method for a foreign key. This method will Delete one or more rows from the database, based on the Foreign Key 'GroupId' /// </summary> /// <returns>True if succeeded, false otherwise. </returns> /// <remarks> /// Properties needed for this method: /// <UL> /// <LI>GroupId. May be SqlInt32.Null</LI> /// </UL> /// Properties set after a succesful call of this method: /// <UL> /// <LI>ErrorCode</LI> /// </UL> /// </remarks> public bool DeleteAllWGroupIdLogic() { SqlCommand cmdToExecute = new SqlCommand(); cmdToExecute.CommandText = "dbo.[GroupPolicy_DeleteAllWGroupIdLogic]"; cmdToExecute.CommandType = CommandType.StoredProcedure; // Use base class' connection object cmdToExecute.Connection = _mainConnection; try { cmdToExecute.Parameters.Add(new SqlParameter("@GroupId", SqlDbType.Int, 4, ParameterDirection.Input, false, 10, 0, "", DataRowVersion.Proposed, _groupId)); cmdToExecute.Parameters.Add(new SqlParameter("@ErrorCode", SqlDbType.Int, 4, ParameterDirection.Output, false, 10, 0, "", DataRowVersion.Proposed, _errorCode)); // Open connection. _mainConnection.Open(); // Execute query. _rowsAffected = cmdToExecute.ExecuteNonQuery(); _errorCode = (SqlInt32)cmdToExecute.Parameters["@ErrorCode"].Value; if(_errorCode != (int)LLBLError.AllOk) { // Throw error. throw new Exception("Stored Procedure 'GroupPolicy_DeleteAllWGroupIdLogic' reported the ErrorCode: " + _errorCode); } return true; } catch(Exception ex) { // some error occured. Bubble it to caller and encapsulate Exception object throw new Exception("GroupPolicy::DeleteAllWGroupIdLogic::Error occured.", ex); } finally { // Close connection. _mainConnection.Close(); cmdToExecute.Dispose(); } } #region Class Property Declarations public SqlInt32 RecordId { get { return _recordId; } set { SqlInt32 recordIdTmp = (SqlInt32)value; if(recordIdTmp.IsNull) { throw new ArgumentOutOfRangeException("RecordId", "RecordId can't be NULL"); } _recordId = value; } } public SqlInt32 GroupId { get { return _groupId; } set { SqlInt32 groupIdTmp = (SqlInt32)value; if(groupIdTmp.IsNull) { throw new ArgumentOutOfRangeException("GroupId", "GroupId can't be NULL"); } _groupId = value; } } public SqlInt32 GroupIdOld { get { return _groupIdOld; } set { SqlInt32 groupIdOldTmp = (SqlInt32)value; if(groupIdOldTmp.IsNull) { throw new ArgumentOutOfRangeException("GroupIdOld", "GroupIdOld can't be NULL"); } _groupIdOld = value; } } public SqlInt32 PolicyId { get { return _policyId; } set { SqlInt32 policyIdTmp = (SqlInt32)value; if(policyIdTmp.IsNull) { throw new ArgumentOutOfRangeException("PolicyId", "PolicyId can't be NULL"); } _policyId = value; } } public SqlInt32 PolicyIdOld { get { return _policyIdOld; } set { SqlInt32 policyIdOldTmp = (SqlInt32)value; if(policyIdOldTmp.IsNull) { throw new ArgumentOutOfRangeException("PolicyIdOld", "PolicyIdOld can't be NULL"); } _policyIdOld = value; } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Dumps commands in QueryStatus and Exec. // #define DUMP_COMMANDS using System; using System.Windows; using System.Windows.Input; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.InteractiveWindow; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.InteractiveWindow.Shell { /// <summary> /// Default tool window for hosting interactive windows inside of Visual Studio. This hooks up support for /// find in windows, forwarding commands down to the text view adapter, and providing access for setting /// VS specific concepts (such as language service GUIDs) for the interactive window. /// /// Interactive windows can also be hosted outside of this tool window if the user creates an IInteractiveWindow /// directly. In that case the user is responsible for doing what this class does themselves. But the /// interactive window will be properly initialized for running inside of Visual Studio's process by our /// VsInteractiveWindowEditorsFactoryService which handles all of the mapping of VS commands to API calls /// on the interactive window. /// </summary> internal sealed class VsInteractiveWindow : ToolWindowPane, IVsFindTarget, IOleCommandTarget, IVsInteractiveWindow { private readonly IComponentModel _componentModel; private readonly IVsEditorAdaptersFactoryService _editorAdapters; private IInteractiveWindow _window; private IVsFindTarget _findTarget; private IOleCommandTarget _commandTarget; private IInteractiveEvaluator _evaluator; private IWpfTextViewHost _textViewHost; internal VsInteractiveWindow(IComponentModel model, Guid providerId, int instanceId, string title, IInteractiveEvaluator evaluator, __VSCREATETOOLWIN creationFlags) { _componentModel = model; this.Caption = title; _editorAdapters = _componentModel.GetService<IVsEditorAdaptersFactoryService>(); _evaluator = evaluator; // The following calls this.OnCreate: Guid clsId = this.ToolClsid; Guid empty = Guid.Empty; Guid typeId = providerId; IVsWindowFrame frame; var vsShell = (IVsUIShell)ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShell)); // we don't pass __VSCREATETOOLWIN.CTW_fMultiInstance because multi instance panes are // destroyed when closed. We are really multi instance but we don't want to be closed. ErrorHandler.ThrowOnFailure( vsShell.CreateToolWindow( (uint)(__VSCREATETOOLWIN.CTW_fInitNew | __VSCREATETOOLWIN.CTW_fToolbarHost | creationFlags), (uint)instanceId, this.GetIVsWindowPane(), ref clsId, ref typeId, ref empty, null, title, null, out frame ) ); this.Frame = frame; } public void SetLanguage(Guid languageServiceGuid, IContentType contentType) { _window.SetLanguage(languageServiceGuid, contentType); } public IInteractiveWindow InteractiveWindow { get { return _window; } } #region ToolWindowPane overrides protected override void OnCreate() { _window = _componentModel.GetService<IInteractiveWindowFactoryService>().CreateWindow(_evaluator); _window.SubmissionBufferAdded += SubmissionBufferAdded; _textViewHost = _window.GetTextViewHost(); var viewAdapter = _editorAdapters.GetViewAdapter(_textViewHost.TextView); _findTarget = viewAdapter as IVsFindTarget; _commandTarget = viewAdapter as IOleCommandTarget; } private void SubmissionBufferAdded(object sender, SubmissionBufferAddedEventArgs e) { GetToolbarHost().ForceUpdateUI(); } protected override void OnClose() { _window.Close(); base.OnClose(); } protected override void Dispose(bool disposing) { if (disposing) { if (_window != null) { _window.Dispose(); } } } /// <summary> /// This property returns the control that should be hosted in the Tool Window. It can be /// either a FrameworkElement (for easy creation of tool windows hosting WPF content), or it /// can be an object implementing one of the IVsUIWPFElement or IVsUIWin32Element /// interfaces. /// </summary> public override object Content { get { return _textViewHost; } set { } } public override void OnToolWindowCreated() { Guid commandUiGuid = VSConstants.GUID_TextEditorFactory; ((IVsWindowFrame)Frame).SetGuidProperty((int)__VSFPROPID.VSFPROPID_InheritKeyBindings, ref commandUiGuid); base.OnToolWindowCreated(); // add our toolbar which is defined in our VSCT file var toolbarHost = GetToolbarHost(); Guid guidInteractiveCmdSet = Guids.InteractiveCommandSetId; ErrorHandler.ThrowOnFailure(toolbarHost.AddToolbar(VSTWT_LOCATION.VSTWT_TOP, ref guidInteractiveCmdSet, (uint)MenuIds.InteractiveWindowToolbar)); } #endregion #region Window IOleCommandTarget public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) { return _commandTarget.QueryStatus(ref pguidCmdGroup, cCmds, prgCmds, pCmdText); } public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) { return _commandTarget.Exec(ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut); } #endregion #region IVsInteractiveWindow public void Show(bool focus) { var windowFrame = (IVsWindowFrame)Frame; ErrorHandler.ThrowOnFailure(focus ? windowFrame.Show() : windowFrame.ShowNoActivate()); if (focus) { IInputElement input = _window.TextView as IInputElement; if (input != null) { Keyboard.Focus(input); } } } private IVsToolWindowToolbarHost GetToolbarHost() { var frame = (IVsWindowFrame)Frame; object result; ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_ToolbarHost, out result)); return (IVsToolWindowToolbarHost)result; } #endregion #region IVsFindTarget public int Find(string pszSearch, uint grfOptions, int fResetStartPoint, IVsFindHelper pHelper, out uint pResult) { if (_findTarget != null) { return _findTarget.Find(pszSearch, grfOptions, fResetStartPoint, pHelper, out pResult); } pResult = 0; return VSConstants.E_NOTIMPL; } public int GetCapabilities(bool[] pfImage, uint[] pgrfOptions) { if (_findTarget != null && pgrfOptions != null && pgrfOptions.Length > 0) { return _findTarget.GetCapabilities(pfImage, pgrfOptions); } return VSConstants.E_NOTIMPL; } public int GetCurrentSpan(TextSpan[] pts) { if (_findTarget != null) { return _findTarget.GetCurrentSpan(pts); } return VSConstants.E_NOTIMPL; } public int GetFindState(out object ppunk) { if (_findTarget != null) { return _findTarget.GetFindState(out ppunk); } ppunk = null; return VSConstants.E_NOTIMPL; } public int GetMatchRect(RECT[] prc) { if (_findTarget != null) { return _findTarget.GetMatchRect(prc); } return VSConstants.E_NOTIMPL; } public int GetProperty(uint propid, out object pvar) { if (_findTarget != null) { return _findTarget.GetProperty(propid, out pvar); } pvar = null; return VSConstants.E_NOTIMPL; } public int GetSearchImage(uint grfOptions, IVsTextSpanSet[] ppSpans, out IVsTextImage ppTextImage) { if (_findTarget != null) { return _findTarget.GetSearchImage(grfOptions, ppSpans, out ppTextImage); } ppTextImage = null; return VSConstants.E_NOTIMPL; } public int MarkSpan(TextSpan[] pts) { if (_findTarget != null) { return _findTarget.MarkSpan(pts); } return VSConstants.E_NOTIMPL; } public int NavigateTo(TextSpan[] pts) { if (_findTarget != null) { return _findTarget.NavigateTo(pts); } return VSConstants.E_NOTIMPL; } public int NotifyFindTarget(uint notification) { if (_findTarget != null) { return _findTarget.NotifyFindTarget(notification); } return VSConstants.E_NOTIMPL; } public int Replace(string pszSearch, string pszReplace, uint grfOptions, int fResetStartPoint, IVsFindHelper pHelper, out int pfReplaced) { if (_findTarget != null) { return _findTarget.Replace(pszSearch, pszReplace, grfOptions, fResetStartPoint, pHelper, out pfReplaced); } pfReplaced = 0; return VSConstants.E_NOTIMPL; } public int SetFindState(object pUnk) { if (_findTarget != null) { return _findTarget.SetFindState(pUnk); } return VSConstants.E_NOTIMPL; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** ** ** ** Purpose: Exception class for security ** ** =============================================================================*/ namespace System.Security { using System.Security; using System; using System.Runtime.Serialization; using System.Security.Permissions; using System.Reflection; using System.Text; using System.Security.Policy; using System.IO; #if FEATURE_SERIALIZATION using System.Runtime.Serialization.Formatters.Binary; #endif // FEATURE_SERIALIZATION using System.Globalization; using System.Security.Util; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class SecurityException : SystemException { #if FEATURE_CAS_POLICY private String m_debugString; // NOTE: If you change the name of this field, you'll have to update SOS as well! private SecurityAction m_action; [NonSerialized] private Type m_typeOfPermissionThatFailed; private String m_permissionThatFailed; private String m_demanded; private String m_granted; private String m_refused; private String m_denied; private String m_permitOnly; private AssemblyName m_assemblyName; private byte[] m_serializedMethodInfo; private String m_strMethodInfo; private SecurityZone m_zone; private String m_url; private const String ActionName = "Action"; private const String FirstPermissionThatFailedName = "FirstPermissionThatFailed"; private const String DemandedName = "Demanded"; private const String GrantedSetName = "GrantedSet"; private const String RefusedSetName = "RefusedSet"; private const String DeniedName = "Denied"; private const String PermitOnlyName = "PermitOnly"; private const String Assembly_Name = "Assembly"; private const String MethodName_Serialized = "Method"; private const String MethodName_String = "Method_String"; private const String ZoneName = "Zone"; private const String UrlName = "Url"; #endif // #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated internal static string GetResString(string sResourceName) { PermissionSet.s_fullTrust.Assert(); return Environment.GetResourceString(sResourceName); } [System.Security.SecurityCritical] // auto-generated #pragma warning disable 618 internal static Exception MakeSecurityException(AssemblyName asmName, Evidence asmEvidence, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed) #pragma warning restore 618 { #if FEATURE_CAS_POLICY // See if we need to throw a HostProtectionException instead HostProtectionPermission hostProtectionPerm = permThatFailed as HostProtectionPermission; if(hostProtectionPerm != null) return new HostProtectionException(GetResString("HostProtection_HostProtection"), HostProtectionPermission.protectedResources, hostProtectionPerm.Resources); // Produce relevant strings String message = ""; MethodInfo method = null; try { if(granted == null && refused == null && demand == null) { message = GetResString("Security_NoAPTCA"); } else { if(demand != null && demand is IPermission) message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), demand.GetType().AssemblyQualifiedName ); else if (permThatFailed != null) message = String.Format(CultureInfo.InvariantCulture, GetResString("Security_Generic"), permThatFailed.GetType().AssemblyQualifiedName); else message = GetResString("Security_GenericNoType"); } method = SecurityRuntime.GetMethodInfo(rmh); } catch(Exception e) { // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a Contract.Assert in this case or it will lock up the thread.) if(e is System.Threading.ThreadAbortException) throw; } /* catch(System.Threading.ThreadAbortException) { // Environment.GetResourceString will throw if we are ReadyForAbort (thread abort). (We shouldn't do a BCLDebug.Assert in this case or it will lock up the thread.) throw; } catch { } */ // make the exception object return new SecurityException(message, asmName, granted, refused, method, action, demand, permThatFailed, asmEvidence); #else return new SecurityException(GetResString("Arg_SecurityException")); #endif } #if FEATURE_CAS_POLICY private static byte[] ObjectToByteArray(Object obj) { if(obj == null) return null; MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); try { formatter.Serialize(stream, obj); byte[] array = stream.ToArray(); return array; } catch (NotSupportedException) { // Serialization of certain methods is not supported (namely // global methods, since they have no representation outside of // a module scope). return null; } } private static Object ByteArrayToObject(byte[] array) { if(array == null || array.Length == 0) return null; MemoryStream stream = new MemoryStream(array); BinaryFormatter formatter = new BinaryFormatter(); Object obj = formatter.Deserialize(stream); return obj; } #endif // FEATURE_CAS_POLICY public SecurityException() : base(GetResString("Arg_SecurityException")) { SetErrorCode(System.__HResults.COR_E_SECURITY); } public SecurityException(String message) : base(message) { // This is the constructor that gets called if you Assert but don't have permission to Assert. (So don't assert in here.) SetErrorCode(System.__HResults.COR_E_SECURITY); } #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public SecurityException(String message, Type type ) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); m_typeOfPermissionThatFailed = type; } // *** Don't use this constructor internally *** [System.Security.SecuritySafeCritical] // auto-generated public SecurityException(String message, Type type, String state ) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); m_typeOfPermissionThatFailed = type; m_demanded = state; } #endif //FEATURE_CAS_POLICY public SecurityException(String message, Exception inner) : base(message, inner) { SetErrorCode(System.__HResults.COR_E_SECURITY); } #if FEATURE_CAS_POLICY // *** Don't use this constructor internally *** [System.Security.SecurityCritical] // auto-generated internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj ) : base(GetResString("Arg_SecurityException")) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); if (grantedSetObj != null) m_granted = grantedSetObj.ToXml().ToString(); if (refusedSetObj != null) m_refused = refusedSetObj.ToXml().ToString(); } // *** Don't use this constructor internally *** [System.Security.SecurityCritical] // auto-generated internal SecurityException( String message, PermissionSet grantedSetObj, PermissionSet refusedSetObj ) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); if (grantedSetObj != null) m_granted = grantedSetObj.ToXml().ToString(); if (refusedSetObj != null) m_refused = refusedSetObj.ToXml().ToString(); } [System.Security.SecuritySafeCritical] // auto-generated protected SecurityException(SerializationInfo info, StreamingContext context) : base (info, context) { if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); try { m_action = (SecurityAction)info.GetValue(ActionName, typeof(SecurityAction)); m_permissionThatFailed = (String)info.GetValueNoThrow(FirstPermissionThatFailedName, typeof(String)); m_demanded = (String)info.GetValueNoThrow(DemandedName, typeof(String)); m_granted = (String)info.GetValueNoThrow(GrantedSetName, typeof(String)); m_refused = (String)info.GetValueNoThrow(RefusedSetName, typeof(String)); m_denied = (String)info.GetValueNoThrow(DeniedName, typeof(String)); m_permitOnly = (String)info.GetValueNoThrow(PermitOnlyName, typeof(String)); m_assemblyName = (AssemblyName)info.GetValueNoThrow(Assembly_Name, typeof(AssemblyName)); m_serializedMethodInfo = (byte[])info.GetValueNoThrow(MethodName_Serialized, typeof(byte[])); m_strMethodInfo = (String)info.GetValueNoThrow(MethodName_String, typeof(String)); m_zone = (SecurityZone)info.GetValue(ZoneName, typeof(SecurityZone)); m_url = (String)info.GetValueNoThrow(UrlName, typeof(String)); } catch { m_action = 0; m_permissionThatFailed = ""; m_demanded = ""; m_granted = ""; m_refused = ""; m_denied = ""; m_permitOnly = ""; m_assemblyName = null; m_serializedMethodInfo = null; m_strMethodInfo = null; m_zone = SecurityZone.NoZone; m_url = ""; } } // ------------------------------------------ // | For failures due to insufficient grant | // ------------------------------------------ [System.Security.SecuritySafeCritical] // auto-generated public SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); Action = action; if(permThatFailed != null) m_typeOfPermissionThatFailed = permThatFailed.GetType(); FirstPermissionThatFailed = permThatFailed; Demanded = demanded; m_granted = (grant == null ? "" : grant.ToXml().ToString()); m_refused = (refused == null ? "" : refused.ToXml().ToString()); m_denied = ""; m_permitOnly = ""; m_assemblyName = assemblyName; Method = method; m_url = ""; m_zone = SecurityZone.NoZone; if(evidence != null) { Url url = evidence.GetHostEvidence<Url>(); if(url != null) m_url = url.GetURLString().ToString(); Zone zone = evidence.GetHostEvidence<Zone>(); if(zone != null) m_zone = zone.SecurityZone; } m_debugString = this.ToString(true, false); } // ------------------------------------------ // | For failures due to deny or PermitOnly | // ------------------------------------------ [System.Security.SecuritySafeCritical] // auto-generated public SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) : base(message) { PermissionSet.s_fullTrust.Assert(); SetErrorCode(System.__HResults.COR_E_SECURITY); Action = SecurityAction.Demand; if(permThatFailed != null) m_typeOfPermissionThatFailed = permThatFailed.GetType(); FirstPermissionThatFailed = permThatFailed; Demanded = demanded; m_granted = ""; m_refused = ""; DenySetInstance = deny; PermitOnlySetInstance = permitOnly; m_assemblyName = null; Method = method; m_zone = SecurityZone.NoZone; m_url = ""; m_debugString = this.ToString(true, false); } [System.Runtime.InteropServices.ComVisible(false)] public SecurityAction Action { get { return m_action; } set { m_action = value; } } public Type PermissionType { [System.Security.SecuritySafeCritical] // auto-generated get { if(m_typeOfPermissionThatFailed == null) { Object ob = XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); if(ob == null) ob = XMLUtil.XmlStringToSecurityObject(m_demanded); if(ob != null) m_typeOfPermissionThatFailed = ob.GetType(); } return m_typeOfPermissionThatFailed; } set { m_typeOfPermissionThatFailed = value; } } public IPermission FirstPermissionThatFailed { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return (IPermission)XMLUtil.XmlStringToSecurityObject(m_permissionThatFailed); } set { m_permissionThatFailed = XMLUtil.SecurityObjectToXmlString(value); } } public String PermissionState { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return m_demanded; } set { m_demanded = value; } } [System.Runtime.InteropServices.ComVisible(false)] public Object Demanded { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return XMLUtil.XmlStringToSecurityObject(m_demanded); } set { m_demanded = XMLUtil.SecurityObjectToXmlString(value); } } public String GrantedSet { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return m_granted; } set { m_granted = value; } } public String RefusedSet { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return m_refused; } set { m_refused = value; } } [System.Runtime.InteropServices.ComVisible(false)] public Object DenySetInstance { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return XMLUtil.XmlStringToSecurityObject(m_denied); } set { m_denied = XMLUtil.SecurityObjectToXmlString(value); } } [System.Runtime.InteropServices.ComVisible(false)] public Object PermitOnlySetInstance { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return XMLUtil.XmlStringToSecurityObject(m_permitOnly); } set { m_permitOnly = XMLUtil.SecurityObjectToXmlString(value); } } [System.Runtime.InteropServices.ComVisible(false)] public AssemblyName FailedAssemblyInfo { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return m_assemblyName; } set { m_assemblyName = value; } } private MethodInfo getMethod() { return (MethodInfo)ByteArrayToObject(m_serializedMethodInfo); } [System.Runtime.InteropServices.ComVisible(false)] public MethodInfo Method { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return getMethod(); } set { RuntimeMethodInfo m = value as RuntimeMethodInfo; m_serializedMethodInfo = ObjectToByteArray(m); if (m != null) { m_strMethodInfo = m.ToString(); } } } public SecurityZone Zone { get { return m_zone; } set { m_zone = value; } } public String Url { [System.Security.SecuritySafeCritical] // auto-generated [SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)] get { return m_url; } set { m_url = value; } } private void ToStringHelper(StringBuilder sb, String resourceString, Object attr) { if (attr == null) return; String attrString = attr as String; if (attrString == null) attrString = attr.ToString(); if (attrString.Length == 0) return; sb.Append(Environment.NewLine); sb.Append(GetResString(resourceString)); sb.Append(Environment.NewLine); sb.Append(attrString); } [System.Security.SecurityCritical] // auto-generated private String ToString(bool includeSensitiveInfo, bool includeBaseInfo) { PermissionSet.s_fullTrust.Assert(); StringBuilder sb = new StringBuilder(); if(includeBaseInfo) sb.Append(base.ToString()); if(Action > 0) ToStringHelper(sb, "Security_Action", Action); ToStringHelper(sb, "Security_TypeFirstPermThatFailed", PermissionType); if(includeSensitiveInfo) { ToStringHelper(sb, "Security_FirstPermThatFailed", m_permissionThatFailed); ToStringHelper(sb, "Security_Demanded", m_demanded); ToStringHelper(sb, "Security_GrantedSet", m_granted); ToStringHelper(sb, "Security_RefusedSet", m_refused); ToStringHelper(sb, "Security_Denied", m_denied); ToStringHelper(sb, "Security_PermitOnly", m_permitOnly); ToStringHelper(sb, "Security_Assembly", m_assemblyName); ToStringHelper(sb, "Security_Method", m_strMethodInfo); } if(m_zone != SecurityZone.NoZone) ToStringHelper(sb, "Security_Zone", m_zone); if(includeSensitiveInfo) ToStringHelper(sb, "Security_Url", m_url); return sb.ToString(); } #else // FEATURE_CAS_POLICY internal SecurityException( PermissionSet grantedSetObj, PermissionSet refusedSetObj ) : this(){} #pragma warning disable 618 internal SecurityException(string message, AssemblyName assemblyName, PermissionSet grant, PermissionSet refused, MethodInfo method, SecurityAction action, Object demanded, IPermission permThatFailed, Evidence evidence) #pragma warning restore 618 : this(){} internal SecurityException(string message, Object deny, Object permitOnly, MethodInfo method, Object demanded, IPermission permThatFailed) : this(){} public override String ToString() { return base.ToString(); } #endif // FEATURE_CAS_POLICY [System.Security.SecurityCritical] // auto-generated private bool CanAccessSensitiveInfo() { bool retVal = false; try { #pragma warning disable 618 new SecurityPermission(SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy).Demand(); #pragma warning restore 618 retVal = true; } catch(SecurityException) { } return retVal; } #if FEATURE_CAS_POLICY [System.Security.SecuritySafeCritical] // auto-generated public override String ToString() { return ToString(CanAccessSensitiveInfo(), true); } #endif //FEATURE_CAS_POLICY [System.Security.SecurityCritical] // auto-generated_required public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info==null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); base.GetObjectData( info, context ); #if FEATURE_CAS_POLICY info.AddValue(ActionName, m_action, typeof(SecurityAction)); info.AddValue(FirstPermissionThatFailedName, m_permissionThatFailed, typeof(String)); info.AddValue(DemandedName, m_demanded, typeof(String)); info.AddValue(GrantedSetName, m_granted, typeof(String)); info.AddValue(RefusedSetName, m_refused, typeof(String)); info.AddValue(DeniedName, m_denied, typeof(String)); info.AddValue(PermitOnlyName, m_permitOnly, typeof(String)); info.AddValue(Assembly_Name, m_assemblyName, typeof(AssemblyName)); info.AddValue(MethodName_Serialized, m_serializedMethodInfo, typeof(byte[])); info.AddValue(MethodName_String, m_strMethodInfo, typeof(String)); info.AddValue(ZoneName, m_zone, typeof(SecurityZone)); info.AddValue(UrlName, m_url, typeof(String)); #endif // FEATURE_CAS_POLICY } } }