context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Azure.WebJobs.Script.Description; using Microsoft.Azure.WebJobs.Script.Management.Models; using Microsoft.Azure.WebJobs.Script.Rpc; using Microsoft.Azure.WebJobs.Script.WebHost.Extensions; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.WebJobs.Script.WebHost.Management { public class WebFunctionsManager : IWebFunctionsManager { private readonly IOptionsMonitor<ScriptApplicationHostOptions> _applicationHostOptions; private readonly ILogger _logger; private readonly HttpClient _client; private readonly IEnumerable<WorkerConfig> _workerConfigs; private readonly ISecretManagerProvider _secretManagerProvider; private readonly IFunctionsSyncManager _functionsSyncManager; public WebFunctionsManager(IOptionsMonitor<ScriptApplicationHostOptions> applicationHostOptions, IOptions<LanguageWorkerOptions> languageWorkerOptions, ILoggerFactory loggerFactory, HttpClient client, ISecretManagerProvider secretManagerProvider, IFunctionsSyncManager functionsSyncManager) { _applicationHostOptions = applicationHostOptions; _logger = loggerFactory?.CreateLogger(ScriptConstants.LogCategoryHostGeneral); _client = client; _workerConfigs = languageWorkerOptions.Value.WorkerConfigs; _secretManagerProvider = secretManagerProvider; _functionsSyncManager = functionsSyncManager; } /// <summary> /// Calls into ScriptHost to retrieve list of FunctionMetadata /// and maps them to FunctionMetadataResponse. /// </summary> /// <param name="request">Current HttpRequest for figuring out baseUrl</param> /// <returns>collection of FunctionMetadataResponse</returns> public async Task<IEnumerable<FunctionMetadataResponse>> GetFunctionsMetadata(HttpRequest request, bool includeProxies) { var baseUrl = $"{request.Scheme}://{request.Host}"; return await GetFunctionsMetadata(baseUrl, includeProxies); } public async Task<IEnumerable<FunctionMetadataResponse>> GetFunctionsMetadata(string baseUrl, bool includeProxies) { var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); string routePrefix = await GetRoutePrefix(hostOptions.RootScriptPath); var tasks = GetFunctionsMetadata(includeProxies).Select(p => p.ToFunctionMetadataResponse(hostOptions, routePrefix, baseUrl)); return await tasks.WhenAll(); } internal IEnumerable<FunctionMetadata> GetFunctionsMetadata(bool includeProxies = false) { var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); return GetFunctionsMetadata(hostOptions, _workerConfigs, _logger, includeProxies); } internal static IEnumerable<FunctionMetadata> GetFunctionsMetadata(ScriptJobHostOptions hostOptions, IEnumerable<WorkerConfig> workerConfigs, ILogger logger, bool includeProxies = false) { var functionDirectories = FileUtility.EnumerateDirectories(hostOptions.RootScriptPath); IEnumerable<FunctionMetadata> functionsMetadata = FunctionMetadataManager.ReadFunctionsMetadata(functionDirectories, null, workerConfigs, logger, fileSystem: FileUtility.Instance); if (includeProxies) { // get proxies metadata var values = ProxyMetadataManager.ReadProxyMetadata(hostOptions.RootScriptPath, logger); var proxyFunctionsMetadata = values.Item1; if (proxyFunctionsMetadata?.Count > 0) { functionsMetadata = proxyFunctionsMetadata.Concat(functionsMetadata); } } return functionsMetadata; } /// <summary> /// It handles creating a new function or updating an existing one. /// It attempts to clean left over artifacts from a possible previous function with the same name /// if config is changed, then `configChanged` is set to true so the caller can call SyncTriggers if needed. /// </summary> /// <param name="name">name of the function to be created</param> /// <param name="functionMetadata">in case of update for function.json</param> /// <param name="request">Current HttpRequest.</param> /// <returns>(success, configChanged, functionMetadataResult)</returns> public async Task<(bool, bool, FunctionMetadataResponse)> CreateOrUpdate(string name, FunctionMetadataResponse functionMetadata, HttpRequest request) { var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); var configChanged = false; var functionDir = Path.Combine(hostOptions.RootScriptPath, name); // Make sure the function folder exists if (!FileUtility.DirectoryExists(functionDir)) { // Cleanup any leftover artifacts from a function with the same name before. DeleteFunctionArtifacts(functionMetadata); Directory.CreateDirectory(functionDir); } string newConfig = null; string configPath = Path.Combine(functionDir, ScriptConstants.FunctionMetadataFileName); string dataFilePath = FunctionMetadataExtensions.GetTestDataFilePath(name, hostOptions); // If files are included, write them out if (functionMetadata?.Files != null) { // If the config is passed in the file collection, save it and don't process it as a file if (functionMetadata.Files.TryGetValue(ScriptConstants.FunctionMetadataFileName, out newConfig)) { functionMetadata.Files.Remove(ScriptConstants.FunctionMetadataFileName); } // Delete all existing files in the directory. This will also delete current function.json, but it gets recreated below FileUtility.DeleteDirectoryContentsSafe(functionDir); await functionMetadata .Files .Select(e => FileUtility.WriteAsync(Path.Combine(functionDir, e.Key), e.Value)) .WhenAll(); } // Get the config (if it was not already passed in as a file) if (newConfig == null && functionMetadata?.Config != null) { newConfig = JsonConvert.SerializeObject(functionMetadata?.Config, Formatting.Indented); } // Get the current config, if any string currentConfig = null; if (FileUtility.FileExists(configPath)) { currentConfig = await FileUtility.ReadAsync(configPath); } // Save the file and set changed flag is it has changed. This helps optimize the syncTriggers call if (newConfig != currentConfig) { await FileUtility.WriteAsync(configPath, newConfig); configChanged = true; } if (functionMetadata.TestData != null) { await FileUtility.WriteAsync(dataFilePath, functionMetadata.TestData); } // we need to sync triggers if config changed, or the files changed await _functionsSyncManager.TrySyncTriggersAsync(); (var success, var functionMetadataResult) = await TryGetFunction(name, request); return (success, configChanged, functionMetadataResult); } /// <summary> /// maps a functionName to its FunctionMetadataResponse /// </summary> /// <param name="name">Function name to retrieve</param> /// <param name="request">Current HttpRequest</param> /// <returns>(success, FunctionMetadataResponse)</returns> public async Task<(bool, FunctionMetadataResponse)> TryGetFunction(string name, HttpRequest request) { // TODO: DI (FACAVAL) Follow up with ahmels - Since loading of function metadata is no longer tied to the script host, we // should be able to inject an IFunctionMetadataManager here and bypass this step. var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); var functionMetadata = FunctionMetadataManager.ReadFunctionMetadata(Path.Combine(hostOptions.RootScriptPath, name), null, _workerConfigs, new Dictionary<string, ICollection<string>>(), fileSystem: FileUtility.Instance); if (functionMetadata != null) { string routePrefix = await GetRoutePrefix(hostOptions.RootScriptPath); var baseUrl = $"{request.Scheme}://{request.Host}"; return (true, await functionMetadata.ToFunctionMetadataResponse(hostOptions, routePrefix, baseUrl)); } else { return (false, null); } } /// <summary> /// Delete a function and all it's artifacts. /// </summary> /// <param name="function">Function to be deleted</param> /// <returns>(success, errorMessage)</returns> public (bool, string) TryDeleteFunction(FunctionMetadataResponse function) { try { var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); var functionPath = function.GetFunctionPath(hostOptions); if (!string.IsNullOrEmpty(functionPath)) { FileUtility.DeleteDirectoryContentsSafe(functionPath); } DeleteFunctionArtifacts(function); _functionsSyncManager.TrySyncTriggersAsync(); return (true, string.Empty); } catch (Exception e) { return (false, e.ToString()); } } private void DeleteFunctionArtifacts(FunctionMetadataResponse function) { var hostOptions = _applicationHostOptions.CurrentValue.ToHostOptions(); var testDataPath = function.GetFunctionTestDataFilePath(hostOptions); if (!string.IsNullOrEmpty(testDataPath)) { FileUtility.DeleteFileSafe(testDataPath); } } // TODO : Due to lifetime scoping issues (this service lifetime is longer than the lifetime // of HttpOptions sourced from host.json) we're reading the http route prefix anew each time // to ensure we have the latest configured value. internal static async Task<string> GetRoutePrefix(string rootScriptPath) { string routePrefix = "api"; string hostConfigFile = Path.Combine(rootScriptPath, ScriptConstants.HostMetadataFileName); if (File.Exists(hostConfigFile)) { string hostConfigJson = await File.ReadAllTextAsync(hostConfigFile); try { var jo = JObject.Parse(hostConfigJson); var token = jo.SelectToken("extensions['http'].routePrefix", errorWhenNoMatch: false); if (token != null) { routePrefix = (string)token; } } catch { // best effort } } return routePrefix; } } }
using System; using System.IO; namespace ICSharpCode.SharpZipLib.Core { /// <summary> /// Provides simple <see cref="Stream"/>" utilities. /// </summary> public sealed class StreamUtils { /// <summary> /// Read from a <see cref="Stream"/> ensuring all the required data is read. /// </summary> /// <param name="stream">The stream to read.</param> /// <param name="buffer">The buffer to fill.</param> /// <seealso cref="ReadFully(Stream,byte[],int,int)"/> static public void ReadFully(Stream stream, byte[] buffer) { ReadFully(stream, buffer, 0, buffer.Length); } /// <summary> /// Read from a <see cref="Stream"/>" ensuring all the required data is read. /// </summary> /// <param name="stream">The stream to read data from.</param> /// <param name="buffer">The buffer to store data in.</param> /// <param name="offset">The offset at which to begin storing data.</param> /// <param name="count">The number of bytes of data to store.</param> /// <exception cref="ArgumentNullException">Required parameter is null</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> and or <paramref name="count"/> are invalid.</exception> /// <exception cref="EndOfStreamException">End of stream is encountered before all the data has been read.</exception> static public void ReadFully(Stream stream, byte[] buffer, int offset, int count) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // Offset can equal length when buffer and count are 0. if ((offset < 0) || (offset > buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((count < 0) || (offset + count > buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(count)); } while (count > 0) { int readCount = stream.Read(buffer, offset, count); if (readCount <= 0) { throw new EndOfStreamException(); } offset += readCount; count -= readCount; } } /// <summary> /// Copy the contents of one <see cref="Stream"/> to another. /// </summary> /// <param name="source">The stream to source data from.</param> /// <param name="destination">The stream to write data to.</param> /// <param name="buffer">The buffer to use during copying.</param> static public void Copy(Stream source, Stream destination, byte[] buffer) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // Ensure a reasonable size of buffer is used without being prohibitive. if (buffer.Length < 128) { throw new ArgumentException("Buffer is too small", nameof(buffer)); } bool copying = true; while (copying) { int bytesRead = source.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { destination.Write(buffer, 0, bytesRead); } else { destination.Flush(); copying = false; } } } /// <summary> /// Copy the contents of one <see cref="Stream"/> to another. /// </summary> /// <param name="source">The stream to source data from.</param> /// <param name="destination">The stream to write data to.</param> /// <param name="buffer">The buffer to use during copying.</param> /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param> /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param> /// <param name="sender">The source for this event.</param> /// <param name="name">The name to use with the event.</param> /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks> static public void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name) { Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1); } /// <summary> /// Copy the contents of one <see cref="Stream"/> to another. /// </summary> /// <param name="source">The stream to source data from.</param> /// <param name="destination">The stream to write data to.</param> /// <param name="buffer">The buffer to use during copying.</param> /// <param name="progressHandler">The <see cref="ProgressHandler">progress handler delegate</see> to use.</param> /// <param name="updateInterval">The minimum <see cref="TimeSpan"/> between progress updates.</param> /// <param name="sender">The source for this event.</param> /// <param name="name">The name to use with the event.</param> /// <param name="fixedTarget">A predetermined fixed target value to use with progress updates. /// If the value is negative the target is calculated by looking at the stream.</param> /// <remarks>This form is specialised for use within #Zip to support events during archive operations.</remarks> static public void Copy(Stream source, Stream destination, byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name, long fixedTarget) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (destination == null) { throw new ArgumentNullException(nameof(destination)); } if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } // Ensure a reasonable size of buffer is used without being prohibitive. if (buffer.Length < 128) { throw new ArgumentException("Buffer is too small", nameof(buffer)); } if (progressHandler == null) { throw new ArgumentNullException(nameof(progressHandler)); } bool copying = true; DateTime marker = DateTime.Now; long processed = 0; long target = 0; if (fixedTarget >= 0) { target = fixedTarget; } else if (source.CanSeek) { target = source.Length - source.Position; } // Always fire 0% progress.. var args = new ProgressEventArgs(name, processed, target); progressHandler(sender, args); bool progressFired = true; while (copying) { int bytesRead = source.Read(buffer, 0, buffer.Length); if (bytesRead > 0) { processed += bytesRead; progressFired = false; destination.Write(buffer, 0, bytesRead); } else { destination.Flush(); copying = false; } if (DateTime.Now - marker > updateInterval) { progressFired = true; marker = DateTime.Now; args = new ProgressEventArgs(name, processed, target); progressHandler(sender, args); copying = args.ContinueRunning; } } if (!progressFired) { args = new ProgressEventArgs(name, processed, target); progressHandler(sender, args); } } /// <summary> /// Initialise an instance of <see cref="StreamUtils"></see> /// </summary> private StreamUtils() { // Do nothing. } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.MasterSetup.DS { public class MST_CurrencyDS { public MST_CurrencyDS() { } private const string THIS = "PCSComUtils.MasterSetup.DS.MST_CurrencyDS"; //************************************************************************** /// <Description> /// This method uses to add data to MST_Currency /// </Description> /// <Inputs> /// MST_CurrencyVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { MST_CurrencyVO objObject = (MST_CurrencyVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO MST_Currency(" + MST_CurrencyTable.CODE_FLD + "," + MST_CurrencyTable.NAME_FLD + "," + MST_CurrencyTable.MASK_FLD + ")" + "VALUES(?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.MASK_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.MASK_FLD].Value = objObject.Mask; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from MST_Currency /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + MST_CurrencyTable.TABLE_NAME + " WHERE " + "CurrencyID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from MST_Currency /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// MST_CurrencyVO /// </Outputs> /// <Returns> /// MST_CurrencyVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_CurrencyTable.CURRENCYID_FLD + "," + MST_CurrencyTable.CODE_FLD + "," + MST_CurrencyTable.NAME_FLD + "," + MST_CurrencyTable.MASK_FLD + " FROM " + MST_CurrencyTable.TABLE_NAME +" WHERE " + MST_CurrencyTable.CURRENCYID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); MST_CurrencyVO objObject = new MST_CurrencyVO(); while (odrPCS.Read()) { objObject.CurrencyID = int.Parse(odrPCS[MST_CurrencyTable.CURRENCYID_FLD].ToString().Trim()); objObject.Code = odrPCS[MST_CurrencyTable.CODE_FLD].ToString().Trim(); objObject.Name = odrPCS[MST_CurrencyTable.NAME_FLD].ToString().Trim(); objObject.Mask = odrPCS[MST_CurrencyTable.MASK_FLD].ToString().Trim(); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to MST_Currency /// </Description> /// <Inputs> /// MST_CurrencyVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; MST_CurrencyVO objObject = (MST_CurrencyVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE MST_Currency SET " + MST_CurrencyTable.CODE_FLD + "= ?" + "," + MST_CurrencyTable.NAME_FLD + "= ?" + "," + MST_CurrencyTable.MASK_FLD + "= ?" +" WHERE " + MST_CurrencyTable.CURRENCYID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.CODE_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.CODE_FLD].Value = objObject.Code; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.NAME_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.NAME_FLD].Value = objObject.Name; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.MASK_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[MST_CurrencyTable.MASK_FLD].Value = objObject.Mask; ocmdPCS.Parameters.Add(new OleDbParameter(MST_CurrencyTable.CURRENCYID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[MST_CurrencyTable.CURRENCYID_FLD].Value = objObject.CurrencyID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from MST_Currency /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + MST_CurrencyTable.CURRENCYID_FLD + "," + MST_CurrencyTable.CODE_FLD + "," + MST_CurrencyTable.NAME_FLD + "," + MST_CurrencyTable.MASK_FLD + " FROM " + MST_CurrencyTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,MST_CurrencyTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Tuesday, January 25, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + MST_CurrencyTable.CURRENCYID_FLD + "," + MST_CurrencyTable.CODE_FLD + "," + MST_CurrencyTable.NAME_FLD + "," + MST_CurrencyTable.MASK_FLD + " FROM " + MST_CurrencyTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,MST_CurrencyTable.TABLE_NAME); } catch(OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get home currency of CCN /// </summary> /// <param name="pintCCNID">CCN ID</param> /// <returns>Home Currency Code</returns> public string GetCurrencyByCCN(int pintCCNID) { const string METHOD_NAME = THIS + ".GetCurrencyByCCN()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT Code FROM MST_Currency WHERE CurrencyID = " + " (SELECT HomeCurrencyID FROM MST_CCN WHERE CCNID = " + pintCCNID + ")"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); return ocmdPCS.ExecuteScalar().ToString(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public object GetUSDCurrency() { const string METHOD_NAME = THIS + ".GetUSDCurrency()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT CurrencyID, Code, Name, Mask FROM MST_Currency WHERE Code = 'USD'"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataReader odrdPCS = ocmdPCS.ExecuteReader(); MST_CurrencyVO voCurrency = null; if (odrdPCS.HasRows) { voCurrency = new MST_CurrencyVO(); while (odrdPCS.Read()) { voCurrency.CurrencyID = Convert.ToInt32(odrdPCS["CurrencyID"].ToString()); voCurrency.Code = odrdPCS["Code"].ToString(); voCurrency.Name = odrdPCS["Name"].ToString(); voCurrency.Mask = odrdPCS["Mask"].ToString(); } } return voCurrency; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedParticipantsClientSnippets { /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipantRequestObject() { // Snippet: CreateParticipant(CreateParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; // Make the request Participant response = participantsClient.CreateParticipant(request); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantRequestObjectAsync() { // Snippet: CreateParticipantAsync(CreateParticipantRequest, CallSettings) // Additional: CreateParticipantAsync(CreateParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) CreateParticipantRequest request = new CreateParticipantRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), Participant = new Participant(), }; // Make the request Participant response = await participantsClient.CreateParticipantAsync(request); // End snippet } /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipant() { // Snippet: CreateParticipant(string, Participant, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; Participant participant = new Participant(); // Make the request Participant response = participantsClient.CreateParticipant(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantAsync() { // Snippet: CreateParticipantAsync(string, Participant, CallSettings) // Additional: CreateParticipantAsync(string, Participant, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; Participant participant = new Participant(); // Make the request Participant response = await participantsClient.CreateParticipantAsync(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipant</summary> public void CreateParticipantResourceNames() { // Snippet: CreateParticipant(ConversationName, Participant, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); Participant participant = new Participant(); // Make the request Participant response = participantsClient.CreateParticipant(parent, participant); // End snippet } /// <summary>Snippet for CreateParticipantAsync</summary> public async Task CreateParticipantResourceNamesAsync() { // Snippet: CreateParticipantAsync(ConversationName, Participant, CallSettings) // Additional: CreateParticipantAsync(ConversationName, Participant, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); Participant participant = new Participant(); // Make the request Participant response = await participantsClient.CreateParticipantAsync(parent, participant); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipantRequestObject() { // Snippet: GetParticipant(GetParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; // Make the request Participant response = participantsClient.GetParticipant(request); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantRequestObjectAsync() { // Snippet: GetParticipantAsync(GetParticipantRequest, CallSettings) // Additional: GetParticipantAsync(GetParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) GetParticipantRequest request = new GetParticipantRequest { ParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), }; // Make the request Participant response = await participantsClient.GetParticipantAsync(request); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipant() { // Snippet: GetParticipant(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request Participant response = participantsClient.GetParticipant(name); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantAsync() { // Snippet: GetParticipantAsync(string, CallSettings) // Additional: GetParticipantAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request Participant response = await participantsClient.GetParticipantAsync(name); // End snippet } /// <summary>Snippet for GetParticipant</summary> public void GetParticipantResourceNames() { // Snippet: GetParticipant(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName name = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request Participant response = participantsClient.GetParticipant(name); // End snippet } /// <summary>Snippet for GetParticipantAsync</summary> public async Task GetParticipantResourceNamesAsync() { // Snippet: GetParticipantAsync(ParticipantName, CallSettings) // Additional: GetParticipantAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName name = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request Participant response = await participantsClient.GetParticipantAsync(name); // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipantsRequestObject() { // Snippet: ListParticipants(ListParticipantsRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ListParticipantsRequest request = new ListParticipantsRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), }; // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(request); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsRequestObjectAsync() { // Snippet: ListParticipantsAsync(ListParticipantsRequest, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ListParticipantsRequest request = new ListParticipantsRequest { ParentAsConversationName = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"), }; // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipants() { // Snippet: ListParticipants(string, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsAsync() { // Snippet: ListParticipantsAsync(string, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]"; // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipants</summary> public void ListParticipantsResourceNames() { // Snippet: ListParticipants(ConversationName, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); // Make the request PagedEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipants(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Participant item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListParticipantsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListParticipantsAsync</summary> public async Task ListParticipantsResourceNamesAsync() { // Snippet: ListParticipantsAsync(ConversationName, string, int?, CallSettings) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ConversationName parent = ConversationName.FromProjectConversation("[PROJECT]", "[CONVERSATION]"); // Make the request PagedAsyncEnumerable<ListParticipantsResponse, Participant> response = participantsClient.ListParticipantsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Participant item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListParticipantsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Participant item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Participant> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Participant item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for UpdateParticipant</summary> public void UpdateParticipantRequestObject() { // Snippet: UpdateParticipant(UpdateParticipantRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new FieldMask(), }; // Make the request Participant response = participantsClient.UpdateParticipant(request); // End snippet } /// <summary>Snippet for UpdateParticipantAsync</summary> public async Task UpdateParticipantRequestObjectAsync() { // Snippet: UpdateParticipantAsync(UpdateParticipantRequest, CallSettings) // Additional: UpdateParticipantAsync(UpdateParticipantRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) UpdateParticipantRequest request = new UpdateParticipantRequest { Participant = new Participant(), UpdateMask = new FieldMask(), }; // Make the request Participant response = await participantsClient.UpdateParticipantAsync(request); // End snippet } /// <summary>Snippet for UpdateParticipant</summary> public void UpdateParticipant() { // Snippet: UpdateParticipant(Participant, FieldMask, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) Participant participant = new Participant(); FieldMask updateMask = new FieldMask(); // Make the request Participant response = participantsClient.UpdateParticipant(participant, updateMask); // End snippet } /// <summary>Snippet for UpdateParticipantAsync</summary> public async Task UpdateParticipantAsync() { // Snippet: UpdateParticipantAsync(Participant, FieldMask, CallSettings) // Additional: UpdateParticipantAsync(Participant, FieldMask, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) Participant participant = new Participant(); FieldMask updateMask = new FieldMask(); // Make the request Participant response = await participantsClient.UpdateParticipantAsync(participant, updateMask); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContentRequestObject() { // Snippet: AnalyzeContent(AnalyzeContentRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), QueryParams = new QueryParameters(), RequestId = "", AssistQueryParams = new AssistQueryParameters(), }; // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(request); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContentRequestObjectAsync() { // Snippet: AnalyzeContentAsync(AnalyzeContentRequest, CallSettings) // Additional: AnalyzeContentAsync(AnalyzeContentRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) AnalyzeContentRequest request = new AnalyzeContentRequest { ParticipantAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), ReplyAudioConfig = new OutputAudioConfig(), TextInput = new TextInput(), QueryParams = new QueryParameters(), RequestId = "", AssistQueryParams = new AssistQueryParameters(), }; // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(request); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent1() { // Snippet: AnalyzeContent(string, TextInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent1Async() { // Snippet: AnalyzeContentAsync(string, TextInput, CallSettings) // Additional: AnalyzeContentAsync(string, TextInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent1ResourceNames() { // Snippet: AnalyzeContent(ParticipantName, TextInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent1ResourceNamesAsync() { // Snippet: AnalyzeContentAsync(ParticipantName, TextInput, CallSettings) // Additional: AnalyzeContentAsync(ParticipantName, TextInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); TextInput textInput = new TextInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, textInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent2() { // Snippet: AnalyzeContent(string, EventInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent2Async() { // Snippet: AnalyzeContentAsync(string, EventInput, CallSettings) // Additional: AnalyzeContentAsync(string, EventInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string participant = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContent</summary> public void AnalyzeContent2ResourceNames() { // Snippet: AnalyzeContent(ParticipantName, EventInput, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = participantsClient.AnalyzeContent(participant, eventInput); // End snippet } /// <summary>Snippet for AnalyzeContentAsync</summary> public async Task AnalyzeContent2ResourceNamesAsync() { // Snippet: AnalyzeContentAsync(ParticipantName, EventInput, CallSettings) // Additional: AnalyzeContentAsync(ParticipantName, EventInput, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName participant = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); EventInput eventInput = new EventInput(); // Make the request AnalyzeContentResponse response = await participantsClient.AnalyzeContentAsync(participant, eventInput); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticlesRequestObject() { // Snippet: SuggestArticles(SuggestArticlesRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, AssistQueryParams = new AssistQueryParameters(), }; // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(request); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesRequestObjectAsync() { // Snippet: SuggestArticlesAsync(SuggestArticlesRequest, CallSettings) // Additional: SuggestArticlesAsync(SuggestArticlesRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) SuggestArticlesRequest request = new SuggestArticlesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, AssistQueryParams = new AssistQueryParameters(), }; // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(request); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticles() { // Snippet: SuggestArticles(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(parent); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesAsync() { // Snippet: SuggestArticlesAsync(string, CallSettings) // Additional: SuggestArticlesAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(parent); // End snippet } /// <summary>Snippet for SuggestArticles</summary> public void SuggestArticlesResourceNames() { // Snippet: SuggestArticles(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestArticlesResponse response = participantsClient.SuggestArticles(parent); // End snippet } /// <summary>Snippet for SuggestArticlesAsync</summary> public async Task SuggestArticlesResourceNamesAsync() { // Snippet: SuggestArticlesAsync(ParticipantName, CallSettings) // Additional: SuggestArticlesAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestArticlesResponse response = await participantsClient.SuggestArticlesAsync(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswersRequestObject() { // Snippet: SuggestFaqAnswers(SuggestFaqAnswersRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, AssistQueryParams = new AssistQueryParameters(), }; // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(request); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersRequestObjectAsync() { // Snippet: SuggestFaqAnswersAsync(SuggestFaqAnswersRequest, CallSettings) // Additional: SuggestFaqAnswersAsync(SuggestFaqAnswersRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) SuggestFaqAnswersRequest request = new SuggestFaqAnswersRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, AssistQueryParams = new AssistQueryParameters(), }; // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(request); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswers() { // Snippet: SuggestFaqAnswers(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersAsync() { // Snippet: SuggestFaqAnswersAsync(string, CallSettings) // Additional: SuggestFaqAnswersAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswers</summary> public void SuggestFaqAnswersResourceNames() { // Snippet: SuggestFaqAnswers(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestFaqAnswersResponse response = participantsClient.SuggestFaqAnswers(parent); // End snippet } /// <summary>Snippet for SuggestFaqAnswersAsync</summary> public async Task SuggestFaqAnswersResourceNamesAsync() { // Snippet: SuggestFaqAnswersAsync(ParticipantName, CallSettings) // Additional: SuggestFaqAnswersAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestFaqAnswersResponse response = await participantsClient.SuggestFaqAnswersAsync(parent); // End snippet } /// <summary>Snippet for SuggestSmartReplies</summary> public void SuggestSmartRepliesRequestObject() { // Snippet: SuggestSmartReplies(SuggestSmartRepliesRequest, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) SuggestSmartRepliesRequest request = new SuggestSmartRepliesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, CurrentTextInput = new TextInput(), }; // Make the request SuggestSmartRepliesResponse response = participantsClient.SuggestSmartReplies(request); // End snippet } /// <summary>Snippet for SuggestSmartRepliesAsync</summary> public async Task SuggestSmartRepliesRequestObjectAsync() { // Snippet: SuggestSmartRepliesAsync(SuggestSmartRepliesRequest, CallSettings) // Additional: SuggestSmartRepliesAsync(SuggestSmartRepliesRequest, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) SuggestSmartRepliesRequest request = new SuggestSmartRepliesRequest { ParentAsParticipantName = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"), LatestMessageAsMessageName = MessageName.FromProjectConversationMessage("[PROJECT]", "[CONVERSATION]", "[MESSAGE]"), ContextSize = 0, CurrentTextInput = new TextInput(), }; // Make the request SuggestSmartRepliesResponse response = await participantsClient.SuggestSmartRepliesAsync(request); // End snippet } /// <summary>Snippet for SuggestSmartReplies</summary> public void SuggestSmartReplies() { // Snippet: SuggestSmartReplies(string, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestSmartRepliesResponse response = participantsClient.SuggestSmartReplies(parent); // End snippet } /// <summary>Snippet for SuggestSmartRepliesAsync</summary> public async Task SuggestSmartRepliesAsync() { // Snippet: SuggestSmartRepliesAsync(string, CallSettings) // Additional: SuggestSmartRepliesAsync(string, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/conversations/[CONVERSATION]/participants/[PARTICIPANT]"; // Make the request SuggestSmartRepliesResponse response = await participantsClient.SuggestSmartRepliesAsync(parent); // End snippet } /// <summary>Snippet for SuggestSmartReplies</summary> public void SuggestSmartRepliesResourceNames() { // Snippet: SuggestSmartReplies(ParticipantName, CallSettings) // Create client ParticipantsClient participantsClient = ParticipantsClient.Create(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestSmartRepliesResponse response = participantsClient.SuggestSmartReplies(parent); // End snippet } /// <summary>Snippet for SuggestSmartRepliesAsync</summary> public async Task SuggestSmartRepliesResourceNamesAsync() { // Snippet: SuggestSmartRepliesAsync(ParticipantName, CallSettings) // Additional: SuggestSmartRepliesAsync(ParticipantName, CancellationToken) // Create client ParticipantsClient participantsClient = await ParticipantsClient.CreateAsync(); // Initialize request argument(s) ParticipantName parent = ParticipantName.FromProjectConversationParticipant("[PROJECT]", "[CONVERSATION]", "[PARTICIPANT]"); // Make the request SuggestSmartRepliesResponse response = await participantsClient.SuggestSmartRepliesAsync(parent); // End snippet } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DBSnapshot Object /// </summary> public class DBSnapshotUnmarshaller : IUnmarshaller<DBSnapshot, XmlUnmarshallerContext>, IUnmarshaller<DBSnapshot, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public DBSnapshot Unmarshall(XmlUnmarshallerContext context) { DBSnapshot unmarshalledObject = new DBSnapshot(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("AllocatedStorage", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.AllocatedStorage = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("AvailabilityZone", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DBInstanceIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DBInstanceIdentifier = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("DBSnapshotIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.DBSnapshotIdentifier = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Encrypted", targetDepth)) { var unmarshaller = BoolUnmarshaller.Instance; unmarshalledObject.Encrypted = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Engine", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Engine = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("EngineVersion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.EngineVersion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("InstanceCreateTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.InstanceCreateTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Iops", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Iops = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("KmsKeyId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.KmsKeyId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("LicenseModel", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.LicenseModel = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("MasterUsername", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.MasterUsername = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("OptionGroupName", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.OptionGroupName = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("PercentProgress", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.PercentProgress = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Port", targetDepth)) { var unmarshaller = IntUnmarshaller.Instance; unmarshalledObject.Port = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SnapshotCreateTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.SnapshotCreateTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SnapshotType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SnapshotType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SourceDBSnapshotIdentifier", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SourceDBSnapshotIdentifier = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("SourceRegion", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.SourceRegion = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("StorageType", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.StorageType = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("TdeCredentialArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.TdeCredentialArn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("VpcId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.VpcId = unmarshaller.Unmarshall(context); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return unmarshalledObject; } } return unmarshalledObject; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <returns></returns> public DBSnapshot Unmarshall(JsonUnmarshallerContext context) { return null; } private static DBSnapshotUnmarshaller _instance = new DBSnapshotUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DBSnapshotUnmarshaller Instance { get { return _instance; } } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { internal enum TriggerIdentifierKind { NotRenamable, RenamableDeclaration, RenamableReference, } /// <summary> /// Determines whether the original token was a renamable identifier on a background thread /// </summary> private class TrackingSession : ForegroundThreadAffinitizedObject { private static readonly Task<TriggerIdentifierKind> s_notRenamableTask = Task.FromResult(TriggerIdentifierKind.NotRenamable); private readonly Task<TriggerIdentifierKind> _isRenamableIdentifierTask; private readonly CancellationTokenSource _cancellationTokenSource; private readonly CancellationToken _cancellationToken; private readonly IAsynchronousOperationListener _asyncListener; private Task<bool> _newIdentifierBindsTask = SpecializedTasks.False; private readonly string _originalName; public string OriginalName { get { return _originalName; } } private readonly ITrackingSpan _trackingSpan; public ITrackingSpan TrackingSpan { get { return _trackingSpan; } } private bool _forceRenameOverloads; public bool ForceRenameOverloads { get { return _forceRenameOverloads; } } public TrackingSession(StateMachine stateMachine, SnapshotSpan snapshotSpan, IAsynchronousOperationListener asyncListener) { AssertIsForeground(); _asyncListener = asyncListener; _trackingSpan = snapshotSpan.Snapshot.CreateTrackingSpan(snapshotSpan.Span, SpanTrackingMode.EdgeInclusive); _cancellationTokenSource = new CancellationTokenSource(); _cancellationToken = _cancellationTokenSource.Token; if (snapshotSpan.Length > 0) { // If the snapshotSpan is nonempty, then the session began with a change that // was touching a word. Asynchronously determine whether that word was a // renamable identifier. If it is, alert the state machine so it can trigger // tagging. _originalName = snapshotSpan.GetText(); _isRenamableIdentifierTask = Task.Factory.SafeStartNewFromAsync( () => DetermineIfRenamableIdentifierAsync(snapshotSpan, initialCheck: true), _cancellationToken, TaskScheduler.Default); var asyncToken = _asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateTrackingSessionAfterIsRenamableIdentifierTask"); _isRenamableIdentifierTask.SafeContinueWith( t => stateMachine.UpdateTrackingSessionIfRenamable(), _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken); QueueUpdateToStateMachine(stateMachine, _isRenamableIdentifierTask); } else { // If the snapshotSpan is empty, that means text was added in a location that is // not touching an existing word, which happens a fair amount when writing new // code. In this case we already know that the user is not renaming an // identifier. _isRenamableIdentifierTask = s_notRenamableTask; } } private void QueueUpdateToStateMachine(StateMachine stateMachine, Task task) { var asyncToken = _asyncListener.BeginAsyncOperation($"{GetType().Name}.{nameof(QueueUpdateToStateMachine)}"); task.SafeContinueWith(t => { AssertIsForeground(); if (_isRenamableIdentifierTask.Result != TriggerIdentifierKind.NotRenamable) { stateMachine.OnTrackingSessionUpdated(this); } }, _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, ForegroundTaskScheduler).CompletesAsyncOperation(asyncToken); } internal void CheckNewIdentifier(StateMachine stateMachine, ITextSnapshot snapshot) { AssertIsForeground(); _newIdentifierBindsTask = _isRenamableIdentifierTask.SafeContinueWithFromAsync( async t => t.Result != TriggerIdentifierKind.NotRenamable && TriggerIdentifierKind.RenamableReference == await DetermineIfRenamableIdentifierAsync( TrackingSpan.GetSpan(snapshot), initialCheck: false).ConfigureAwait(false), _cancellationToken, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.Default); QueueUpdateToStateMachine(stateMachine, _newIdentifierBindsTask); } internal bool IsDefinitelyRenamableIdentifier() { // This needs to be able to run on a background thread for the CodeFix return IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult: false, cancellationToken: CancellationToken.None); } public void Cancel() { AssertIsForeground(); _cancellationTokenSource.Cancel(); } private async Task<TriggerIdentifierKind> DetermineIfRenamableIdentifierAsync(SnapshotSpan snapshotSpan, bool initialCheck) { AssertIsBackground(); var document = snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); if (document != null) { var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var syntaxTree = await document.GetSyntaxTreeAsync(_cancellationToken).ConfigureAwait(false); var token = syntaxTree.GetTouchingWord(snapshotSpan.Start.Position, syntaxFactsService, _cancellationToken); // The OriginalName is determined with a simple textual check, so for a // statement such as "Dim [x = 1" the textual check will return a name of "[x". // The token found for "[x" is an identifier token, but only due to error // recovery (the "[x" is actually in the trailing trivia). If the OriginalName // found through the textual check has a different length than the span of the // touching word, then we cannot perform a rename. if (initialCheck && token.Span.Length != this.OriginalName.Length) { return TriggerIdentifierKind.NotRenamable; } var languageHeuristicsService = document.Project.LanguageServices.GetService<IRenameTrackingLanguageHeuristicsService>(); if (syntaxFactsService.IsIdentifier(token) && languageHeuristicsService.IsIdentifierValidForRenameTracking(token.Text)) { var semanticModel = await document.GetSemanticModelForNodeAsync(token.Parent, _cancellationToken).ConfigureAwait(false); var semanticFacts = document.GetLanguageService<ISemanticFactsService>(); var renameSymbolInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, _cancellationToken); if (!renameSymbolInfo.HasSymbols) { return TriggerIdentifierKind.NotRenamable; } if (renameSymbolInfo.IsMemberGroup) { // This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option _forceRenameOverloads = true; return await DetermineIfRenamableSymbolsAsync(renameSymbolInfo.Symbols, document, token).ConfigureAwait(false); } else { return await DetermineIfRenamableSymbolAsync(renameSymbolInfo.Symbols.Single(), document, token).ConfigureAwait(false); } } } return TriggerIdentifierKind.NotRenamable; } private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolsAsync(IEnumerable<ISymbol> symbols, Document document, SyntaxToken token) { foreach (var symbol in symbols) { // Get the source symbol if possible var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol; if (!sourceSymbol.Locations.All(loc => loc.IsInSource)) { return TriggerIdentifierKind.NotRenamable; } } return TriggerIdentifierKind.RenamableReference; } private async Task<TriggerIdentifierKind> DetermineIfRenamableSymbolAsync(ISymbol symbol, Document document, SyntaxToken token) { // Get the source symbol if possible var sourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol, document.Project.Solution, _cancellationToken).ConfigureAwait(false) ?? symbol; if (!sourceSymbol.Locations.All(loc => loc.IsInSource)) { return TriggerIdentifierKind.NotRenamable; } return sourceSymbol.Locations.Any(loc => loc == token.GetLocation()) ? TriggerIdentifierKind.RenamableDeclaration : TriggerIdentifierKind.RenamableReference; } internal bool CanInvokeRename( ISyntaxFactsService syntaxFactsService, IRenameTrackingLanguageHeuristicsService languageHeuristicsService, bool isSmartTagCheck, bool waitForResult, CancellationToken cancellationToken) { if (IsRenamableIdentifier(_isRenamableIdentifierTask, waitForResult, cancellationToken)) { var isRenamingDeclaration = _isRenamableIdentifierTask.Result == TriggerIdentifierKind.RenamableDeclaration; var newName = TrackingSpan.GetText(TrackingSpan.TextBuffer.CurrentSnapshot); var comparison = isRenamingDeclaration || syntaxFactsService.IsCaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; if (!string.Equals(OriginalName, newName, comparison) && syntaxFactsService.IsValidIdentifier(newName) && languageHeuristicsService.IsIdentifierValidForRenameTracking(newName)) { // At this point, we want to allow renaming if the user invoked Ctrl+. explicitly, but we // want to avoid showing a smart tag if we're renaming a reference that binds to an existing // symbol. if (!isSmartTagCheck || isRenamingDeclaration || !NewIdentifierDefinitelyBindsToReference()) { return true; } } } return false; } private bool NewIdentifierDefinitelyBindsToReference() { return _newIdentifierBindsTask.Status == TaskStatus.RanToCompletion && _newIdentifierBindsTask.Result; } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Differencing; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudio.Text.Operations; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { /// <summary> /// An IVisualStudioDocument which represents the secondary buffer to the workspace API. /// </summary> internal sealed class ContainedDocument : ForegroundThreadAffinitizedObject, IVisualStudioHostDocument { private const string ReturnReplacementString = @"{|r|}"; private const string NewLineReplacementString = @"{|n|}"; private const string HTML = "HTML"; private const string Razor = "Razor"; private const string XOML = "XOML"; private const char RazorExplicit = '@'; private const string CSharpRazorBlock = "{"; private const string VBRazorBlock = "code"; private const string HelperRazor = "helper"; private const string FunctionsRazor = "functions"; private static readonly EditOptions s_venusEditOptions = new EditOptions(new StringDifferenceOptions { DifferenceType = StringDifferenceTypes.Character, IgnoreTrimWhiteSpace = false }); private readonly AbstractContainedLanguage _containedLanguage; private readonly SourceCodeKind _sourceCodeKind; private readonly IComponentModel _componentModel; private readonly Workspace _workspace; private readonly ITextDifferencingSelectorService _differenceSelectorService; private readonly IOptionService _optionService; private readonly HostType _hostType; private readonly ReiteratedVersionSnapshotTracker _snapshotTracker; private readonly IFormattingRule _vbHelperFormattingRule; private readonly string _itemMoniker; public AbstractProject Project { get { return _containedLanguage.Project; } } public bool SupportsRename { get { return _hostType == HostType.Razor; } } public DocumentId Id { get; } public IReadOnlyList<string> Folders { get; } public TextLoader Loader { get; } public DocumentKey Key { get; } public ContainedDocument( AbstractContainedLanguage containedLanguage, SourceCodeKind sourceCodeKind, Workspace workspace, IVsHierarchy hierarchy, uint itemId, IComponentModel componentModel, IFormattingRule vbHelperFormattingRule) { Contract.ThrowIfNull(containedLanguage); _containedLanguage = containedLanguage; _sourceCodeKind = sourceCodeKind; _componentModel = componentModel; _workspace = workspace; _optionService = _workspace.Services.GetService<IOptionService>(); _hostType = GetHostType(); var rdt = (IVsRunningDocumentTable)componentModel.GetService<SVsServiceProvider>().GetService(typeof(SVsRunningDocumentTable)); IVsHierarchy sharedHierarchy; uint itemIdInSharedHierarchy; var isSharedHierarchy = LinkedFileUtilities.TryGetSharedHierarchyAndItemId(hierarchy, itemId, out sharedHierarchy, out itemIdInSharedHierarchy); var filePath = isSharedHierarchy ? rdt.GetMonikerForHierarchyAndItemId(sharedHierarchy, itemIdInSharedHierarchy) : rdt.GetMonikerForHierarchyAndItemId(hierarchy, itemId); // we couldn't look up the document moniker in RDT for a hierarchy/item pair // Since we only use this moniker as a key, we could fall back to something else, like the document name. if (filePath == null) { Debug.Assert(false, "Could not get the document moniker for an item in its hierarchy."); filePath = hierarchy.GetDocumentNameForHierarchyAndItemId(itemId); } if (Project.Hierarchy != null) { string moniker; Project.Hierarchy.GetCanonicalName(itemId, out moniker); _itemMoniker = moniker; } this.Key = new DocumentKey(Project, filePath); this.Id = DocumentId.CreateNewId(Project.Id, filePath); this.Folders = containedLanguage.Project.GetFolderNames(itemId); this.Loader = TextLoader.From(containedLanguage.SubjectBuffer.AsTextContainer(), VersionStamp.Create(), filePath); _differenceSelectorService = componentModel.GetService<ITextDifferencingSelectorService>(); _snapshotTracker = new ReiteratedVersionSnapshotTracker(_containedLanguage.SubjectBuffer); _vbHelperFormattingRule = vbHelperFormattingRule; } private HostType GetHostType() { var projectionBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionBuffer != null) { if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(HTML))) { return HostType.HTML; } if (projectionBuffer.SourceBuffers.Any(b => b.ContentType.IsOfType(Razor))) { return HostType.Razor; } } else { // XOML is set up differently. For XOML, the secondary buffer (i.e. SubjectBuffer) // is a projection buffer, while the primary buffer (i.e. DataBuffer) is not. Instead, // the primary buffer is a regular unprojected ITextBuffer with the HTML content type. if (_containedLanguage.DataBuffer.CurrentSnapshot.ContentType.IsOfType(HTML)) { return HostType.XOML; } } throw ExceptionUtilities.Unreachable; } public DocumentInfo GetInitialState() { return DocumentInfo.Create( this.Id, this.Name, folders: this.Folders, sourceCodeKind: _sourceCodeKind, loader: this.Loader, filePath: this.Key.Moniker); } public bool IsOpen { get { return true; } } #pragma warning disable 67 public event EventHandler UpdatedOnDisk; public event EventHandler<bool> Opened; public event EventHandler<bool> Closing; #pragma warning restore 67 IVisualStudioHostProject IVisualStudioHostDocument.Project { get { return this.Project; } } public ITextBuffer GetOpenTextBuffer() { return _containedLanguage.SubjectBuffer; } public SourceTextContainer GetOpenTextContainer() { return this.GetOpenTextBuffer().AsTextContainer(); } public IContentType ContentType { get { return _containedLanguage.SubjectBuffer.ContentType; } } public string Name { get { try { return Path.GetFileName(this.FilePath); } catch (ArgumentException) { return this.FilePath; } } } public SourceCodeKind SourceCodeKind { get { return _sourceCodeKind; } } public string FilePath { get { return Key.Moniker; } } public AbstractContainedLanguage ContainedLanguage { get { return _containedLanguage; } } public void Dispose() { _snapshotTracker.StopTracking(_containedLanguage.SubjectBuffer); this.ContainedLanguage.Dispose(); } public DocumentId FindProjectDocumentIdWithItemId(uint itemidInsertionPoint) { return Project.GetCurrentDocuments().SingleOrDefault(d => d.GetItemId() == itemidInsertionPoint).Id; } public uint FindItemIdOfDocument(Document document) { return Project.GetDocumentOrAdditionalDocument(document.Id).GetItemId(); } public void UpdateText(SourceText newText) { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var originalSnapshot = subjectBuffer.CurrentSnapshot; var originalText = originalSnapshot.AsText(); var changes = newText.GetTextChanges(originalText); IEnumerable<int> affectedVisibleSpanIndices = null; var editorVisibleSpansInOriginal = SharedPools.Default<List<TextSpan>>().AllocateAndClear(); try { var originalDocument = _workspace.CurrentSolution.GetDocument(this.Id); editorVisibleSpansInOriginal.AddRange(GetEditorVisibleSpans()); var newChanges = FilterTextChanges(originalText, editorVisibleSpansInOriginal, changes).ToList(); if (newChanges.Count == 0) { // no change to apply return; } ApplyChanges(subjectBuffer, newChanges, editorVisibleSpansInOriginal, out affectedVisibleSpanIndices); AdjustIndentation(subjectBuffer, affectedVisibleSpanIndices); } finally { SharedPools.Default<HashSet<int>>().ClearAndFree((HashSet<int>)affectedVisibleSpanIndices); SharedPools.Default<List<TextSpan>>().ClearAndFree(editorVisibleSpansInOriginal); } } private IEnumerable<TextChange> FilterTextChanges(SourceText originalText, List<TextSpan> editorVisibleSpansInOriginal, IReadOnlyList<TextChange> changes) { // no visible spans or changes if (editorVisibleSpansInOriginal.Count == 0 || changes.Count == 0) { // return empty one yield break; } using (var pooledObject = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var changeQueue = pooledObject.Object; changeQueue.AddRange(changes); var spanIndex = 0; var changeIndex = 0; for (; spanIndex < editorVisibleSpansInOriginal.Count; spanIndex++) { var visibleSpan = editorVisibleSpansInOriginal[spanIndex]; var visibleTextSpan = GetVisibleTextSpan(originalText, visibleSpan, uptoFirstAndLastLine: true); for (; changeIndex < changeQueue.Count; changeIndex++) { var change = changeQueue[changeIndex]; // easy case first if (change.Span.End < visibleSpan.Start) { // move to next change continue; } if (visibleSpan.End < change.Span.Start) { // move to next visible span break; } // make sure we are not replacing whitespace around start and at the end of visible span if (WhitespaceOnEdges(originalText, visibleTextSpan, change)) { continue; } if (visibleSpan.Contains(change.Span)) { yield return change; continue; } // now it is complex case where things are intersecting each other var subChanges = GetSubTextChanges(originalText, change, visibleSpan).ToList(); if (subChanges.Count > 0) { if (subChanges.Count == 1 && subChanges[0] == change) { // we can't break it. not much we can do here. just don't touch and ignore this change continue; } changeQueue.InsertRange(changeIndex + 1, subChanges); continue; } } } } } private bool WhitespaceOnEdges(SourceText text, TextSpan visibleTextSpan, TextChange change) { if (!string.IsNullOrWhiteSpace(change.NewText)) { return false; } if (change.Span.End <= visibleTextSpan.Start) { return true; } if (visibleTextSpan.End <= change.Span.Start) { return true; } return false; } private IEnumerable<TextChange> GetSubTextChanges(SourceText originalText, TextChange changeInOriginalText, TextSpan visibleSpanInOriginalText) { using (var changes = SharedPools.Default<List<TextChange>>().GetPooledObject()) { var leftText = originalText.ToString(changeInOriginalText.Span); var rightText = changeInOriginalText.NewText; var offsetInOriginalText = changeInOriginalText.Span.Start; if (TryGetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText, changes.Object)) { return changes.Object.ToList(); } return GetSubTextChanges(originalText, visibleSpanInOriginalText, leftText, rightText, offsetInOriginalText); } } private bool TryGetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText, List<TextChange> changes) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spansInLeftText = leftPool.Object; var spansInRightText = rightPool.Object; if (TryGetWhitespaceOnlyChanges(leftText, rightText, spansInLeftText, spansInRightText)) { for (var i = 0; i < spansInLeftText.Count; i++) { var spanInLeftText = spansInLeftText[i]; var spanInRightText = spansInRightText[i]; if (spanInLeftText.IsEmpty && spanInRightText.IsEmpty) { continue; } var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText, out textChange)) { changes.Add(textChange); } } return true; } return false; } } private IEnumerable<TextChange> GetSubTextChanges( SourceText originalText, TextSpan visibleSpanInOriginalText, string leftText, string rightText, int offsetInOriginalText) { // these are expensive. but hopely, we don't hit this as much except the boundary cases. using (var leftPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) using (var rightPool = SharedPools.Default<List<ValueTuple<int, int>>>().GetPooledObject()) { var leftReplacementMap = leftPool.Object; var rightReplacementMap = rightPool.Object; string leftTextWithReplacement, rightTextWithReplacement; GetTextWithReplacements(leftText, rightText, leftReplacementMap, rightReplacementMap, out leftTextWithReplacement, out rightTextWithReplacement); var diffResult = DiffStrings(leftTextWithReplacement, rightTextWithReplacement); foreach (var difference in diffResult) { var spanInLeftText = AdjustSpan(diffResult.LeftDecomposition.GetSpanInOriginal(difference.Left), leftReplacementMap); var spanInRightText = AdjustSpan(diffResult.RightDecomposition.GetSpanInOriginal(difference.Right), rightReplacementMap); var spanInOriginalText = new TextSpan(offsetInOriginalText + spanInLeftText.Start, spanInLeftText.Length); TextChange textChange; if (TryGetSubTextChange(originalText, visibleSpanInOriginalText, rightText, spanInOriginalText, spanInRightText.ToTextSpan(), out textChange)) { yield return textChange; } } } } private bool TryGetWhitespaceOnlyChanges(string leftText, string rightText, List<TextSpan> spansInLeftText, List<TextSpan> spansInRightText) { return TryGetWhitespaceGroup(leftText, spansInLeftText) && TryGetWhitespaceGroup(rightText, spansInRightText) && spansInLeftText.Count == spansInRightText.Count; } private bool TryGetWhitespaceGroup(string text, List<TextSpan> groups) { if (text.Length == 0) { groups.Add(new TextSpan(0, 0)); return true; } var start = 0; for (var i = 0; i < text.Length; i++) { var ch = text[i]; switch (ch) { case ' ': if (!TextAt(text, i - 1, ' ')) { start = i; } break; case '\r': case '\n': if (i == 0) { groups.Add(TextSpan.FromBounds(0, 0)); } else if (TextAt(text, i - 1, ' ')) { groups.Add(TextSpan.FromBounds(start, i)); } else if (TextAt(text, i - 1, '\n')) { groups.Add(TextSpan.FromBounds(start, i)); } start = i + 1; break; default: return false; } } if (start <= text.Length) { groups.Add(TextSpan.FromBounds(start, text.Length)); } return true; } private bool TextAt(string text, int index, char ch) { if (index < 0 || text.Length <= index) { return false; } return text[index] == ch; } private bool TryGetSubTextChange( SourceText originalText, TextSpan visibleSpanInOriginalText, string rightText, TextSpan spanInOriginalText, TextSpan spanInRightText, out TextChange textChange) { textChange = default(TextChange); var visibleFirstLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.Start); var visibleLastLineInOriginalText = originalText.Lines.GetLineFromPosition(visibleSpanInOriginalText.End); // skip easy case // 1. things are out of visible span if (!visibleSpanInOriginalText.IntersectsWith(spanInOriginalText)) { return false; } // 2. there are no intersects var snippetInRightText = rightText.Substring(spanInRightText.Start, spanInRightText.Length); if (visibleSpanInOriginalText.Contains(spanInOriginalText) && visibleSpanInOriginalText.End != spanInOriginalText.End) { textChange = new TextChange(spanInOriginalText, snippetInRightText); return true; } // okay, more complex case. things are intersecting boundaries. var firstLineOfRightTextSnippet = snippetInRightText.GetFirstLineText(); var lastLineOfRightTextSnippet = snippetInRightText.GetLastLineText(); // there are 4 complex cases - these are all heuristic. not sure what better way I have. and the heristic is heavily based on // text differ's behavior. // 1. it is a single line if (visibleFirstLineInOriginalText.LineNumber == visibleLastLineInOriginalText.LineNumber) { // don't do anything return false; } // 2. replacement contains visible spans if (spanInOriginalText.Contains(visibleSpanInOriginalText)) { // header // don't do anything // body textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length, snippetInRightText.Length - firstLineOfRightTextSnippet.Length - lastLineOfRightTextSnippet.Length)); // footer // don't do anything return true; } // 3. replacement intersects with start if (spanInOriginalText.Start < visibleSpanInOriginalText.Start && visibleSpanInOriginalText.Start <= spanInOriginalText.End && spanInOriginalText.End < visibleSpanInOriginalText.End) { // header // don't do anything // body if (visibleFirstLineInOriginalText.EndIncludingLineBreak <= spanInOriginalText.End) { textChange = new TextChange( TextSpan.FromBounds(visibleFirstLineInOriginalText.EndIncludingLineBreak, spanInOriginalText.End), snippetInRightText.Substring(firstLineOfRightTextSnippet.Length)); return true; } return false; } // 4. replacement intersects with end if (visibleSpanInOriginalText.Start < spanInOriginalText.Start && spanInOriginalText.Start <= visibleSpanInOriginalText.End && visibleSpanInOriginalText.End <= spanInOriginalText.End) { // body if (spanInOriginalText.Start <= visibleLastLineInOriginalText.Start) { textChange = new TextChange( TextSpan.FromBounds(spanInOriginalText.Start, visibleLastLineInOriginalText.Start), snippetInRightText.Substring(0, snippetInRightText.Length - lastLineOfRightTextSnippet.Length)); return true; } // footer // don't do anything return false; } // if it got hit, then it means there is a missing case throw ExceptionUtilities.Unreachable; } private IHierarchicalDifferenceCollection DiffStrings(string leftTextWithReplacement, string rightTextWithReplacement) { var diffService = _differenceSelectorService.GetTextDifferencingService( _workspace.Services.GetLanguageServices(this.Project.Language).GetService<IContentTypeLanguageService>().GetDefaultContentType()); diffService = diffService ?? _differenceSelectorService.DefaultTextDifferencingService; return diffService.DiffStrings(leftTextWithReplacement, rightTextWithReplacement, s_venusEditOptions.DifferenceOptions); } private void GetTextWithReplacements( string leftText, string rightText, List<ValueTuple<int, int>> leftReplacementMap, List<ValueTuple<int, int>> rightReplacementMap, out string leftTextWithReplacement, out string rightTextWithReplacement) { // to make diff works better, we choose replacement strings that don't appear in both texts. var returnReplacement = GetReplacementStrings(leftText, rightText, ReturnReplacementString); var newLineReplacement = GetReplacementStrings(leftText, rightText, NewLineReplacementString); leftTextWithReplacement = GetTextWithReplacementMap(leftText, returnReplacement, newLineReplacement, leftReplacementMap); rightTextWithReplacement = GetTextWithReplacementMap(rightText, returnReplacement, newLineReplacement, rightReplacementMap); } private static string GetReplacementStrings(string leftText, string rightText, string initialReplacement) { if (leftText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(initialReplacement, StringComparison.Ordinal) < 0) { return initialReplacement; } // okay, there is already one in the given text. const string format = "{{|{0}|{1}|{0}|}}"; for (var i = 0; true; i++) { var replacement = string.Format(format, i.ToString(), initialReplacement); if (leftText.IndexOf(replacement, StringComparison.Ordinal) < 0 && rightText.IndexOf(replacement, StringComparison.Ordinal) < 0) { return replacement; } } } private string GetTextWithReplacementMap(string text, string returnReplacement, string newLineReplacement, List<ValueTuple<int, int>> replacementMap) { var delta = 0; var returnLength = returnReplacement.Length; var newLineLength = newLineReplacement.Length; var sb = StringBuilderPool.Allocate(); for (var i = 0; i < text.Length; i++) { var ch = text[i]; if (ch == '\r') { sb.Append(returnReplacement); delta += returnLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } else if (ch == '\n') { sb.Append(newLineReplacement); delta += newLineLength - 1; replacementMap.Add(ValueTuple.Create(i + delta, delta)); continue; } sb.Append(ch); } return StringBuilderPool.ReturnAndFree(sb); } private Span AdjustSpan(Span span, List<ValueTuple<int, int>> replacementMap) { var start = span.Start; var end = span.End; for (var i = 0; i < replacementMap.Count; i++) { var positionAndDelta = replacementMap[i]; if (positionAndDelta.Item1 <= span.Start) { start = span.Start - positionAndDelta.Item2; } if (positionAndDelta.Item1 <= span.End) { end = span.End - positionAndDelta.Item2; } if (positionAndDelta.Item1 > span.End) { break; } } return Span.FromBounds(start, end); } public IEnumerable<TextSpan> GetEditorVisibleSpans() { var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var projectionDataBuffer = _containedLanguage.DataBuffer as IProjectionBuffer; if (projectionDataBuffer != null) { return projectionDataBuffer.CurrentSnapshot .GetSourceSpans() .Where(ss => ss.Snapshot.TextBuffer == subjectBuffer) .Select(s => s.Span.ToTextSpan()) .OrderBy(s => s.Start); } else { return SpecializedCollections.EmptyEnumerable<TextSpan>(); } } private static void ApplyChanges( IProjectionBuffer subjectBuffer, IEnumerable<TextChange> changes, IList<TextSpan> visibleSpansInOriginal, out IEnumerable<int> affectedVisibleSpansInNew) { using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { var affectedSpans = SharedPools.Default<HashSet<int>>().AllocateAndClear(); affectedVisibleSpansInNew = affectedSpans; var currentVisibleSpanIndex = 0; foreach (var change in changes) { // Find the next visible span that either overlaps or intersects with while (currentVisibleSpanIndex < visibleSpansInOriginal.Count && visibleSpansInOriginal[currentVisibleSpanIndex].End < change.Span.Start) { currentVisibleSpanIndex++; } // no more place to apply text changes if (currentVisibleSpanIndex >= visibleSpansInOriginal.Count) { break; } var newText = change.NewText; var span = change.Span.ToSpan(); edit.Replace(span, newText); affectedSpans.Add(currentVisibleSpanIndex); } edit.Apply(); } } private void AdjustIndentation(IProjectionBuffer subjectBuffer, IEnumerable<int> visibleSpanIndex) { if (!visibleSpanIndex.Any()) { return; } var snapshot = subjectBuffer.CurrentSnapshot; var document = _workspace.CurrentSolution.GetDocument(this.Id); var originalText = document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); Contract.Requires(object.ReferenceEquals(originalText, snapshot.AsText())); var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var options = _workspace.Options .WithChangedOption(FormattingOptions.UseTabs, root.Language, !editorOptions.IsConvertTabsToSpacesEnabled()) .WithChangedOption(FormattingOptions.TabSize, root.Language, editorOptions.GetTabSize()) .WithChangedOption(FormattingOptions.IndentationSize, root.Language, editorOptions.GetIndentSize()); using (var pooledObject = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var spans = pooledObject.Object; spans.AddRange(this.GetEditorVisibleSpans()); using (var edit = subjectBuffer.CreateEdit(s_venusEditOptions, reiteratedVersionNumber: null, editTag: null)) { foreach (var spanIndex in visibleSpanIndex) { var rule = GetBaseIndentationRule(root, originalText, spans, spanIndex); var visibleSpan = spans[spanIndex]; AdjustIndentationForSpan(document, edit, visibleSpan, rule, options); } edit.Apply(); } } } private void AdjustIndentationForSpan( Document document, ITextEdit edit, TextSpan visibleSpan, IFormattingRule baseIndentationRule, OptionSet options) { var root = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); using (var rulePool = SharedPools.Default<List<IFormattingRule>>().GetPooledObject()) using (var spanPool = SharedPools.Default<List<TextSpan>>().GetPooledObject()) { var venusFormattingRules = rulePool.Object; var visibleSpans = spanPool.Object; venusFormattingRules.Add(baseIndentationRule); venusFormattingRules.Add(ContainedDocumentPreserveFormattingRule.Instance); var formattingRules = venusFormattingRules.Concat(Formatter.GetDefaultFormattingRules(document)); var workspace = document.Project.Solution.Workspace; var changes = Formatter.GetFormattedTextChanges( root, new TextSpan[] { CommonFormattingHelpers.GetFormattingSpan(root, visibleSpan) }, workspace, options, formattingRules, CancellationToken.None); visibleSpans.Add(visibleSpan); var newChanges = FilterTextChanges(document.GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None), visibleSpans, changes.ToReadOnlyCollection()).Where(t => visibleSpan.Contains(t.Span)); foreach (var change in newChanges) { edit.Replace(change.Span.ToSpan(), change.NewText); } } } public BaseIndentationFormattingRule GetBaseIndentationRule(SyntaxNode root, SourceText text, List<TextSpan> spans, int spanIndex) { if (_hostType == HostType.Razor) { var currentSpanIndex = spanIndex; TextSpan visibleSpan; TextSpan visibleTextSpan; GetVisibleAndTextSpan(text, spans, currentSpanIndex, out visibleSpan, out visibleTextSpan); var end = visibleSpan.End; var current = root.FindToken(visibleTextSpan.Start).Parent; while (current != null) { if (current.Span.Start == visibleTextSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Explicit) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } } if (current.Span.Start < visibleSpan.Start) { var blockType = GetRazorCodeBlockType(visibleSpan.Start); if (blockType == RazorCodeBlockType.Block || blockType == RazorCodeBlockType.Helper) { var baseIndentation = GetBaseIndentation(root, text, visibleSpan); return new BaseIndentationFormattingRule(root, TextSpan.FromBounds(visibleSpan.Start, end), baseIndentation, _vbHelperFormattingRule); } if (currentSpanIndex == 0) { break; } GetVisibleAndTextSpan(text, spans, --currentSpanIndex, out visibleSpan, out visibleTextSpan); continue; } current = current.Parent; } } var span = spans[spanIndex]; var indentation = GetBaseIndentation(root, text, span); return new BaseIndentationFormattingRule(root, span, indentation, _vbHelperFormattingRule); } private void GetVisibleAndTextSpan(SourceText text, List<TextSpan> spans, int spanIndex, out TextSpan visibleSpan, out TextSpan visibleTextSpan) { visibleSpan = spans[spanIndex]; visibleTextSpan = GetVisibleTextSpan(text, visibleSpan); if (visibleTextSpan.IsEmpty) { // span has no text in them visibleTextSpan = visibleSpan; } } private int GetBaseIndentation(SyntaxNode root, SourceText text, TextSpan span) { // Is this right? We should probably get this from the IVsContainedLanguageHost instead. var editorOptionsFactory = _componentModel.GetService<IEditorOptionsFactoryService>(); var editorOptions = editorOptionsFactory.GetOptions(_containedLanguage.DataBuffer); var additionalIndentation = GetAdditionalIndentation(root, text, span); string baseIndentationString; int parent, indentSize, useTabs = 0, tabSize = 0; // Skip over the first line, since it's in "Venus space" anyway. var startingLine = text.Lines.GetLineFromPosition(span.Start); for (var line = startingLine; line.Start < span.End; line = text.Lines[line.LineNumber + 1]) { Marshal.ThrowExceptionForHR( this.ContainedLanguage.ContainedLanguageHost.GetLineIndent( line.LineNumber, out baseIndentationString, out parent, out indentSize, out useTabs, out tabSize)); if (!string.IsNullOrEmpty(baseIndentationString)) { return baseIndentationString.GetColumnFromLineOffset(baseIndentationString.Length, editorOptions.GetTabSize()) + additionalIndentation; } } return additionalIndentation; } private TextSpan GetVisibleTextSpan(SourceText text, TextSpan visibleSpan, bool uptoFirstAndLastLine = false) { var start = visibleSpan.Start; for (; start < visibleSpan.End; start++) { if (!char.IsWhiteSpace(text[start])) { break; } } var end = visibleSpan.End - 1; if (start <= end) { for (; start <= end; end--) { if (!char.IsWhiteSpace(text[end])) { break; } } } if (uptoFirstAndLastLine) { var firstLine = text.Lines.GetLineFromPosition(visibleSpan.Start); var lastLine = text.Lines.GetLineFromPosition(visibleSpan.End); if (firstLine.LineNumber < lastLine.LineNumber) { start = (start < firstLine.End) ? start : firstLine.End; end = (lastLine.Start < end + 1) ? end : lastLine.Start - 1; } } return (start <= end) ? TextSpan.FromBounds(start, end + 1) : default(TextSpan); } private int GetAdditionalIndentation(SyntaxNode root, SourceText text, TextSpan span) { if (_hostType == HostType.HTML) { return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } if (_hostType == HostType.Razor) { var type = GetRazorCodeBlockType(span.Start); // razor block if (type == RazorCodeBlockType.Block) { // more workaround for csharp razor case. when } for csharp razor code block is just typed, "}" exist // in both subject and surface buffer and there is no easy way to figure out who owns } just typed. // in this case, we let razor owns it. later razor will remove } from subject buffer if it is something // razor owns. if (this.Project.Language == LanguageNames.CSharp) { var textSpan = GetVisibleTextSpan(text, span); var end = textSpan.End - 1; if (end >= 0 && text[end] == '}') { var token = root.FindToken(end); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.Start == end && syntaxFact != null) { SyntaxToken openBrace; if (syntaxFact.TryGetCorrespondingOpenBrace(token, out openBrace) && !textSpan.Contains(openBrace.Span)) { return 0; } } } } // same as C#, but different text is in the buffer if (this.Project.Language == LanguageNames.VisualBasic) { var textSpan = GetVisibleTextSpan(text, span); var subjectSnapshot = _containedLanguage.SubjectBuffer.CurrentSnapshot; var end = textSpan.End - 1; if (end >= 0) { var ch = subjectSnapshot[end]; if (CheckCode(subjectSnapshot, textSpan.End, ch, VBRazorBlock, checkAt: false) || CheckCode(subjectSnapshot, textSpan.End, ch, FunctionsRazor, checkAt: false)) { var token = root.FindToken(end, findInsideTrivia: true); var syntaxFact = _workspace.Services.GetLanguageServices(Project.Language).GetService<ISyntaxFactsService>(); if (token.Span.End == textSpan.End && syntaxFact != null) { if (syntaxFact.IsSkippedTokensTrivia(token.Parent)) { return 0; } } } } } return _optionService.GetOption(FormattingOptions.IndentationSize, this.Project.Language); } } return 0; } private RazorCodeBlockType GetRazorCodeBlockType(int position) { Debug.Assert(_hostType == HostType.Razor); var subjectBuffer = (IProjectionBuffer)this.GetOpenTextBuffer(); var subjectSnapshot = subjectBuffer.CurrentSnapshot; var surfaceSnapshot = ((IProjectionBuffer)_containedLanguage.DataBuffer).CurrentSnapshot; var surfacePoint = surfaceSnapshot.MapFromSourceSnapshot(new SnapshotPoint(subjectSnapshot, position), PositionAffinity.Predecessor); if (!surfacePoint.HasValue) { // how this can happen? return RazorCodeBlockType.Implicit; } var ch = char.ToLower(surfaceSnapshot[Math.Max(surfacePoint.Value - 1, 0)]); // razor block if (IsCodeBlock(surfaceSnapshot, surfacePoint.Value, ch)) { return RazorCodeBlockType.Block; } if (ch == RazorExplicit) { return RazorCodeBlockType.Explicit; } if (CheckCode(surfaceSnapshot, surfacePoint.Value, HelperRazor)) { return RazorCodeBlockType.Helper; } return RazorCodeBlockType.Implicit; } private bool IsCodeBlock(ITextSnapshot surfaceSnapshot, int position, char ch) { if (this.Project.Language == LanguageNames.CSharp) { return CheckCode(surfaceSnapshot, position, ch, CSharpRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor, CSharpRazorBlock); } if (this.Project.Language == LanguageNames.VisualBasic) { return CheckCode(surfaceSnapshot, position, ch, VBRazorBlock) || CheckCode(surfaceSnapshot, position, ch, FunctionsRazor); } return false; } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag, bool checkAt = true) { if (ch != tag[tag.Length - 1] || position < tag.Length) { return false; } var start = position - tag.Length; var razorTag = snapshot.GetText(start, tag.Length); return string.Equals(razorTag, tag, StringComparison.OrdinalIgnoreCase) && (!checkAt || snapshot[start - 1] == RazorExplicit); } private bool CheckCode(ITextSnapshot snapshot, int position, string tag) { int i = position - 1; if (i < 0) { return false; } for (; i >= 0; i--) { if (!char.IsWhiteSpace(snapshot[i])) { break; } } var ch = snapshot[i]; position = i + 1; return CheckCode(snapshot, position, ch, tag); } private bool CheckCode(ITextSnapshot snapshot, int position, char ch, string tag1, string tag2) { if (!CheckCode(snapshot, position, ch, tag2, checkAt: false)) { return false; } return CheckCode(snapshot, position - tag2.Length, tag1); } public ITextUndoHistory GetTextUndoHistory() { // In Venus scenarios, the undo history is associated with the data buffer return _componentModel.GetService<ITextUndoHistoryRegistry>().GetHistory(_containedLanguage.DataBuffer); } public uint GetItemId() { AssertIsForeground(); if (_itemMoniker == null) { return (uint)VSConstants.VSITEMID.Nil; } uint itemId; Project.Hierarchy.ParseCanonicalName(_itemMoniker, out itemId); return itemId; } private enum RazorCodeBlockType { Block, Explicit, Implicit, Helper } private enum HostType { HTML, Razor, XOML } } }
// --------------------------------------------------------------------------- // <copyright file="MeetingRequestSchema.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the MeetingRequestSchema class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System.Diagnostics.CodeAnalysis; /// <summary> /// Represents the schema for meeting requests. /// </summary> [Schema] public class MeetingRequestSchema : MeetingMessageSchema { /// <summary> /// Field URIs for MeetingRequest. /// </summary> private static class FieldUris { public const string MeetingRequestType = "meetingRequest:MeetingRequestType"; public const string IntendedFreeBusyStatus = "meetingRequest:IntendedFreeBusyStatus"; public const string ChangeHighlights = "meetingRequest:ChangeHighlights"; } /// <summary> /// Defines the MeetingRequestType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingRequestType = new GenericPropertyDefinition<MeetingRequestType>( XmlElementNames.MeetingRequestType, FieldUris.MeetingRequestType, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the IntendedFreeBusyStatus property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IntendedFreeBusyStatus = new GenericPropertyDefinition<LegacyFreeBusyStatus>( XmlElementNames.IntendedFreeBusyStatus, FieldUris.IntendedFreeBusyStatus, PropertyDefinitionFlags.CanFind, ExchangeVersion.Exchange2007_SP1); /// <summary> /// Defines the ChangeHighlights property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ChangeHighlights = new ComplexPropertyDefinition<ChangeHighlights>( XmlElementNames.ChangeHighlights, FieldUris.ChangeHighlights, ExchangeVersion.Exchange2013, delegate() { return new ChangeHighlights(); }); /// <summary> /// Enhanced Location property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EnhancedLocation = AppointmentSchema.EnhancedLocation; /// <summary> /// Defines the Start property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Start = AppointmentSchema.Start; /// <summary> /// Defines the End property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition End = AppointmentSchema.End; /// <summary> /// Defines the OriginalStart property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition OriginalStart = AppointmentSchema.OriginalStart; /// <summary> /// Defines the IsAllDayEvent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsAllDayEvent = AppointmentSchema.IsAllDayEvent; /// <summary> /// Defines the LegacyFreeBusyStatus property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LegacyFreeBusyStatus = AppointmentSchema.LegacyFreeBusyStatus; /// <summary> /// Defines the Location property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Location = AppointmentSchema.Location; /// <summary> /// Defines the When property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition When = AppointmentSchema.When; /// <summary> /// Defines the IsMeeting property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsMeeting = AppointmentSchema.IsMeeting; /// <summary> /// Defines the IsCancelled property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsCancelled = AppointmentSchema.IsCancelled; /// <summary> /// Defines the IsRecurring property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsRecurring = AppointmentSchema.IsRecurring; /// <summary> /// Defines the MeetingRequestWasSent property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingRequestWasSent = AppointmentSchema.MeetingRequestWasSent; /// <summary> /// Defines the AppointmentType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentType = AppointmentSchema.AppointmentType; /// <summary> /// Defines the MyResponseType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MyResponseType = AppointmentSchema.MyResponseType; /// <summary> /// Defines the Organizer property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Organizer = AppointmentSchema.Organizer; /// <summary> /// Defines the RequiredAttendees property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition RequiredAttendees = AppointmentSchema.RequiredAttendees; /// <summary> /// Defines the OptionalAttendees property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition OptionalAttendees = AppointmentSchema.OptionalAttendees; /// <summary> /// Defines the Resources property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Resources = AppointmentSchema.Resources; /// <summary> /// Defines the ConflictingMeetingCount property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConflictingMeetingCount = AppointmentSchema.ConflictingMeetingCount; /// <summary> /// Defines the AdjacentMeetingCount property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AdjacentMeetingCount = AppointmentSchema.AdjacentMeetingCount; /// <summary> /// Defines the ConflictingMeetings property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConflictingMeetings = AppointmentSchema.ConflictingMeetings; /// <summary> /// Defines the AdjacentMeetings property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AdjacentMeetings = AppointmentSchema.AdjacentMeetings; /// <summary> /// Defines the Duration property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Duration = AppointmentSchema.Duration; /// <summary> /// Defines the TimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition TimeZone = AppointmentSchema.TimeZone; /// <summary> /// Defines the AppointmentReplyTime property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentReplyTime = AppointmentSchema.AppointmentReplyTime; /// <summary> /// Defines the AppointmentSequenceNumber property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentSequenceNumber = AppointmentSchema.AppointmentSequenceNumber; /// <summary> /// Defines the AppointmentState property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AppointmentState = AppointmentSchema.AppointmentState; /// <summary> /// Defines the Recurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition Recurrence = AppointmentSchema.Recurrence; /// <summary> /// Defines the FirstOccurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition FirstOccurrence = AppointmentSchema.FirstOccurrence; /// <summary> /// Defines the LastOccurrence property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition LastOccurrence = AppointmentSchema.LastOccurrence; /// <summary> /// Defines the ModifiedOccurrences property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ModifiedOccurrences = AppointmentSchema.ModifiedOccurrences; /// <summary> /// Defines the DeletedOccurrences property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition DeletedOccurrences = AppointmentSchema.DeletedOccurrences; /// <summary> /// Defines the MeetingTimeZone property. /// </summary> internal static readonly PropertyDefinition MeetingTimeZone = AppointmentSchema.MeetingTimeZone; /// <summary> /// Defines the StartTimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition StartTimeZone = AppointmentSchema.StartTimeZone; /// <summary> /// Defines the EndTimeZone property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition EndTimeZone = AppointmentSchema.EndTimeZone; /// <summary> /// Defines the ConferenceType property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition ConferenceType = AppointmentSchema.ConferenceType; /// <summary> /// Defines the AllowNewTimeProposal property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition AllowNewTimeProposal = AppointmentSchema.AllowNewTimeProposal; /// <summary> /// Defines the IsOnlineMeeting property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition IsOnlineMeeting = AppointmentSchema.IsOnlineMeeting; /// <summary> /// Defines the MeetingWorkspaceUrl property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition MeetingWorkspaceUrl = AppointmentSchema.MeetingWorkspaceUrl; /// <summary> /// Defines the NetShowUrl property. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "Immutable type")] public static readonly PropertyDefinition NetShowUrl = AppointmentSchema.NetShowUrl; // This must be after the declaration of property definitions internal static new readonly MeetingRequestSchema Instance = new MeetingRequestSchema(); /// <summary> /// Registers properties. /// </summary> /// <remarks> /// IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the same order as they are defined in types.xsd) /// </remarks> internal override void RegisterProperties() { base.RegisterProperties(); this.RegisterProperty(MeetingRequestType); this.RegisterProperty(IntendedFreeBusyStatus); this.RegisterProperty(ChangeHighlights); this.RegisterProperty(Start); this.RegisterProperty(End); this.RegisterProperty(OriginalStart); this.RegisterProperty(IsAllDayEvent); this.RegisterProperty(LegacyFreeBusyStatus); this.RegisterProperty(Location); this.RegisterProperty(When); this.RegisterProperty(IsMeeting); this.RegisterProperty(IsCancelled); this.RegisterProperty(IsRecurring); this.RegisterProperty(MeetingRequestWasSent); this.RegisterProperty(AppointmentType); this.RegisterProperty(MyResponseType); this.RegisterProperty(Organizer); this.RegisterProperty(RequiredAttendees); this.RegisterProperty(OptionalAttendees); this.RegisterProperty(Resources); this.RegisterProperty(ConflictingMeetingCount); this.RegisterProperty(AdjacentMeetingCount); this.RegisterProperty(ConflictingMeetings); this.RegisterProperty(AdjacentMeetings); this.RegisterProperty(Duration); this.RegisterProperty(TimeZone); this.RegisterProperty(AppointmentReplyTime); this.RegisterProperty(AppointmentSequenceNumber); this.RegisterProperty(AppointmentState); this.RegisterProperty(Recurrence); this.RegisterProperty(FirstOccurrence); this.RegisterProperty(LastOccurrence); this.RegisterProperty(ModifiedOccurrences); this.RegisterProperty(DeletedOccurrences); this.RegisterInternalProperty(MeetingTimeZone); this.RegisterProperty(StartTimeZone); this.RegisterProperty(EndTimeZone); this.RegisterProperty(ConferenceType); this.RegisterProperty(AllowNewTimeProposal); this.RegisterProperty(IsOnlineMeeting); this.RegisterProperty(MeetingWorkspaceUrl); this.RegisterProperty(NetShowUrl); this.RegisterProperty(EnhancedLocation); } /// <summary> /// Initializes a new instance of the <see cref="MeetingRequestSchema"/> class. /// </summary> internal MeetingRequestSchema() : base() { } } }
using System; using System.Collections.Generic; using EncompassRest.Loans.Enums; namespace EncompassRest.Loans.RateLocks { /// <summary> /// LoanInformation /// </summary> public sealed partial class LoanInformation : DirtyExtensibleObject { private DirtyValue<List<LockRequestBorrower>?>? _lockRequestBorrowers; private DirtyValue<string?>? _planCode; private DirtyValue<string?>? _loanDocumentationType; private DirtyValue<string?>? _borrowerMinimumFico; private DirtyValue<string?>? _coBorrowerMinimumFico; private DirtyValue<string?>? _creditScoreToUse; private DirtyValue<bool?>? _isFirstTimeHomeBuyer; private DirtyValue<bool?>? _canDemonstrateTwelveMonthMortgageRentalHistory; private DirtyValue<SubjectProperty?>? _subjectProperty; private DirtyValue<StringEnumValue<LoanPurposeType>>? _loanPurposeType; private DirtyValue<bool?>? _currentAcquisition; private DirtyValue<bool?>? _currentConstructionRefinance; private DirtyValue<bool?>? _loanFor203K; private DirtyValue<decimal?>? _totalForLesserOfSumAsIs; private DirtyValue<string?>? _lienPriorityType; private DirtyValue<StringEnumValue<LoanType>>? _mortgageType; private DirtyValue<StringEnumValue<AmortizationType>>? _loanAmortizationType; private DirtyValue<decimal?>? _gpmRate; private DirtyValue<int?>? _gpmYears; private DirtyValue<string?>? _fnmProductPlanIdentifier; private DirtyValue<string?>? _otherAmortizationTypeDescription; private DirtyValue<string?>? _requestImpoundWaived; private DirtyValue<StringEnumValue<ImpoundType>>? _requestImpoundType; private DirtyValue<bool?>? _prepayPenalty; private DirtyValue<int?>? _penaltyTerm; private DirtyValue<bool?>? _noClosingCost; private DirtyValue<bool?>? _lenderFeeWaiver; private DirtyValue<DateTime?>? _estimatedClosingDate; private DirtyValue<decimal?>? _sellerPaidMiPremium; private DirtyValue<decimal?>? _fhaUpfrontMiPremiumPercent; private DirtyValue<decimal?>? _fundingAmount; private DirtyValue<decimal?>? _ltv; private DirtyValue<decimal?>? _combinedLtv; private DirtyValue<decimal?>? _mipPaidInCash; private DirtyValue<bool?>? _roundToNearestFifty; private DirtyValue<int?>? _balloonLoanMaturityTerms; private DirtyValue<int?>? _loanAmortizationTerms; private DirtyValue<decimal?>? _baseLoanAmount; private DirtyValue<decimal?>? _borrowerRequestedLoanAmount; private DirtyValue<decimal?>? _helocActualBalance; private DirtyValue<decimal?>? _firstSubordinateAmount; private DirtyValue<decimal?>? _secondSubordinateAmount; private DirtyValue<decimal?>? _otherSubordinateAmount; private DirtyValue<bool?>? _lockField; private DirtyValue<decimal?>? _totalSubordinateFinancing; private DirtyValue<DateTime?>? _pricingUpdated; private DirtyValue<StringEnumValue<ImpoundType>>? _impoundType; private DirtyValue<StringEnumValue<ImpoundWaived>>? _impoundWaived; private DirtyValue<bool?>? _isLenderPaidMortgageInsurance; private DirtyValue<string?>? _pricingHistoryData; /// <summary> /// Object containing the borrowers' information. /// </summary> public List<LockRequestBorrower>? LockRequestBorrowers { get => _lockRequestBorrowers; set => SetField(ref _lockRequestBorrowers, value); } /// <summary> /// The plan code associated with the lock request. /// </summary> public string? PlanCode { get => _planCode; set => SetField(ref _planCode, value); } /// <summary> /// Fannie Mae loan documentation type code. /// </summary> public string? LoanDocumentationType { get => _loanDocumentationType; set => SetField(ref _loanDocumentationType, value); } /// <summary> /// The minimum FICO score allowed for the borrower to qualify for the loan program. /// </summary> public string? BorrowerMinimumFico { get => _borrowerMinimumFico; set => SetField(ref _borrowerMinimumFico, value); } /// <summary> /// The minimum FICO score allowed for the co-borrower to qualify for the loan program. /// </summary> public string? CoBorrowerMinimumFico { get => _coBorrowerMinimumFico; set => SetField(ref _coBorrowerMinimumFico, value); } /// <summary> /// The credit score to use when qualifying the loan for a loan product. Depending on the loan product and the scores of the applicants, the credit score may come from the borrower, co-borrower, or even co-mortgagors. /// </summary> public string? CreditScoreToUse { get => _creditScoreToUse; set => SetField(ref _creditScoreToUse, value); } /// <summary> /// Indicates whether the borrower is a first time home buyer. /// </summary> public bool? IsFirstTimeHomeBuyer { get => _isFirstTimeHomeBuyer; set => SetField(ref _isFirstTimeHomeBuyer, value); } /// <summary> /// Indicates whether the borrower can demonstrate twelve months mortgage rental history. /// </summary> public bool? CanDemonstrateTwelveMonthMortgageRentalHistory { get => _canDemonstrateTwelveMonthMortgageRentalHistory; set => SetField(ref _canDemonstrateTwelveMonthMortgageRentalHistory, value); } /// <summary> /// Attributes that define the subject property. /// </summary> public SubjectProperty? SubjectProperty { get => _subjectProperty; set => SetField(ref _subjectProperty, value); } /// <summary> /// Loan Purpose Type. Possible values are: construction-perm, no cash-out refi, purchase, construction, cash-out refi, other /// </summary> public StringEnumValue<LoanPurposeType> LoanPurposeType { get => _loanPurposeType; set => SetField(ref _loanPurposeType, value); } /// <summary> /// Indicates whether the loan is a current Acquisition. /// </summary> public bool? CurrentAcquisition { get => _currentAcquisition; set => SetField(ref _currentAcquisition, value); } /// <summary> /// Indicates whether the loan is a current Construction Refinance. /// </summary> public bool? CurrentConstructionRefinance { get => _currentConstructionRefinance; set => SetField(ref _currentConstructionRefinance, value); } /// <summary> /// Indicates whether the loan is for a 203K. /// </summary> public bool? LoanFor203K { get => _loanFor203K; set => SetField(ref _loanFor203K, value); } /// <summary> /// Total for lesser of sum as is. /// </summary> public decimal? TotalForLesserOfSumAsIs { get => _totalForLesserOfSumAsIs; set => SetField(ref _totalForLesserOfSumAsIs, value); } /// <summary> /// Lien priority type. /// </summary> public string? LienPriorityType { get => _lienPriorityType; set => SetField(ref _lienPriorityType, value); } /// <summary> /// Mortgage type. Possible values are: Conventional, VA, FHA, USDA-RHS, Other, HELOC /// </summary> public StringEnumValue<LoanType>? MortgageType { get => _mortgageType; set => SetField(ref _mortgageType, value); } /// <summary> /// Loan Amortization Type. Possible values are fixed rate, gpm-rate, arm, other /// </summary> public StringEnumValue<AmortizationType> LoanAmortizationType { get => _loanAmortizationType; set => SetField(ref _loanAmortizationType, value); } /// <summary> /// GPM rate. A mortgage in which the payments are lower in the first years, and then increase annually until a level that fully amortizes the loan within its term. /// </summary> public decimal? GpmRate { get => _gpmRate; set => SetField(ref _gpmRate, value); } /// <summary> /// GPM years. The number of years the rate (as defined by the GPM attribute) is in effect before the loan is reamortized. /// </summary> public int? GpmYears { get => _gpmYears; set => SetField(ref _gpmYears, value); } /// <summary> /// FNM Product Plan Identifier. /// </summary> public string? FnmProductPlanIdentifier { get => _fnmProductPlanIdentifier; set => SetField(ref _fnmProductPlanIdentifier, value); } /// <summary> /// Description if the amortization type is set to Other. /// </summary> public string? OtherAmortizationTypeDescription { get => _otherAmortizationTypeDescription; set => SetField(ref _otherAmortizationTypeDescription, value); } /// <summary> /// Request Impound Waived indicator. /// </summary> public string? RequestImpoundWaived { get => _requestImpoundWaived; set => SetField(ref _requestImpoundWaived, value); } /// <summary> /// Request Impound Type. Possible values are: Taxes and Insurance, taxes only, insurance only, no impounds /// </summary> public StringEnumValue<ImpoundType> RequestImpoundType { get => _requestImpoundType; set => SetField(ref _requestImpoundType, value); } /// <summary> /// Indicates whether the Penalty is prepaid. /// </summary> public bool? PrepayPenalty { get => _prepayPenalty; set => SetField(ref _prepayPenalty, value); } /// <summary> /// Term of the penalty in months. /// </summary> public int? PenaltyTerm { get => _penaltyTerm; set => SetField(ref _penaltyTerm, value); } /// <summary> /// Indicates whether there is a closing cost. /// </summary> public bool? NoClosingCost { get => _noClosingCost; set => SetField(ref _noClosingCost, value); } /// <summary> /// Indicates whether there is a lender fee waiver. /// </summary> public bool? LenderFeeWaiver { get => _lenderFeeWaiver; set => SetField(ref _lenderFeeWaiver, value); } /// <summary> /// Estimated closing date of the loan. /// </summary> public DateTime? EstimatedClosingDate { get => _estimatedClosingDate; set => SetField(ref _estimatedClosingDate, value); } /// <summary> /// Seller paid MI premium. /// </summary> public decimal? SellerPaidMiPremium { get => _sellerPaidMiPremium; set => SetField(ref _sellerPaidMiPremium, value); } /// <summary> /// FHA upfront MI premium percentage /// </summary> public decimal? FhaUpfrontMiPremiumPercent { get => _fhaUpfrontMiPremiumPercent; set => SetField(ref _fhaUpfrontMiPremiumPercent, value); } /// <summary> /// Funding amount. /// </summary> public decimal? FundingAmount { get => _fundingAmount; set => SetField(ref _fundingAmount, value); } /// <summary> /// The Loan-to-Value (LTV) ratio used for the lock request. /// </summary> public decimal? Ltv { get => _ltv; set => SetField(ref _ltv, value); } /// <summary> /// The combined Loan-to-Value (CLTV) ratio used for the lock request. /// </summary> public decimal? CombinedLtv { get => _combinedLtv; set => SetField(ref _combinedLtv, value); } /// <summary> /// The Amount Paid in Cash or the MIP/Funding amount. /// </summary> public decimal? MipPaidInCash { get => _mipPaidInCash; set => SetField(ref _mipPaidInCash, value); } /// <summary> /// Round the Total Loan Amount to the nearest $50 increment. /// </summary> public bool? RoundToNearestFifty { get => _roundToNearestFifty; set => SetField(ref _roundToNearestFifty, value); } /// <summary> /// Balloon loan maturity terms. /// </summary> public int? BalloonLoanMaturityTerms { get => _balloonLoanMaturityTerms; set => SetField(ref _balloonLoanMaturityTerms, value); } /// <summary> /// Loan amortization terms. /// </summary> public int? LoanAmortizationTerms { get => _loanAmortizationTerms; set => SetField(ref _loanAmortizationTerms, value); } /// <summary> /// Base loan amount. /// </summary> public decimal? BaseLoanAmount { get => _baseLoanAmount; set => SetField(ref _baseLoanAmount, value); } /// <summary> /// Borrower requested loan amount. /// </summary> public decimal? BorrowerRequestedLoanAmount { get => _borrowerRequestedLoanAmount; set => SetField(ref _borrowerRequestedLoanAmount, value); } /// <summary> /// HELOC actual balance. /// </summary> public decimal? HelocActualBalance { get => _helocActualBalance; set => SetField(ref _helocActualBalance, value); } /// <summary> /// First subordinate amount. /// </summary> public decimal? FirstSubordinateAmount { get => _firstSubordinateAmount; set => SetField(ref _firstSubordinateAmount, value); } /// <summary> /// Second subordinate amount. /// </summary> public decimal? SecondSubordinateAmount { get => _secondSubordinateAmount; set => SetField(ref _secondSubordinateAmount, value); } /// <summary> /// Other subordinate amount. /// </summary> public decimal? OtherSubordinateAmount { get => _otherSubordinateAmount; set => SetField(ref _otherSubordinateAmount, value); } /// <summary> /// Lock field. /// </summary> public bool? LockField { get => _lockField; set => SetField(ref _lockField, value); } /// <summary> /// Total subordinate financing. /// </summary> public decimal? TotalSubordinateFinancing { get => _totalSubordinateFinancing; set => SetField(ref _totalSubordinateFinancing, value); } /// <summary> /// The last date and time that pricing was imported. /// </summary> public DateTime? PricingUpdated { get => _pricingUpdated; set => SetField(ref _pricingUpdated, value); } /// <summary> /// Impound type. Possible options are: Taxes and Insurance(T and I), Taxes only(T), Insurance only(I), No impounds\ /// </summary> public StringEnumValue<ImpoundType> ImpoundType { get => _impoundType; set => SetField(ref _impoundType, value); } /// <summary> /// Whether the impound is waived or not waived. /// </summary> public StringEnumValue<ImpoundWaived> ImpoundWaived { get => _impoundWaived; set => SetField(ref _impoundWaived, value); } /// <summary> /// Indicates whether the lender has paid MI. /// </summary> public bool? IsLenderPaidMortgageInsurance { get => _isLenderPaidMortgageInsurance; set => SetField(ref _isLenderPaidMortgageInsurance, value); } /// <summary> /// Pricing history data. /// </summary> public string? PricingHistoryData { get => _pricingHistoryData; set => SetField(ref _pricingHistoryData, value); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Threading; namespace UltimateFracturing { public static partial class Fracturer { private class FracturingStats { public FracturingStats() { nChunkCount = 0; nTotalChunks = 0; nSplitCount = 0; bCancelFracturing = false; } public int nChunkCount; public int nTotalChunks; public int nSplitCount; public bool bCancelFracturing; } private class VoronoiCell { public class Face { public Face(Plane plane, Matrix4x4 mtxPlane, int nAdjacentCell) { this.plane = plane; this.mtxPlane = mtxPlane; this.nAdjacentCell = nAdjacentCell; } public Plane plane; public Matrix4x4 mtxPlane; public int nAdjacentCell; } public VoronoiCell(int nIndex, int x, int y, int z) { this.nIndex = nIndex; this.x = x; this.y = y; this.z = z; v3Center = Vector3.zero; listCellFaces = new List<Face>(); } public int nIndex; public int x; public int y; public int z; public Vector3 v3Center; public Vector3 v3Min; public Vector3 v3Max; public List<Face> listCellFaces; } private class VoronoiPointDistance { public VoronoiPointDistance(int nIndex, float fDistanceSqr) { this.nIndex = nIndex; this.fDistanceSqr = fDistanceSqr; } public class IncreasingDistanceComparer : IComparer<VoronoiPointDistance> { public int Compare(VoronoiPointDistance a, VoronoiPointDistance b) { return a.fDistanceSqr - b.fDistanceSqr < 0.0f ? -1 : 1; } } public int nIndex; public float fDistanceSqr; } public struct VoronoiCellKey { public int x; public int y; public int z; public VoronoiCellKey(int x, int y, int z) { this.x = x; this.y = y; this.z = z; } public class EqualityComparer : IEqualityComparer<VoronoiCellKey> { public bool Equals(VoronoiCellKey x, VoronoiCellKey y) { if(x.x == y.x && x.y == y.y && x.z == y.z) { return true; } return false; } public int GetHashCode(VoronoiCellKey x) { return x.x.GetHashCode() + x.y.GetHashCode() + x.z.GetHashCode(); } } } private class VoronoiThreadData { public VoronoiThreadData() { listVoronoiCells = new List<VoronoiCell>(); listMeshDatasChunks = new List<MeshData>(); } public List<VoronoiCell> listVoronoiCells; public MeshData meshDataCube; public List<MeshData> listMeshDatasObject; public List<MeshData> listMeshDatasChunks; public SpaceTreeNode spaceTree; public FracturedObject fracturedComponent; public int nCurrentCell; public int nTotalCells; public int nCellsProcessed; public ProgressDelegate progress; } private static FracturingStats s_FracturingStats = new FracturingStats(); private static VoronoiThreadData s_VoronoiThreadData = new VoronoiThreadData(); public delegate void ProgressDelegate(string strTitle, string message, float fT); public static void CancelFracturing() { lock(s_FracturingStats) { s_FracturingStats.bCancelFracturing = true; } } public static bool IsFracturingCancelled() { bool bCancelled = false; lock(s_FracturingStats) { bCancelled = s_FracturingStats.bCancelFracturing; } return bCancelled; } public static bool FractureToChunks(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); bool bFracturingOK = false; GameObject gameObjectIn = fracturedComponent.SourceObject; MeshFilter meshfIn = null; Mesh newMesh = null; if(gameObjectIn) { meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn) { newMesh = CopyMesh(meshfIn); newMesh.name = string.Format("mesh_{0}{1}", fracturedComponent.SourceObject.gameObject.name, fracturedComponent.SourceObject.gameObject.GetInstanceID().ToString()); //Debug.Log("In: " + gameObjectIn.name + " (Layer " + LayerMask.LayerToName(gameObjectIn.layer) + " " + gameObjectIn.layer + ")" + ": " + meshfIn.sharedMesh.subMeshCount + " submesh(es), " + ": " + (meshfIn.sharedMesh.triangles.Length / 3) + " triangles, " + meshfIn.sharedMesh.vertexCount + " vertices, " + (meshfIn.sharedMesh.normals != null ? meshfIn.sharedMesh.normals.Length : 0) + " normals, " + (meshfIn.sharedMesh.tangents != null ? meshfIn.sharedMesh.tangents.Length : 0) + " tangents, " + (meshfIn.sharedMesh.colors != null ? meshfIn.sharedMesh.colors.Length : 0) + " colors, " + (meshfIn.sharedMesh.colors32 != null ? meshfIn.sharedMesh.colors32.Length : 0) + " colors32, " + (meshfIn.sharedMesh.uv != null ? meshfIn.sharedMesh.uv.Length : 0) + " uv1, " + (meshfIn.sharedMesh.uv2 != null ? meshfIn.sharedMesh.uv2.Length : 0) + " uv2"); } } if(fracturedComponent.FracturePattern == FracturedObject.EFracturePattern.BSP) { bFracturingOK = FractureToChunksBSP(fracturedComponent, bPositionOnSourceAndHideOriginal, out listGameObjectsOut, progress); } else if(fracturedComponent.FracturePattern == FracturedObject.EFracturePattern.Voronoi) { bFracturingOK = FractureToChunksVoronoi(fracturedComponent, bPositionOnSourceAndHideOriginal, out listGameObjectsOut, progress); } if(fracturedComponent.SingleMeshObject != null) { GameObject.DestroyImmediate(fracturedComponent.SingleMeshObject); } if(bFracturingOK && Fracturer.IsFracturingCancelled() == false) { fracturedComponent.OnCreateFracturedObject(); fracturedComponent.SingleMeshObject = GameObject.Instantiate(fracturedComponent.SourceObject) as GameObject; fracturedComponent.SingleMeshObject.name = "@" + fracturedComponent.name + " (single mesh)"; fracturedComponent.SingleMeshObject.transform.localPosition = fracturedComponent.transform.position; fracturedComponent.SingleMeshObject.transform.localRotation = fracturedComponent.transform.rotation; fracturedComponent.SingleMeshObject.transform.localScale = fracturedComponent.SourceObject.transform.localScale; fracturedComponent.SingleMeshObject.transform.parent = fracturedComponent.transform; Component[] aComponents = fracturedComponent.SingleMeshObject.GetComponents<Component>(); for(int i = 0; i < aComponents.Length; i++) { Component c = aComponents[i]; if(c.GetType() != typeof(Transform) && c.GetType() != typeof(MeshRenderer) && c.GetType() != typeof(MeshFilter)) { Component.DestroyImmediate(c); } } MeshFilter singleMeshFilter = fracturedComponent.SingleMeshObject.GetComponent<MeshFilter>(); singleMeshFilter.sharedMesh = newMesh; #if UNITY_3_5 fracturedComponent.SingleMeshObject.SetActiveRecursively(true); #else fracturedComponent.SingleMeshObject.SetActive(true); #endif /* #if UNITY_EDITOR && !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) UnityEditor.Undo.RegisterCreatedObjectUndo(fracturedComponent.SingleMeshObject, "Created " + fracturedComponent.SingleMeshObject.name); foreach(GameObject chunk in listGameObjectsOut) { UnityEditor.Undo.RegisterCreatedObjectUndo(chunk, "Created " + chunk.name); } #endif */ } return bFracturingOK; } private static Mesh CopyMesh(MeshFilter meshfIn) { Mesh newMesh = new Mesh(); Vector3[] av3Vertices = meshfIn.sharedMesh.vertices; Vector3[] av3Normals = meshfIn.sharedMesh.normals; Vector4[] av4Tangents = meshfIn.sharedMesh.tangents; Vector2[] av2Mapping1 = meshfIn.sharedMesh.uv; Vector2[] av2Mapping2 = meshfIn.sharedMesh.uv2; Color[] acolColors = meshfIn.sharedMesh.colors; Color32[] aColors32 = meshfIn.sharedMesh.colors32; if(av3Vertices != null) { if(av3Vertices.Length > 0) { Vector3[] av3NewVertices = new Vector3[av3Vertices.Length]; av3Vertices.CopyTo(av3NewVertices, 0); newMesh.vertices = av3NewVertices; } } if(av3Normals != null) { if(av3Normals.Length > 0) { Vector3[] av3NewNormals = new Vector3[av3Normals.Length]; av3Normals.CopyTo(av3NewNormals, 0); newMesh.normals = av3NewNormals; } } if(av4Tangents != null) { if(av4Tangents.Length > 0) { Vector4[] av4NewTangents = new Vector4[av4Tangents.Length]; av4Tangents.CopyTo(av4NewTangents, 0); newMesh.tangents = av4NewTangents; } } if(av2Mapping1 != null) { if(av2Mapping1.Length > 0) { Vector2[] av2NewMapping1 = new Vector2[av2Mapping1.Length]; av2Mapping1.CopyTo(av2NewMapping1, 0); newMesh.uv = av2NewMapping1; } } if(av2Mapping2 != null) { if(av2Mapping2.Length > 0) { Vector2[] av2NewMapping2 = new Vector2[av2Mapping2.Length]; av2Mapping2.CopyTo(av2NewMapping2, 0); newMesh.uv2 = av2NewMapping2; } } if(acolColors != null) { if(acolColors.Length > 0) { Color[] acolNewColors = new Color[acolColors.Length]; acolColors.CopyTo(acolNewColors, 0); newMesh.colors = acolNewColors; } } if(aColors32 != null) { if(aColors32.Length > 0) { Color32[] aNewColors32 = new Color32[aColors32.Length]; aColors32.CopyTo(aNewColors32, 0); newMesh.colors32 = aNewColors32; } } newMesh.subMeshCount = meshfIn.sharedMesh.subMeshCount; for(int nSubMesh = 0; nSubMesh < meshfIn.sharedMesh.subMeshCount; nSubMesh++) { int[] anTriangles = meshfIn.sharedMesh.GetTriangles(nSubMesh); int[] anNewTriangles = new int[anTriangles.Length]; anTriangles.CopyTo(anNewTriangles, 0); newMesh.SetTriangles(anNewTriangles, nSubMesh); } return newMesh; } private static bool FractureToChunksBSP(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); MeshFilter meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn == null) { return false; } s_FracturingStats = new FracturingStats(); s_FracturingStats.nTotalChunks = fracturedComponent.GenerateNumChunks; if(progress != null) { progress("Fracturing", "Initializing...", 0.0f); } foreach(FracturedChunk chunk in fracturedComponent.ListFracturedChunks) { if(chunk != null) { UnityEngine.Object.DestroyImmediate(chunk.gameObject); } } fracturedComponent.ListFracturedChunks.Clear(); fracturedComponent.DecomposeRadius = (meshfIn.sharedMesh.bounds.max - meshfIn.sharedMesh.bounds.min).magnitude; Random.seed = fracturedComponent.RandomSeed; // Check if the input object already has been split, to get its split closing submesh FracturedChunk fracturedChunk = fracturedComponent.gameObject.GetComponent<FracturedChunk>(); int nSplitCloseSubMesh = fracturedChunk != null ? fracturedChunk.SplitSubMeshIndex : -1; if(nSplitCloseSubMesh == -1 && fracturedComponent.SourceObject.GetComponent<Renderer>()) { // Check if its material is the same as the split material if(fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterial == fracturedComponent.SplitMaterial) { nSplitCloseSubMesh = 0; } } SplitOptions splitOptions = SplitOptions.Default; splitOptions.bVerticesAreLocal = false; Vector3 v3OriginalPos = fracturedComponent.transform.position; Quaternion qOriginalRot = fracturedComponent.transform.rotation; // We'll do the splitting in (0, 0, 0) in order to improve precision Vector3 v3OriginalSourcePos = fracturedComponent.SourceObject.transform.position; fracturedComponent.SourceObject.transform.position = Vector3.zero; fracturedComponent.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.transform.rotation = fracturedComponent.SourceObject.transform.rotation; Material[] aMaterials = fracturedComponent.SourceObject.GetComponent<Renderer>() ? fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterials : null; MeshData meshDataIn = new MeshData(meshfIn.transform, meshfIn.sharedMesh, aMaterials, fracturedComponent.SourceObject.transform.localToWorldMatrix, true, nSplitCloseSubMesh, true); // Fracture the object Queue<MeshData> queueMeshDatas = new Queue<MeshData>(); // For depth order traversal, we are targeting a number of generated chunks Queue<int> queueLevels = new Queue<int>(); // Here we store the depth level of each meshData if(fracturedComponent.GenerateIslands) { CombinedMesh combinedMesh = fracturedComponent.SourceObject.GetComponent<CombinedMesh>(); if(combinedMesh != null) { // Does the mesh come from an combined mesh? -> separate objects and detect mesh islands combinedMesh.TransformObjInfoMeshVectorsToLocal(fracturedComponent.SourceObject.transform.transform); List<MeshData> listMeshDatasCombined = new List<MeshData>(); for(int nObject = 0; nObject < combinedMesh.GetObjectCount(); nObject++) { CombinedMesh.ObjectInfo objectMeshInfo = combinedMesh.GetObjectInfo(nObject); MeshData compositeObjectMesh = new MeshData(meshfIn.transform, objectMeshInfo.mesh, objectMeshInfo.aMaterials, fracturedComponent.transform.localToWorldMatrix * objectMeshInfo.mtxLocal, true, -1, true); List<MeshData> listIslands = ComputeMeshDataIslands(compositeObjectMesh, false, fracturedComponent, progress); foreach(MeshData island in listIslands) { queueMeshDatas.Enqueue(island); queueLevels.Enqueue(0); listMeshDatasCombined.Add(island); } } if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listMeshDatasCombined.Count; i++) { if(progress != null) { progress("Fracturing", "Processing combined object chunks connectivity...", i / (float)listMeshDatasCombined.Count); if(Fracturer.IsFracturingCancelled()) return false; } for(int j = 0; j < listMeshDatasCombined.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, false, listMeshDatasCombined[i], listMeshDatasCombined[j]); } } } } } else { List<MeshData> listIslands = ComputeMeshDataIslands(meshDataIn, false, fracturedComponent, progress); foreach(MeshData island in listIslands) { queueMeshDatas.Enqueue(island); queueLevels.Enqueue(0); } } } else { queueMeshDatas.Enqueue(meshDataIn); queueLevels.Enqueue(0); } s_FracturingStats.nChunkCount = 1; bool bEqualSize = fracturedComponent.GenerateIslands; // Generate chunks equally sized no matter the size of the islands detected while(queueMeshDatas.Count < s_FracturingStats.nTotalChunks) { if(IsFracturingCancelled()) { break; } MeshData meshDataCurrent = queueMeshDatas.Dequeue(); int nDepthCurrent = queueLevels.Dequeue(); if(progress != null) { progress("Fracturing", string.Format("Computing chunk {0}/{1} (Depth {2})", s_FracturingStats.nChunkCount + 1, s_FracturingStats.nTotalChunks, bEqualSize ? ": size ordered traversal" : nDepthCurrent.ToString()), Mathf.Clamp01((float)s_FracturingStats.nChunkCount / (float)s_FracturingStats.nTotalChunks)); } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; int nSplitAxis = -1; Matrix4x4 planeMtx = GetRandomPlaneSplitMatrix(meshDataCurrent, fracturedComponent, out nSplitAxis); if(SplitMeshUsingPlane(meshDataCurrent, fracturedComponent, splitOptions, planeMtx.MultiplyVector(Vector3.up), planeMtx.MultiplyVector(Vector3.right), planeMtx.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, progress) == true) { s_FracturingStats.nSplitCount++; foreach(MeshData meshDataPos in listMeshDataPos) queueMeshDatas.Enqueue(meshDataPos); queueLevels.Enqueue(nDepthCurrent + 1); foreach(MeshData meshDataNeg in listMeshDataNeg) queueMeshDatas.Enqueue(meshDataNeg); queueLevels.Enqueue(nDepthCurrent + 1); } if(bEqualSize) { // If we want to have equally sized objects mainly because of small islands preprocessing detection, then order the results by size for the next iterations List<MeshData> listSizeOrderedMeshDatas = new List<MeshData>(); while(queueMeshDatas.Count > 0) { listSizeOrderedMeshDatas.Add(queueMeshDatas.Dequeue()); } listSizeOrderedMeshDatas.Sort(new MeshData.DecreasingSizeComparer(nSplitAxis)); foreach(MeshData meshDataOrdered in listSizeOrderedMeshDatas) { queueMeshDatas.Enqueue(meshDataOrdered); } } s_FracturingStats.nChunkCount = queueMeshDatas.Count; } MeshData[] aMeshDataOut = queueMeshDatas.ToArray(); // Set the mesh properties and add objects to list if(IsFracturingCancelled() == false) { for(int nMeshCount = 0; nMeshCount < aMeshDataOut.Length; nMeshCount++) { // Create new game object GameObject newGameObject = CreateNewSplitGameObject(fracturedComponent.SourceObject, fracturedComponent, fracturedComponent.SourceObject.name + (nMeshCount + 1), true, aMeshDataOut[nMeshCount]); newGameObject.AddComponent<Rigidbody>(); newGameObject.GetComponent<Rigidbody>().isKinematic = true; listGameObjectsOut.Add(newGameObject); } if(fracturedComponent.GenerateChunkConnectionInfo) { ComputeChunkConnections(fracturedComponent, listGameObjectsOut, new List<MeshData>(aMeshDataOut), progress); } fracturedComponent.ComputeChunksRelativeVolume(); fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); fracturedComponent.ComputeSupportPlaneIntersections(); } // Compute the colliders if necessary if(fracturedComponent.AlwaysComputeColliders) { ComputeChunkColliders(fracturedComponent, progress); } bool bCancelled = IsFracturingCancelled(); // Reposition and hide original? fracturedComponent.SourceObject.transform.position = v3OriginalSourcePos; if(bPositionOnSourceAndHideOriginal) { fracturedComponent.gameObject.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.gameObject.transform.rotation = fracturedComponent.SourceObject.transform.rotation; #if UNITY_3_5 fracturedComponent.SourceObject.SetActiveRecursively(false); #else fracturedComponent.SourceObject.SetActive(false); #endif } else { fracturedComponent.transform.position = v3OriginalPos; fracturedComponent.transform.rotation = qOriginalRot; } return bCancelled == false; } private static bool FractureToChunksVoronoi(FracturedObject fracturedComponent, bool bPositionOnSourceAndHideOriginal, out List<GameObject> listGameObjectsOut, ProgressDelegate progress = null) { listGameObjectsOut = new List<GameObject>(); MeshFilter meshfIn = fracturedComponent.SourceObject.GetComponent<MeshFilter>(); if(meshfIn == null) { return false; } int nTotalCellsX = Mathf.Max(1, fracturedComponent.VoronoiCellsXCount); int nTotalCellsY = Mathf.Max(1, fracturedComponent.VoronoiCellsYCount); int nTotalCellsZ = Mathf.Max(1, fracturedComponent.VoronoiCellsZCount); s_FracturingStats = new FracturingStats(); int nTotalCells = nTotalCellsX * nTotalCellsY * nTotalCellsZ; s_VoronoiThreadData = new VoronoiThreadData(); if(progress != null) { progress("Fracturing", "Initializing...", 0.0f); } foreach(FracturedChunk chunk in fracturedComponent.ListFracturedChunks) { if(chunk != null) { UnityEngine.Object.DestroyImmediate(chunk.gameObject); } } fracturedComponent.ListFracturedChunks.Clear(); fracturedComponent.DecomposeRadius = (meshfIn.sharedMesh.bounds.max - meshfIn.sharedMesh.bounds.min).magnitude; Random.seed = fracturedComponent.RandomSeed; // Check if the input object already has been split, to get its split closing submesh FracturedChunk fracturedChunk = fracturedComponent.gameObject.GetComponent<FracturedChunk>(); int nSplitCloseSubMesh = fracturedChunk != null ? fracturedChunk.SplitSubMeshIndex : -1; if(nSplitCloseSubMesh == -1 && fracturedComponent.SourceObject.GetComponent<Renderer>()) { // Check if its material is the same as the split material if(fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterial == fracturedComponent.SplitMaterial) { nSplitCloseSubMesh = 0; } } // Mesh data will be in local coordinates Material[] aMaterials = fracturedComponent.SourceObject.GetComponent<Renderer>() ? fracturedComponent.SourceObject.GetComponent<Renderer>().sharedMaterials : null; MeshData meshDataIn = new MeshData(meshfIn.transform, meshfIn.sharedMesh, aMaterials, fracturedComponent.SourceObject.transform.localToWorldMatrix, false, nSplitCloseSubMesh, true); // Precompute space volumes with mesh datas for each volume to speed up cell generation SpaceTreeNode spaceTree = fracturedComponent.VoronoiVolumeOptimization ? SpaceTreeNode.BuildSpaceTree(meshDataIn, 8, fracturedComponent, progress) : null; // Create the cells and planes List<VoronoiCell> listVoronoiCells = new List<VoronoiCell>(); Dictionary<VoronoiCellKey, VoronoiCell> dicPos2Cell = new Dictionary<VoronoiCellKey,VoronoiCell>(); VoronoiCellKey cellKey = new VoronoiCellKey(); float fMinX = meshDataIn.v3Min.x; float fMinY = meshDataIn.v3Min.y; float fMinZ = meshDataIn.v3Min.z; float fMaxX = meshDataIn.v3Max.x; float fMaxY = meshDataIn.v3Max.y; float fMaxZ = meshDataIn.v3Max.z; float fSizeX = (fMaxX - fMinX) / nTotalCellsX; float fSizeY = (fMaxY - fMinY) / nTotalCellsY; float fSizeZ = (fMaxZ - fMinZ) / nTotalCellsZ; // We assume cells in this radius will affect the cell in the center int nCellInfluenceRadius = fracturedComponent.VoronoiProximityOptimization ? 2 : 20; for(int nCellX = 0; nCellX < nTotalCellsX; nCellX++) { for(int nCellY = 0; nCellY < nTotalCellsY; nCellY++) { for(int nCellZ = 0; nCellZ < nTotalCellsZ; nCellZ++) { float fCenterX = fMinX + (fSizeX * 0.5f) + (fSizeX * nCellX); float fCenterY = fMinY + (fSizeY * 0.5f) + (fSizeY * nCellY); float fCenterZ = fMinZ + (fSizeZ * 0.5f) + (fSizeZ * nCellZ); fCenterX += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeX * 0.5f * 0.99f * fracturedComponent.VoronoiCellsXSizeVariation; fCenterY += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeY * 0.5f * 0.99f * fracturedComponent.VoronoiCellsYSizeVariation; fCenterZ += UnityEngine.Random.Range(-1.0f, 1.0f) * fSizeZ * 0.5f * 0.99f * fracturedComponent.VoronoiCellsZSizeVariation; VoronoiCell newCell = new VoronoiCell(listVoronoiCells.Count, nCellX, nCellY, nCellZ); newCell.v3Center = new Vector3(fCenterX, fCenterY, fCenterZ); // We'll compute the v3Min and v3Max later, but this are rough values. float fRoughInfluenceRadius = nCellInfluenceRadius + (nCellInfluenceRadius * 0.5f) + 0.01f; newCell.v3Min = newCell.v3Center - new Vector3(fSizeX * fRoughInfluenceRadius, fSizeY * fRoughInfluenceRadius, fSizeZ * fRoughInfluenceRadius); newCell.v3Max = newCell.v3Center + new Vector3(fSizeX * fRoughInfluenceRadius, fSizeY * fRoughInfluenceRadius, fSizeZ * fRoughInfluenceRadius); listVoronoiCells.Add(newCell); dicPos2Cell.Add(new VoronoiCellKey(nCellX, nCellY, nCellZ), newCell); } } } List<VoronoiPointDistance> listPointDistances = new List<VoronoiPointDistance>(); for(int nCell = 0; nCell < listVoronoiCells.Count; nCell++) { if(progress != null) { progress("Fracturing", string.Format("Creating cell planes... (cell {0}/{1}) ", nCell + 1, listVoronoiCells.Count), (float)nCell / (float)listVoronoiCells.Count); } if(IsFracturingCancelled()) { break; } Vector3 v3CellCenter = listVoronoiCells[nCell].v3Center; listPointDistances.Clear(); listPointDistances.Capacity = Mathf.RoundToInt(Mathf.Pow(nCellInfluenceRadius * 2 + 1, 3)) + 1; // Build separation planes for(int x = -nCellInfluenceRadius; x <= nCellInfluenceRadius; x++) { for(int y = -nCellInfluenceRadius; y <= nCellInfluenceRadius; y++) { for(int z = -nCellInfluenceRadius; z <= nCellInfluenceRadius; z++) { if(x == 0 && y == 0 && z == 0) { continue; } int nCellX = listVoronoiCells[nCell].x + x; int nCellY = listVoronoiCells[nCell].y + y; int nCellZ = listVoronoiCells[nCell].z + z; if(nCellX < 0 || nCellX >= nTotalCellsX) continue; if(nCellY < 0 || nCellY >= nTotalCellsY) continue; if(nCellZ < 0 || nCellZ >= nTotalCellsZ) continue; cellKey.x = nCellX; cellKey.y = nCellY; cellKey.z = nCellZ; VoronoiCell otherCell = dicPos2Cell[cellKey]; listPointDistances.Add(new VoronoiPointDistance(otherCell.nIndex, (v3CellCenter - otherCell.v3Center).sqrMagnitude)); } } } listPointDistances.Sort(new VoronoiPointDistance.IncreasingDistanceComparer()); foreach(VoronoiPointDistance pointDistance in listPointDistances) { int nCellSeparation = pointDistance.nIndex; Vector3 v3NewPlaneNormal = (v3CellCenter - listVoronoiCells[nCellSeparation].v3Center).normalized; Vector3 v3NewPlanePoint = (v3CellCenter + listVoronoiCells[nCellSeparation].v3Center) * 0.5f; Plane newCellPlane = new Plane(v3NewPlaneNormal, v3NewPlanePoint); Vector3 v3Forward = Vector3.forward; float fMagX = Mathf.Abs(v3NewPlaneNormal.x); float fMagY = Mathf.Abs(v3NewPlaneNormal.y); float fMagZ = Mathf.Abs(v3NewPlaneNormal.z); if(fMagX <= fMagY && fMagX <= fMagZ) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.right); if(fMagY <= fMagX && fMagY <= fMagZ) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.up); if(fMagZ <= fMagX && fMagZ <= fMagY) v3Forward = Vector3.Cross(v3NewPlaneNormal, Vector3.forward); Quaternion qPlaneRot = Quaternion.LookRotation(v3Forward, v3NewPlaneNormal); Matrix4x4 mtxPlane = Matrix4x4.TRS(-v3NewPlaneNormal * newCellPlane.distance, qPlaneRot, Vector3.one); listVoronoiCells[nCell].listCellFaces.Add(new VoronoiCell.Face(newCellPlane, mtxPlane, nCellSeparation)); } } // Fracture a dummy cube and see which planes affect each cell MeshData meshDataCube = MeshData.CreateBoxMeshData(Vector3.zero, Quaternion.identity, Vector3.one, meshDataIn.v3Min, meshDataIn.v3Max); Thread[] threads = fracturedComponent.VoronoiMultithreading ? new Thread[UnityEngine.SystemInfo.processorCount] : new Thread[1]; s_VoronoiThreadData.listVoronoiCells = listVoronoiCells; s_VoronoiThreadData.meshDataCube = meshDataCube; s_VoronoiThreadData.listMeshDatasObject = null; s_VoronoiThreadData.spaceTree = spaceTree; s_VoronoiThreadData.fracturedComponent = fracturedComponent; s_VoronoiThreadData.nCurrentCell = 0; s_VoronoiThreadData.nTotalCells = nTotalCells; s_VoronoiThreadData.nCellsProcessed = 0; s_VoronoiThreadData.progress = progress; for(int nThread = 0; nThread < threads.Length; nThread++) { threads[nThread] = new Thread(new ThreadStart(ThreadVoronoiComputePlaneDependencies)); threads[nThread].Start(); } int nLastCell = -1; // float fStartTime = Time.realtimeSinceStartup; while(true) { if(IsFracturingCancelled()) { break; } int nCurrentCell = 0; lock(typeof(VoronoiThreadData)) { nCurrentCell = s_VoronoiThreadData.nCurrentCell; } if(nCurrentCell != nLastCell) { if(s_VoronoiThreadData.progress != null) { s_VoronoiThreadData.progress("Fracturing", string.Format("Finding cell plane dependencies... (cell {0}/{1}) ", nCurrentCell + 1, nTotalCells), (float)nCurrentCell / (float)nTotalCells); } nLastCell = nCurrentCell; } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCellsProcessed == nTotalCells) { break; } } Thread.Sleep(0); } // float fEndTime = Time.realtimeSinceStartup; // Debug.Log("Multithread time (" + threads.Length + " threads) = " + (fEndTime - fStartTime) + " seconds"); // Fracture the object List<MeshData> listMeshDataOut = new List<MeshData>(); List<MeshData> listMeshDatasIn = new List<MeshData>(); if(IsFracturingCancelled() == false) { if(fracturedComponent.GenerateIslands) { CombinedMesh combinedMesh = fracturedComponent.SourceObject.GetComponent<CombinedMesh>(); if(combinedMesh != null) { // Does the mesh come from an combined mesh? -> separate objects and detect mesh islands combinedMesh.TransformObjInfoMeshVectorsToLocal(fracturedComponent.transform); for(int nObject = 0; nObject < combinedMesh.GetObjectCount(); nObject++) { CombinedMesh.ObjectInfo objectMeshInfo = combinedMesh.GetObjectInfo(nObject); MeshData compositeObjectMesh = new MeshData(meshfIn.transform, objectMeshInfo.mesh, objectMeshInfo.aMaterials, fracturedComponent.transform.localToWorldMatrix * objectMeshInfo.mtxLocal, true, -1, true); List<MeshData> listIslands = ComputeMeshDataIslands(compositeObjectMesh, true, fracturedComponent, progress); foreach(MeshData island in listIslands) { listMeshDatasIn.Add(island); } } if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listMeshDatasIn.Count; i++) { if(progress != null) { progress("Fracturing", "Processing combined object chunks connectivity...", i / (float)listMeshDatasIn.Count); if(Fracturer.IsFracturingCancelled()) return false; } for(int j = 0; j < listMeshDatasIn.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, true, listMeshDatasIn[i], listMeshDatasIn[j]); } } } } } else { listMeshDatasIn = ComputeMeshDataIslands(meshDataIn, true, fracturedComponent, progress); } } else { listMeshDatasIn.Add(meshDataIn); } if(listVoronoiCells.Count == 1) { listMeshDataOut.AddRange(listMeshDatasIn); } else { s_VoronoiThreadData.listMeshDatasObject = listMeshDatasIn; s_VoronoiThreadData.fracturedComponent = fracturedComponent; s_VoronoiThreadData.nCurrentCell = 0; s_VoronoiThreadData.nCellsProcessed = 0; for(int nThread = 0; nThread < threads.Length; nThread++) { threads[nThread] = new Thread(new ThreadStart(ThreadVoronoiComputeCells)); threads[nThread].Start(); } nLastCell = -1; // fStartTime = Time.realtimeSinceStartup; while(true) { if(IsFracturingCancelled()) { break; } int nCurrentCell = 0; lock(typeof(VoronoiThreadData)) { nCurrentCell = s_VoronoiThreadData.nCurrentCell; } //if(nCurrentCell != nLastCell) { if(s_VoronoiThreadData.progress != null) { s_VoronoiThreadData.progress("Fracturing", string.Format("Computing cell {0}/{1}", nCurrentCell, nTotalCells), Mathf.Clamp01((float)nCurrentCell / (float)nTotalCells)); } nLastCell = nCurrentCell; } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCellsProcessed == nTotalCells) { break; } } Thread.Sleep(0); } // fEndTime = Time.realtimeSinceStartup; // Debug.Log("Multithread time cells (" + threads.Length + " threads) = " + (fEndTime - fStartTime) + " seconds"); listMeshDataOut.AddRange(s_VoronoiThreadData.listMeshDatasChunks); } } // Set the mesh properties and add objects to list if(IsFracturingCancelled() == false) { if(fracturedComponent.Verbose) { Debug.Log(string.Format("Computed {0} slices for {1} chunks (Average: {2}).", s_FracturingStats.nSplitCount, listMeshDataOut.Count, (float)s_FracturingStats.nSplitCount / (float)listMeshDataOut.Count)); } if(listMeshDataOut.Count > 0) { for(int nMeshCount = 0; nMeshCount < listMeshDataOut.Count; nMeshCount++) { // Create new game object and have into account we need to transform from old local space to new chunk local space listMeshDataOut[nMeshCount].v3Position = Vector3.Scale(listMeshDataOut[nMeshCount].v3Position, meshfIn.transform.localScale); for(int v = 0; v < listMeshDataOut[nMeshCount].aVertexData.Length; v++) { Vector3 v3Vertex = listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex; v3Vertex = Vector3.Scale(v3Vertex, meshfIn.transform.localScale); v3Vertex -= listMeshDataOut[nMeshCount].v3Position; listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex = v3Vertex; } listMeshDataOut[nMeshCount].v3Position = fracturedComponent.transform.TransformPoint(listMeshDataOut[nMeshCount].v3Position); listMeshDataOut[nMeshCount].qRotation = fracturedComponent.transform.rotation; listMeshDataOut[nMeshCount].v3Scale = fracturedComponent.transform.localScale; GameObject newGameObject = CreateNewSplitGameObject(fracturedComponent.SourceObject, fracturedComponent, fracturedComponent.SourceObject.name + (nMeshCount + 1), false, listMeshDataOut[nMeshCount]); newGameObject.AddComponent<Rigidbody>(); newGameObject.GetComponent<Rigidbody>().isKinematic = true; listGameObjectsOut.Add(newGameObject); // Now that the gameobject has vertices in local coordinates, transform vertices from meshdatas to world space for connection computation later for(int v = 0; v < listMeshDataOut[nMeshCount].aVertexData.Length; v++) { Vector3 v3Vertex = listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex; v3Vertex = newGameObject.transform.TransformPoint(v3Vertex); listMeshDataOut[nMeshCount].aVertexData[v].v3Vertex = v3Vertex; } } } if(fracturedComponent.GenerateChunkConnectionInfo) { ComputeChunkConnections(fracturedComponent, listGameObjectsOut, listMeshDataOut, progress); } fracturedComponent.ComputeChunksRelativeVolume(); fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); fracturedComponent.ComputeSupportPlaneIntersections(); } // Compute the colliders if necessary if(fracturedComponent.AlwaysComputeColliders && IsFracturingCancelled() == false) { ComputeChunkColliders(fracturedComponent, progress); } bool bCancelled = IsFracturingCancelled(); // Reposition and hide original? if(bPositionOnSourceAndHideOriginal) { fracturedComponent.gameObject.transform.position = fracturedComponent.SourceObject.transform.position; fracturedComponent.gameObject.transform.rotation = fracturedComponent.SourceObject.transform.rotation; #if UNITY_3_5 fracturedComponent.SourceObject.SetActiveRecursively(false); #else fracturedComponent.SourceObject.SetActive(false); #endif } return bCancelled == false; } public static void ThreadVoronoiComputePlaneDependencies() { SplitOptions splitOptionsCube = new SplitOptions(); splitOptionsCube.bForceNoIslandGeneration = true; splitOptionsCube.bForceNoChunkConnectionInfo = true; splitOptionsCube.bForceNoIslandConnectionInfo = true; splitOptionsCube.bForceNoCap = false; splitOptionsCube.bForceCapVertexSoup = true; splitOptionsCube.bVerticesAreLocal = true; while(true) { int nCell; lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCurrentCell >= s_VoronoiThreadData.nTotalCells) { break; } nCell = s_VoronoiThreadData.nCurrentCell; s_VoronoiThreadData.nCurrentCell++; } if(IsFracturingCancelled()) { break; } if(s_VoronoiThreadData.spaceTree != null) { List<MeshData> volumeMeshDatas = SpaceTreeNode.GetSmallestPossibleMeshData(s_VoronoiThreadData.spaceTree, s_VoronoiThreadData.listVoronoiCells[nCell].v3Min, s_VoronoiThreadData.listVoronoiCells[nCell].v3Max); if(volumeMeshDatas.Count == 0) { s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Clear(); lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } continue; } } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; List<MeshData> listMeshDataCell = new List<MeshData>(); listMeshDataCell.Add(s_VoronoiThreadData.meshDataCube.GetDeepCopy()); for(int nFace = 0; nFace < s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Count; nFace++) { VoronoiCell.Face cellFace = s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace]; List<MeshData> listMeshDataIteration = new List<MeshData>(); bool bCutSomething = false; foreach(MeshData meshDataCell in listMeshDataCell) { if(SplitMeshUsingPlane(meshDataCell, s_VoronoiThreadData.fracturedComponent, splitOptionsCube, cellFace.mtxPlane.MultiplyVector(Vector3.up), cellFace.mtxPlane.MultiplyVector(Vector3.right), cellFace.mtxPlane.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, s_VoronoiThreadData.progress) == true) { listMeshDataIteration.AddRange(listMeshDataPos); if(listMeshDataNeg.Count > 0) { bCutSomething = true; } } } listMeshDataCell = listMeshDataIteration; if(bCutSomething == false) { // Didn't cut anything, remove this face s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.RemoveAt(nFace); nFace--; } if(listMeshDataCell.Count == 0) { // Empty cell s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Clear(); break; } } // Recompute cell bounding box min/max with all the cells that affect this one Vector3 v3Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); Vector3 v3Max = new Vector3(float.MinValue, float.MinValue, float.MinValue); foreach(MeshData meshDataCell in listMeshDataCell) { if(meshDataCell.v3Min.x < v3Min.x) v3Min.x = meshDataCell.v3Min.x; if(meshDataCell.v3Min.y < v3Min.y) v3Min.y = meshDataCell.v3Min.y; if(meshDataCell.v3Min.z < v3Min.z) v3Min.z = meshDataCell.v3Min.z; if(meshDataCell.v3Max.x > v3Max.x) v3Max.x = meshDataCell.v3Max.x; if(meshDataCell.v3Max.y > v3Max.y) v3Max.y = meshDataCell.v3Max.y; if(meshDataCell.v3Max.z > v3Max.z) v3Max.z = meshDataCell.v3Max.z; } s_VoronoiThreadData.listVoronoiCells[nCell].v3Min = v3Min; s_VoronoiThreadData.listVoronoiCells[nCell].v3Max = v3Max; lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } } } public static void ThreadVoronoiComputeCells() { SplitOptions splitOptionsMesh = new SplitOptions(); splitOptionsMesh.bForceNoProgressInfo = true; splitOptionsMesh.bVerticesAreLocal = true; splitOptionsMesh.bIgnoreNegativeSide = true; splitOptionsMesh.bForceNoIslandGeneration = true; while(true) { int nCell; lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.nCurrentCell >= s_VoronoiThreadData.nTotalCells) { break; } nCell = s_VoronoiThreadData.nCurrentCell; s_VoronoiThreadData.nCurrentCell++; } if(IsFracturingCancelled()) { break; } List<MeshData> listMeshDataPos; List<MeshData> listMeshDataNeg; List<MeshData> listMeshDataCell = new List<MeshData>(); foreach(MeshData meshData in s_VoronoiThreadData.listMeshDatasObject) { listMeshDataCell.Add(meshData); } if(s_VoronoiThreadData.spaceTree != null) { listMeshDataCell = SpaceTreeNode.GetSmallestPossibleMeshData(s_VoronoiThreadData.spaceTree, s_VoronoiThreadData.listVoronoiCells[nCell].v3Min, s_VoronoiThreadData.listVoronoiCells[nCell].v3Max); if(listMeshDataCell.Count == 0) { lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } continue; } } for(int nFace = 0; nFace < s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces.Count; nFace++) { VoronoiCell.Face cellFace = s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace]; List<MeshData> listMeshDataIteration = new List<MeshData>(); splitOptionsMesh.nForceMeshConnectivityHash = CreateMeshConnectivityVoronoiHash(nCell, s_VoronoiThreadData.listVoronoiCells[nCell].listCellFaces[nFace].nAdjacentCell); foreach(MeshData meshDataCell in listMeshDataCell) { if(SplitMeshUsingPlane(meshDataCell, s_VoronoiThreadData.fracturedComponent, splitOptionsMesh, cellFace.mtxPlane.MultiplyVector(Vector3.up), cellFace.mtxPlane.MultiplyVector(Vector3.right), cellFace.mtxPlane.MultiplyPoint3x4(Vector3.zero), out listMeshDataPos, out listMeshDataNeg, s_VoronoiThreadData.progress) == true) { lock(s_FracturingStats) { s_FracturingStats.nSplitCount++; } listMeshDataIteration.AddRange(listMeshDataPos); } } listMeshDataCell = listMeshDataIteration; if(listMeshDataCell.Count == 0) { break; } } lock(typeof(VoronoiThreadData)) { if(s_VoronoiThreadData.fracturedComponent.GenerateIslands) { // Should be only 0 or 1 elements in listMeshDataCell (we forced no island generation), but to be consistent with our implementation foreach(MeshData meshData in listMeshDataCell) { s_VoronoiThreadData.listMeshDatasChunks.AddRange(ComputeMeshDataIslands(meshData, splitOptionsMesh.bVerticesAreLocal, s_VoronoiThreadData.fracturedComponent, null)); } } else { s_VoronoiThreadData.listMeshDatasChunks.AddRange(listMeshDataCell); } } lock(typeof(VoronoiThreadData)) { s_VoronoiThreadData.nCellsProcessed++; } } } public static List<MeshData> ComputeMeshDataIslands(MeshData meshDataIn, bool bVerticesAreLocal, FracturedObject fracturedComponent, ProgressDelegate progress) { MeshFaceConnectivity faceConnectivity = new MeshFaceConnectivity(); MeshDataConnectivity meshConnectivity = new MeshDataConnectivity(); List<int>[] aListIndices = new List<int>[meshDataIn.aaIndices.Length]; List<VertexData> listVertexData = new List<VertexData>(); for(int nSubMesh = 0; nSubMesh < meshDataIn.nSubMeshCount; nSubMesh++) { aListIndices[nSubMesh] = new List<int>(); for(int i = 0; i < meshDataIn.aaIndices[nSubMesh].Length / 3; i++) { int nIndex1 = meshDataIn.aaIndices[nSubMesh][i * 3 + 0]; int nIndex2 = meshDataIn.aaIndices[nSubMesh][i * 3 + 1]; int nIndex3 = meshDataIn.aaIndices[nSubMesh][i * 3 + 2]; int nHashV1 = meshDataIn.aVertexData[nIndex1].nVertexHash; int nHashV2 = meshDataIn.aVertexData[nIndex2].nVertexHash; int nHashV3 = meshDataIn.aVertexData[nIndex3].nVertexHash; Vector3 v1 = meshDataIn.aVertexData[nIndex1].v3Vertex; Vector3 v2 = meshDataIn.aVertexData[nIndex2].v3Vertex; Vector3 v3 = meshDataIn.aVertexData[nIndex3].v3Vertex; aListIndices[nSubMesh].Add(nIndex1); aListIndices[nSubMesh].Add(nIndex2); aListIndices[nSubMesh].Add(nIndex3); if(fracturedComponent.GenerateChunkConnectionInfo) { meshConnectivity.NotifyNewClippedFace(meshDataIn, nSubMesh, i, nSubMesh, i); } faceConnectivity.AddEdge(nSubMesh, v1, v2, nHashV1, nHashV2, nIndex1, nIndex2); faceConnectivity.AddEdge(nSubMesh, v2, v3, nHashV2, nHashV3, nIndex2, nIndex3); faceConnectivity.AddEdge(nSubMesh, v3, v1, nHashV3, nHashV1, nIndex3, nIndex1); } } listVertexData.AddRange(meshDataIn.aVertexData); meshDataIn.meshDataConnectivity = meshConnectivity; List<MeshData> listIslands = MeshData.PostProcessConnectivity(meshDataIn, faceConnectivity, meshConnectivity, aListIndices, listVertexData, meshDataIn.nSplitCloseSubMesh, meshDataIn.nCurrentVertexHash, false); if(fracturedComponent.GenerateChunkConnectionInfo) { for(int i = 0; i < listIslands.Count; i++) { if(progress != null) { progress("Fracturing", "Processing initial island connectivity...", i / (float)listIslands.Count); if(Fracturer.IsFracturingCancelled()) return new List<MeshData>(); } for(int j = 0; j < listIslands.Count; j++) { if(i != j) { ComputeIslandsMeshDataConnectivity(fracturedComponent, bVerticesAreLocal, listIslands[i], listIslands[j]); } } } } return listIslands; } public static void ComputeChunkColliders(FracturedObject fracturedComponent, ProgressDelegate progress) { int nChunk = 0; int nTotalFaces = 0; s_FracturingStats = new FracturingStats(); foreach(FracturedChunk fracturedChunk in fracturedComponent.ListFracturedChunks) { if(IsFracturingCancelled()) { break; } if(progress != null) { progress("Computing colliders", string.Format("Collider {0}/{1}", nChunk + 1, fracturedComponent.ListFracturedChunks.Count), (float)nChunk / (float)fracturedComponent.ListFracturedChunks.Count); } if(fracturedChunk == null) { continue; } if(fracturedChunk.GetComponent<Collider>() != null) { MeshCollider meshCollider = fracturedChunk.GetComponent<MeshCollider>(); if(meshCollider) { meshCollider.sharedMesh = null; } if(fracturedChunk.GetComponent<Collider>()) { Object.DestroyImmediate(fracturedChunk.GetComponent<Collider>()); } } if(fracturedChunk.GetComponent<Rigidbody>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Rigidbody>()); } while(fracturedChunk.transform.childCount > 0) { // Destroy concave collider hulls Object.DestroyImmediate(fracturedChunk.transform.GetChild(0).gameObject); } fracturedChunk.HasConcaveCollider = false; bool bColliderCreated = false; RemoveEmptySubmeshes(fracturedChunk); if(fracturedChunk.Volume > fracturedComponent.MinColliderVolumeForBox) { if(fracturedComponent.IntegrateWithConcaveCollider) { int nTriangles = UltimateFracturing.ConcaveColliderInterface.ComputeHull(fracturedChunk.gameObject, fracturedComponent); if(nTriangles > 0) { fracturedChunk.HasConcaveCollider = true; bColliderCreated = true; nTotalFaces += nTriangles; } } else { MeshFilter meshFilter = fracturedChunk.GetComponent<MeshFilter>(); if(meshFilter != null && meshFilter.sharedMesh != null && meshFilter.sharedMesh.vertexCount >= 3) { fracturedChunk.HasConcaveCollider = false; MeshCollider newCollider = fracturedChunk.gameObject.AddComponent<MeshCollider>(); newCollider.convex = true; bColliderCreated = true; if(newCollider.sharedMesh) { nTotalFaces += newCollider.sharedMesh.triangles.Length / 3; } } } } if(bColliderCreated == false) { fracturedChunk.gameObject.AddComponent<BoxCollider>(); nTotalFaces += 12; } if(fracturedChunk.GetComponent<Collider>()) { fracturedChunk.GetComponent<Collider>().material = fracturedComponent.ChunkPhysicMaterial; } fracturedChunk.gameObject.AddComponent<Rigidbody>(); fracturedChunk.GetComponent<Rigidbody>().isKinematic = true; nChunk++; } if(IsFracturingCancelled() == false) { fracturedComponent.ComputeChunksMass(fracturedComponent.TotalMass); } if(fracturedComponent.Verbose && fracturedComponent.ListFracturedChunks.Count > 0) { Debug.Log("Total collider triangles: " + nTotalFaces + ". Average = " + (nTotalFaces / fracturedComponent.ListFracturedChunks.Count)); } } public static void DeleteChunkColliders(FracturedObject fracturedComponent) { foreach(FracturedChunk fracturedChunk in fracturedComponent.ListFracturedChunks) { while(fracturedChunk.transform.childCount > 0) { // Destroy concave collider hulls Object.DestroyImmediate(fracturedChunk.transform.GetChild(0).gameObject); } if(fracturedChunk.GetComponent<Collider>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Collider>()); } if(fracturedChunk.GetComponent<Rigidbody>() != null) { Object.DestroyImmediate(fracturedChunk.GetComponent<Rigidbody>()); } } } private static Matrix4x4 GetRandomPlaneSplitMatrix(MeshData meshDataIn, FracturedObject fracturedComponent, out int nSplitAxisPerformed) { Vector3 v3RandomPosition = Vector3.zero; Quaternion qPlane = Quaternion.identity; Vector3 v3Min = meshDataIn.v3Min - meshDataIn.v3Position; Vector3 v3Max = meshDataIn.v3Max - meshDataIn.v3Position; if(fracturedComponent.SplitsWorldSpace == false) { // Compute min/max values in local space :( v3Min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue); v3Max = new Vector3(float.MinValue, float.MinValue, float.MinValue); Matrix4x4 mtxTransformVertices = Matrix4x4.TRS(meshDataIn.v3Position, meshDataIn.qRotation, meshDataIn.v3Scale).inverse; for(int i = 0; i < meshDataIn.aVertexData.Length; i++) { Vector3 v3Local = mtxTransformVertices.MultiplyPoint3x4(meshDataIn.aVertexData[i].v3Vertex); if(v3Local.x < v3Min.x) v3Min.x = v3Local.x; if(v3Local.y < v3Min.y) v3Min.y = v3Local.y; if(v3Local.z < v3Min.z) v3Min.z = v3Local.z; if(v3Local.x > v3Max.x) v3Max.x = v3Local.x; if(v3Local.y > v3Max.y) v3Max.y = v3Local.y; if(v3Local.z > v3Max.z) v3Max.z = v3Local.z; } } int nSplitAxis = -1; if(fracturedComponent.SplitRegularly) { float fSizeX = v3Max.x - v3Min.x; float fSizeY = v3Max.y - v3Min.y; float fSizeZ = v3Max.z - v3Min.z; if(fSizeX >= fSizeY && fSizeX >= fSizeZ) { nSplitAxis = 0; } else if(fSizeY >= fSizeX && fSizeY >= fSizeZ) { nSplitAxis = 1; } else { nSplitAxis = 2; } } else { for(int i = 0; i < 3; i++) { float fRandomAxis = Random.value; bool bSkipX = Mathf.Approximately(fracturedComponent.SplitXProbability, 0.0f); bool bSkipY = Mathf.Approximately(fracturedComponent.SplitYProbability, 0.0f); bool bSkipZ = Mathf.Approximately(fracturedComponent.SplitZProbability, 0.0f); if(bSkipX == false) { if(fRandomAxis <= fracturedComponent.SplitXProbability || (bSkipY && bSkipZ)) { nSplitAxis = 0; } } if(bSkipY == false && nSplitAxis == -1) { float fSplitInYProbabilityAccum = fracturedComponent.SplitXProbability + fracturedComponent.SplitYProbability; if(fRandomAxis <= fSplitInYProbabilityAccum || bSkipZ == true) { nSplitAxis = 1; } } if(nSplitAxis == -1) { nSplitAxis = 2; } } } nSplitAxisPerformed = nSplitAxis; float fRadius = 0.0f; float fAngleMax = 45.0f; if(nSplitAxis == 0) { fRadius = (v3Max.x - v3Min.x) * 0.5f; qPlane = Quaternion.LookRotation(-Vector3.up, Vector3.right) * Quaternion.Euler(new Vector3(0.0f, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitXVariation, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitXVariation)); } else if(nSplitAxis == 1) { fRadius = (v3Max.y - v3Min.y) * 0.5f; qPlane = Quaternion.Euler(new Vector3(Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitYVariation, 0.0f, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitYVariation)); } else if(nSplitAxis == 2) { fRadius = (v3Max.z - v3Min.z) * 0.5f; qPlane = Quaternion.LookRotation(-Vector3.up, Vector3.forward) * Quaternion.Euler(new Vector3(Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitZVariation, Random.Range(-fAngleMax, fAngleMax) * fracturedComponent.SplitZVariation, 0.0f)); } fRadius = fRadius * fracturedComponent.SplitSizeVariation * 0.8f; v3RandomPosition = new Vector3(Random.Range(-1.0f, 1.0f) * fRadius, Random.Range(-1.0f, 1.0f) * fRadius, Random.Range(-1.0f, 1.0f) * fRadius); if(fracturedComponent.SplitsWorldSpace == false) { return Matrix4x4.TRS(v3RandomPosition + meshDataIn.v3Position, fracturedComponent.SourceObject.transform.rotation * qPlane, Vector3.one); } return Matrix4x4.TRS(v3RandomPosition + meshDataIn.v3Position, qPlane, Vector3.one); } private static GameObject CreateNewSplitGameObject(GameObject gameObjectIn, FracturedObject fracturedComponent, string strName, bool bTransformVerticesBackToLocal, MeshData meshData) { GameObject newGameObject = new GameObject(strName); MeshFilter meshFilter = newGameObject.AddComponent<MeshFilter>(); FracturedChunk fracturedChunk = newGameObject.AddComponent<FracturedChunk>(); fracturedChunk.transform.parent = fracturedComponent.transform; if(fracturedComponent.SourceObject) { newGameObject.layer = fracturedComponent.SourceObject.layer; } else { newGameObject.layer = fracturedComponent.gameObject.layer; } fracturedComponent.ListFracturedChunks.Add(fracturedChunk); meshData.FillMeshFilter(meshFilter, bTransformVerticesBackToLocal); fracturedChunk.SplitSubMeshIndex = meshData.nSplitCloseSubMesh; fracturedChunk.OnCreateFromFracturedObject(fracturedComponent, meshData.nSplitCloseSubMesh); newGameObject.AddComponent<MeshRenderer>(); newGameObject.GetComponent<Renderer>().shadowCastingMode = gameObjectIn.GetComponent<Renderer>().shadowCastingMode; newGameObject.GetComponent<Renderer>().receiveShadows = gameObjectIn.GetComponent<Renderer>().receiveShadows; newGameObject.GetComponent<Renderer>().enabled = false; Material[] aMaterials = new Material[meshData.nSubMeshCount]; meshData.aMaterials.CopyTo(aMaterials, 0); if(meshData.aMaterials.Length < meshData.nSubMeshCount) { // Add split material aMaterials[meshData.nSubMeshCount - 1] = fracturedComponent.SplitMaterial; } newGameObject.GetComponent<Renderer>().sharedMaterials = aMaterials; newGameObject.GetComponent<Renderer>().lightmapIndex = gameObjectIn.GetComponent<Renderer>().lightmapIndex; newGameObject.GetComponent<Renderer>().lightmapScaleOffset = gameObjectIn.GetComponent<Renderer>().lightmapScaleOffset; newGameObject.GetComponent<Renderer>().useLightProbes = gameObjectIn.GetComponent<Renderer>().useLightProbes; // Debug.Log("Out: " + newGameObject.name + ": " + meshFilter.sharedMesh.subMeshCount + " submesh(es), " + ": " + (meshFilter.sharedMesh.triangles.Length / 3) + " triangles, " + meshFilter.sharedMesh.vertexCount + " vertices, " + (meshFilter.sharedMesh.normals != null ? meshFilter.sharedMesh.normals.Length : 0) + " normals, " + (meshFilter.sharedMesh.tangents != null ? meshFilter.sharedMesh.tangents.Length : 0) + " tangents, " + (meshFilter.sharedMesh.colors != null ? meshFilter.sharedMesh.colors.Length : 0) + " colors, " + (meshFilter.sharedMesh.colors32 != null ? meshFilter.sharedMesh.colors32.Length : 0) + " colors32, " + (meshFilter.sharedMesh.uv != null ? meshFilter.sharedMesh.uv.Length : 0) + " uv1, " + (meshFilter.sharedMesh.uv2 != null ? meshFilter.sharedMesh.uv2.Length : 0) + " uv2"); return newGameObject; } private static int CreateMeshConnectivityVoronoiHash(int nCell1, int nCell2) { int nMax = Mathf.Max(nCell1, nCell2) + 256; int nMin = Mathf.Min(nCell1, nCell2) + 256; return (nMax << 16) | nMin; } private static void ComputeChunkConnections(FracturedObject fracturedObject, List<GameObject> listGameObjects, List<MeshData> listMeshDatas, ProgressDelegate progress = null) { for(int i = 0; i < listGameObjects.Count; i++) { if(progress != null) { progress("Fracturing", "Computing connections...", i / (float)listGameObjects.Count); } if(IsFracturingCancelled()) { return; } FracturedChunk chunkA = listGameObjects[i].GetComponent<FracturedChunk>(); List<FracturedChunk.AdjacencyInfo> listAdjacentChunks = new List<FracturedChunk.AdjacencyInfo>(); for(int j = 0; j < listGameObjects.Count; j++) { if(i == j) continue; FracturedChunk chunkB = listGameObjects[j].GetComponent<FracturedChunk>(); float fSharedArea = 0.0f; bool bConnected = listMeshDatas[i].GetSharedFacesArea(fracturedObject, listMeshDatas[j], out fSharedArea); bool bShared = fSharedArea >= fracturedObject.ChunkConnectionMinArea; if(Mathf.Approximately(fracturedObject.ChunkConnectionMinArea, 0.0f) && bConnected) { bShared = true; } if(bShared && bConnected) { listAdjacentChunks.Add(new FracturedChunk.AdjacencyInfo(chunkB, fSharedArea)); } } chunkA.ListAdjacentChunks = listAdjacentChunks; } } private static void RemoveEmptySubmeshes(FracturedChunk fracturedChunk) { MeshFilter meshFilter = fracturedChunk.GetComponent<MeshFilter>(); if (meshFilter == null) { return; } Mesh mesh = meshFilter.sharedMesh; if (mesh.subMeshCount < 2) { return; } MeshRenderer meshRenderer = fracturedChunk.GetComponent<MeshRenderer>(); List<Material> listMaterials = new List<Material>(); List<int[]> listSubmeshes = new List<int[]>(); int nSplitIndexSubtract = 0; for (int i = 0; i < mesh.subMeshCount; i++) { int[] indices = mesh.GetIndices(i); if (indices != null && indices.Length > 0) { listMaterials.Add(meshRenderer.sharedMaterials[i]); listSubmeshes.Add(indices); } else { if (i < fracturedChunk.SplitSubMeshIndex) { nSplitIndexSubtract--; } } } mesh.subMeshCount = listSubmeshes.Count; for (int i = 0; i < listSubmeshes.Count; i++) { mesh.SetTriangles(listSubmeshes[i], i); meshRenderer.sharedMaterials = listMaterials.ToArray(); } fracturedChunk.SplitSubMeshIndex -= nSplitIndexSubtract; meshFilter.sharedMesh = mesh; } } }
// // FontBackendHandler.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Globalization; using System.Text; using AppKit; using CoreText; using Foundation; using Xwt.Backends; using Xwt.Drawing; namespace Xwt.Mac { public class MacFontBackendHandler: FontBackendHandler { public override object GetSystemDefaultFont () { return FontData.FromFont (NSFont.SystemFontOfSize (0)); } public override object GetSystemDefaultMonospaceFont () { var font = NSFont.SystemFontOfSize (0); return Create (GetDefaultMonospaceFontNames(Desktop.DesktopType), font.PointSize, FontStyle.Normal, FontWeight.Normal, FontStretch.Normal); } public override IEnumerable<string> GetInstalledFonts () { return NSFontManager.SharedFontManager.AvailableFontFamilies; } public override IEnumerable<KeyValuePair<string, object>> GetAvailableFamilyFaces (string family) { foreach (var nsFace in NSFontManager.SharedFontManager.AvailableMembersOfFontFamily(family)) { var name = NSString.FromHandle(nsFace.ValueAt(1)); using (var weightValue = (NSNumber)NSValue.ValueFromPointer(nsFace.ValueAt(2)).NonretainedObjectValue) using (var traitsValue = (NSNumber)NSValue.ValueFromPointer(nsFace.ValueAt(3)).NonretainedObjectValue) { var weight = weightValue.Int32Value; var traits = (NSFontTraitMask)traitsValue.Int32Value; yield return new KeyValuePair<string, object>(name, FontData.FromFamily(family, traits, weight, 0)); } } yield break; } public override object Create (string fontName, double size, FontStyle style, FontWeight weight, FontStretch stretch) { var t = GetStretchTrait (stretch) | GetStyleTrait (style); var names = fontName.Split (new char[] {','}, StringSplitOptions.RemoveEmptyEntries); NSFont f = null; foreach (var name in names) { f = NSFontManager.SharedFontManager.FontWithFamily (name.Trim (), t, weight.ToMacValue (), (float)size); if (f != null) break; } if (f == null) return null; var fd = FontData.FromFont (NSFontManager.SharedFontManager.ConvertFont (f, t)); fd.Style = style; fd.Weight = weight; fd.Stretch = stretch; return fd; } public override bool RegisterFontFromFile (string fontPath) { return CTFontManager.RegisterFontsForUrl (NSUrl.FromFilename (fontPath), CTFontManagerScope.Process) == null; } #region IFontBackendHandler implementation public override object Copy (object handle) { FontData f = (FontData) handle; f = f.Copy (); f.Font = (NSFont) f.Font.Copy (); return f; } public override object SetSize (object handle, double size) { FontData f = (FontData) handle; f = f.Copy (); f.Font = NSFontManager.SharedFontManager.ConvertFont (f.Font, (float)size); return f; } public override object SetFamily (object handle, string family) { FontData f = (FontData) handle; f = f.Copy (); var names = family.Split (new char[] {','}, StringSplitOptions.RemoveEmptyEntries); NSFont font = null; foreach (var name in names) { font = NSFontManager.SharedFontManager.ConvertFontToFamily (f.Font, name.Trim ()); if (font != null) { f.Font = font; break; } } return f; } public override object SetStyle (object handle, FontStyle style) { FontData f = (FontData) handle; f = f.Copy (); NSFontTraitMask mask; if (style == FontStyle.Italic || style == FontStyle.Oblique) mask = NSFontTraitMask.Italic; else mask = NSFontTraitMask.Unitalic; f.Font = NSFontManager.SharedFontManager.ConvertFont (f.Font, mask); f.Style = style; return f; } static FontWeight [] weightLookupTable = { FontWeight.Ultrathin, // 0 FontWeight.Thin, FontWeight.Ultralight, FontWeight.Light, FontWeight.Book, FontWeight.Normal, // 5 FontWeight.Medium, FontWeight.Mediumbold, FontWeight.Semibold, FontWeight.Bold, // 9 FontWeight.Ultrabold, FontWeight.Heavy, FontWeight.Ultraheavy, FontWeight.Semiblack, FontWeight.Black, FontWeight.Ultrablack // 15 }; internal static FontWeight GetWeightFromValue (nint weightValue) { if (weightValue < 0 || weightValue >= weightLookupTable.Length) throw new ArgumentOutOfRangeException (nameof (weightValue), "needs to be from 0-" + weightLookupTable.Length + " was:" + weightValue); return weightLookupTable [weightValue]; } NSFontTraitMask GetStretchTrait (FontStretch stretch) { switch (stretch) { case FontStretch.Condensed: case FontStretch.ExtraCondensed: case FontStretch.SemiCondensed: return NSFontTraitMask.Condensed; case FontStretch.Normal: return default (NSFontTraitMask); default: return NSFontTraitMask.Expanded; } } NSFontTraitMask GetStyleTrait (FontStyle style) { switch (style) { case FontStyle.Italic: case FontStyle.Oblique: return NSFontTraitMask.Italic; default: return default (NSFontTraitMask); } } public override object SetWeight (object handle, FontWeight weight) { FontData f = (FontData) handle; f = f.Copy (); f.Font = f.Font.WithWeight (weight); f.Weight = weight; return f; } public override object SetStretch (object handle, FontStretch stretch) { FontData f = (FontData) handle; f = f.Copy (); NSFont font = f.Font; if (stretch < FontStretch.SemiCondensed) { font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Condensed); font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Expanded | NSFontTraitMask.Narrow); } if (stretch == FontStretch.SemiCondensed) { font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Narrow); font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Expanded | NSFontTraitMask.Condensed); } else if (stretch > FontStretch.Normal) { font = NSFontManager.SharedFontManager.ConvertFont (font, NSFontTraitMask.Expanded); font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Compressed | NSFontTraitMask.Narrow | NSFontTraitMask.Condensed); } else { font = NSFontManager.SharedFontManager.ConvertFontToNotHaveTrait (font, NSFontTraitMask.Condensed | NSFontTraitMask.Expanded | NSFontTraitMask.Narrow | NSFontTraitMask.Compressed); } f.Font = font; f.Stretch = stretch; return f; } public override double GetSize (object handle) { FontData f = (FontData) handle; return f.Font.PointSize; } public override string GetFamily (object handle) { FontData f = (FontData) handle; return f.Font.FamilyName; } public override FontStyle GetStyle (object handle) { FontData f = (FontData) handle; return f.Style; } public override FontWeight GetWeight (object handle) { FontData f = (FontData) handle; return f.Weight; } public override FontStretch GetStretch (object handle) { FontData f = (FontData) handle; return f.Stretch; } #endregion } public class FontData { public NSFont Font; public FontStyle Style; public FontWeight Weight; public FontStretch Stretch; public FontData () { } public static FontData FromFamily (string family, NSFontTraitMask traits, int weight, float size) { var font = NSFontManager.SharedFontManager.FontWithFamily (family, traits, weight, size); var gentraits = NSFontManager.SharedFontManager.TraitsOfFont (font); // NSFontManager may loose the traits, restore them here if (traits > 0 && gentraits == 0) font = NSFontManager.SharedFontManager.ConvertFont (font, traits); return FromFont (font); } public static FontData FromFont (NSFont font) { var traits = NSFontManager.SharedFontManager.TraitsOfFont (font); FontStretch stretch; if ((traits & NSFontTraitMask.Condensed) != 0) stretch = FontStretch.Condensed; else if ((traits & NSFontTraitMask.Narrow) != 0) stretch = FontStretch.SemiCondensed; else if ((traits & NSFontTraitMask.Compressed) != 0) stretch = FontStretch.ExtraCondensed; else if ((traits & NSFontTraitMask.Expanded) != 0) stretch = FontStretch.Expanded; else stretch = FontStretch.Normal; FontStyle style; if ((traits & NSFontTraitMask.Italic) != 0) style = FontStyle.Italic; else style = FontStyle.Normal; return new FontData { Font = font, Style = style, Weight = MacFontBackendHandler.GetWeightFromValue (NSFontManager.SharedFontManager.WeightOfFont (font)), Stretch = stretch }; } public FontData Copy () { return new FontData { Font = Font, Style = Style, Weight = Weight, Stretch = Stretch }; } public override string ToString () { StringBuilder sb = new StringBuilder (Font.FamilyName); if (Style != FontStyle.Normal) sb.Append (' ').Append (Style.ToString ()); if (Weight != FontWeight.Normal) sb.Append (' ').Append (Weight.ToString ()); if (Stretch != FontStretch.Normal) sb.Append (' ').Append (Stretch.ToString ()); sb.Append (' ').Append (Font.PointSize.ToString (CultureInfo.InvariantCulture)); return sb.ToString (); } } }
// // ReplicationTest.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Net; using Apache.Http; using Apache.Http.Client; using Apache.Http.Client.Methods; using Apache.Http.Entity; using Apache.Http.Impl.Client; using Apache.Http.Message; using Couchbase.Lite; using Couchbase.Lite.Auth; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Threading; using Couchbase.Lite.Util; using NUnit.Framework; using Org.Apache.Commons.IO; using Org.Apache.Commons.IO.Output; using Sharpen; namespace Couchbase.Lite.Replicator { public class ReplicationTest : LiteTestCase { public const string Tag = "Replicator"; /// <exception cref="System.Exception"></exception> public virtual void TestPusher() { CountDownLatch replicationDoneSignal = new CountDownLatch(1); Uri remote = GetReplicationURL(); string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); // Create some documents: IDictionary<string, object> documentProperties = new Dictionary<string, object>(); string doc1Id = string.Format("doc1-%s", docIdTimestamp); documentProperties.Put("_id", doc1Id); documentProperties.Put("foo", 1); documentProperties.Put("bar", false); Body body = new Body(documentProperties); RevisionInternal rev1 = new RevisionInternal(body, database); Status status = new Status(); rev1 = database.PutRevision(rev1, null, false, status); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); documentProperties.Put("_rev", rev1.GetRevId()); documentProperties.Put("UPDATED", true); RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties , database), rev1.GetRevId(), false, status); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); documentProperties = new Dictionary<string, object>(); string doc2Id = string.Format("doc2-%s", docIdTimestamp); documentProperties.Put("_id", doc2Id); documentProperties.Put("baz", 666); documentProperties.Put("fnord", true); database.PutRevision(new RevisionInternal(documentProperties, database), null, false , status); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); bool continuous = false; Replication repl = database.CreatePushReplication(remote); repl.SetContinuous(continuous); repl.SetCreateTarget(true); // Check the replication's properties: NUnit.Framework.Assert.AreEqual(database, repl.GetLocalDatabase()); NUnit.Framework.Assert.AreEqual(remote, repl.GetRemoteUrl()); NUnit.Framework.Assert.IsFalse(repl.IsPull()); NUnit.Framework.Assert.IsFalse(repl.IsContinuous()); NUnit.Framework.Assert.IsTrue(repl.ShouldCreateTarget()); NUnit.Framework.Assert.IsNull(repl.GetFilter()); NUnit.Framework.Assert.IsNull(repl.GetFilterParams()); // TODO: CAssertNil(r1.doc_ids); // TODO: CAssertNil(r1.headers); // Check that the replication hasn't started running: NUnit.Framework.Assert.IsFalse(repl.IsRunning()); NUnit.Framework.Assert.AreEqual(Replication.ReplicationStatus.ReplicationStopped, repl.GetStatus()); NUnit.Framework.Assert.AreEqual(0, repl.GetCompletedChangesCount()); NUnit.Framework.Assert.AreEqual(0, repl.GetChangesCount()); NUnit.Framework.Assert.IsNull(repl.GetLastError()); RunReplication(repl); // make sure doc1 is there // TODO: make sure doc2 is there (refactoring needed) Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm() )); Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id); Log.D(Tag, "Send http request to " + pathToDoc); CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new _BackgroundTask_122(pathToDoc, doc1Id, httpRequestDoneSignal ); //Closes the connection. getDocTask.Execute(); Log.D(Tag, "Waiting for http request to finish"); try { httpRequestDoneSignal.Await(300, TimeUnit.Seconds); Log.D(Tag, "http request finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } Log.D(Tag, "testPusher() finished"); } private sealed class _BackgroundTask_122 : BackgroundTask { public _BackgroundTask_122(Uri pathToDoc, string doc1Id, CountDownLatch httpRequestDoneSignal ) { this.pathToDoc = pathToDoc; this.doc1Id = doc1Id; this.httpRequestDoneSignal = httpRequestDoneSignal; } public override void Run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; string responseString = null; try { response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm())); StatusLine statusLine = response.GetStatusLine(); NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScOk); if (statusLine.GetStatusCode() == HttpStatus.ScOk) { ByteArrayOutputStream @out = new ByteArrayOutputStream(); response.GetEntity().WriteTo(@out); @out.Close(); responseString = @out.ToString(); NUnit.Framework.Assert.IsTrue(responseString.Contains(doc1Id)); Log.D(ReplicationTest.Tag, "result: " + responseString); } else { response.GetEntity().GetContent().Close(); throw new IOException(statusLine.GetReasonPhrase()); } } catch (ClientProtocolException e) { NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage (), e); } catch (IOException e) { NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e); } httpRequestDoneSignal.CountDown(); } private readonly Uri pathToDoc; private readonly string doc1Id; private readonly CountDownLatch httpRequestDoneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestPusherDeletedDoc() { CountDownLatch replicationDoneSignal = new CountDownLatch(1); Uri remote = GetReplicationURL(); string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); // Create some documents: IDictionary<string, object> documentProperties = new Dictionary<string, object>(); string doc1Id = string.Format("doc1-%s", docIdTimestamp); documentProperties.Put("_id", doc1Id); documentProperties.Put("foo", 1); documentProperties.Put("bar", false); Body body = new Body(documentProperties); RevisionInternal rev1 = new RevisionInternal(body, database); Status status = new Status(); rev1 = database.PutRevision(rev1, null, false, status); NUnit.Framework.Assert.AreEqual(Status.Created, status.GetCode()); documentProperties.Put("_rev", rev1.GetRevId()); documentProperties.Put("UPDATED", true); documentProperties.Put("_deleted", true); RevisionInternal rev2 = database.PutRevision(new RevisionInternal(documentProperties , database), rev1.GetRevId(), false, status); NUnit.Framework.Assert.IsTrue(status.GetCode() >= 200 && status.GetCode() < 300); Replication repl = database.CreatePushReplication(remote); ((Pusher)repl).SetCreateTarget(true); RunReplication(repl); // make sure doc1 is deleted Uri replicationUrlTrailing = new Uri(string.Format("%s/", remote.ToExternalForm() )); Uri pathToDoc = new Uri(replicationUrlTrailing, doc1Id); Log.D(Tag, "Send http request to " + pathToDoc); CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new _BackgroundTask_216(pathToDoc, httpRequestDoneSignal ); getDocTask.Execute(); Log.D(Tag, "Waiting for http request to finish"); try { httpRequestDoneSignal.Await(300, TimeUnit.Seconds); Log.D(Tag, "http request finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } Log.D(Tag, "testPusherDeletedDoc() finished"); } private sealed class _BackgroundTask_216 : BackgroundTask { public _BackgroundTask_216(Uri pathToDoc, CountDownLatch httpRequestDoneSignal) { this.pathToDoc = pathToDoc; this.httpRequestDoneSignal = httpRequestDoneSignal; } public override void Run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; string responseString = null; try { response = httpclient.Execute(new HttpGet(pathToDoc.ToExternalForm())); StatusLine statusLine = response.GetStatusLine(); Log.D(ReplicationTest.Tag, "statusLine " + statusLine); NUnit.Framework.Assert.AreEqual(HttpStatus.ScNotFound, statusLine.GetStatusCode() ); } catch (ClientProtocolException e) { NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage (), e); } catch (IOException e) { NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e); } finally { httpRequestDoneSignal.CountDown(); } } private readonly Uri pathToDoc; private readonly CountDownLatch httpRequestDoneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestPuller() { string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); string doc1Id = string.Format("doc1-%s", docIdTimestamp); string doc2Id = string.Format("doc2-%s", docIdTimestamp); AddDocWithId(doc1Id, "attachment.png"); AddDocWithId(doc2Id, "attachment2.png"); // workaround for https://github.com/couchbase/sync_gateway/issues/228 Sharpen.Thread.Sleep(1000); DoPullReplication(); Log.D(Tag, "Fetching doc1 via id: " + doc1Id); RevisionInternal doc1 = database.GetDocumentWithIDAndRev(doc1Id, null, EnumSet.NoneOf <Database.TDContentOptions>()); NUnit.Framework.Assert.IsNotNull(doc1); NUnit.Framework.Assert.IsTrue(doc1.GetRevId().StartsWith("1-")); NUnit.Framework.Assert.AreEqual(1, doc1.GetProperties().Get("foo")); Log.D(Tag, "Fetching doc2 via id: " + doc2Id); RevisionInternal doc2 = database.GetDocumentWithIDAndRev(doc2Id, null, EnumSet.NoneOf <Database.TDContentOptions>()); NUnit.Framework.Assert.IsNotNull(doc2); NUnit.Framework.Assert.IsTrue(doc2.GetRevId().StartsWith("1-")); NUnit.Framework.Assert.AreEqual(1, doc2.GetProperties().Get("foo")); Log.D(Tag, "testPuller() finished"); } /// <exception cref="System.Exception"></exception> public virtual void TestPullerWithLiveQuery() { // This is essentially a regression test for a deadlock // that was happening when the LiveQuery#onDatabaseChanged() // was calling waitForUpdateThread(), but that thread was // waiting on connection to be released by the thread calling // waitForUpdateThread(). When the deadlock bug was present, // this test would trigger the deadlock and never finish. Log.D(Database.Tag, "testPullerWithLiveQuery"); string docIdTimestamp = System.Convert.ToString(Runtime.CurrentTimeMillis()); string doc1Id = string.Format("doc1-%s", docIdTimestamp); string doc2Id = string.Format("doc2-%s", docIdTimestamp); AddDocWithId(doc1Id, "attachment2.png"); AddDocWithId(doc2Id, "attachment2.png"); int numDocsBeforePull = database.GetDocumentCount(); View view = database.GetView("testPullerWithLiveQueryView"); view.SetMapAndReduce(new _Mapper_307(), null, "1"); LiveQuery allDocsLiveQuery = view.CreateQuery().ToLiveQuery(); allDocsLiveQuery.AddChangeListener(new _ChangeListener_317(numDocsBeforePull)); // the first time this is called back, the rows will be empty. // but on subsequent times we should expect to get a non empty // row set. allDocsLiveQuery.Start(); DoPullReplication(); } private sealed class _Mapper_307 : Mapper { public _Mapper_307() { } public void Map(IDictionary<string, object> document, Emitter emitter) { if (document.Get("_id") != null) { emitter.Emit(document.Get("_id"), null); } } } private sealed class _ChangeListener_317 : LiveQuery.ChangeListener { public _ChangeListener_317(int numDocsBeforePull) { this.numDocsBeforePull = numDocsBeforePull; } public void Changed(LiveQuery.ChangeEvent @event) { int numTimesCalled = 0; if (@event.GetError() != null) { throw new RuntimeException(@event.GetError()); } if (numTimesCalled++ > 0) { NUnit.Framework.Assert.IsTrue(@event.GetRows().GetCount() > numDocsBeforePull); } Log.D(Database.Tag, "rows " + @event.GetRows()); } private readonly int numDocsBeforePull; } private void DoPullReplication() { Uri remote = GetReplicationURL(); CountDownLatch replicationDoneSignal = new CountDownLatch(1); Replication repl = (Replication)database.CreatePullReplication(remote); repl.SetContinuous(false); RunReplication(repl); } /// <exception cref="System.IO.IOException"></exception> private void AddDocWithId(string docId, string attachmentName) { string docJson; if (attachmentName != null) { // add attachment to document InputStream attachmentStream = GetAsset(attachmentName); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.Copy(attachmentStream, baos); string attachmentBase64 = Base64.EncodeBytes(baos.ToByteArray()); docJson = string.Format("{\"foo\":1,\"bar\":false, \"_attachments\": { \"i_use_couchdb.png\": { \"content_type\": \"image/png\", \"data\": \"%s\" } } }" , attachmentBase64); } else { docJson = "{\"foo\":1,\"bar\":false}"; } // push a document to server Uri replicationUrlTrailingDoc1 = new Uri(string.Format("%s/%s", GetReplicationURL ().ToExternalForm(), docId)); Uri pathToDoc1 = new Uri(replicationUrlTrailingDoc1, docId); Log.D(Tag, "Send http request to " + pathToDoc1); CountDownLatch httpRequestDoneSignal = new CountDownLatch(1); BackgroundTask getDocTask = new _BackgroundTask_376(pathToDoc1, docJson, httpRequestDoneSignal ); getDocTask.Execute(); Log.D(Tag, "Waiting for http request to finish"); try { httpRequestDoneSignal.Await(300, TimeUnit.Seconds); Log.D(Tag, "http request finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private sealed class _BackgroundTask_376 : BackgroundTask { public _BackgroundTask_376(Uri pathToDoc1, string docJson, CountDownLatch httpRequestDoneSignal ) { this.pathToDoc1 = pathToDoc1; this.docJson = docJson; this.httpRequestDoneSignal = httpRequestDoneSignal; } public override void Run() { HttpClient httpclient = new DefaultHttpClient(); HttpResponse response; string responseString = null; try { HttpPut post = new HttpPut(pathToDoc1.ToExternalForm()); StringEntity se = new StringEntity(docJson.ToString()); se.SetContentType(new BasicHeader("content_type", "application/json")); post.SetEntity(se); response = httpclient.Execute(post); StatusLine statusLine = response.GetStatusLine(); Log.D(ReplicationTest.Tag, "Got response: " + statusLine); NUnit.Framework.Assert.IsTrue(statusLine.GetStatusCode() == HttpStatus.ScCreated); } catch (ClientProtocolException e) { NUnit.Framework.Assert.IsNull("Got ClientProtocolException: " + e.GetLocalizedMessage (), e); } catch (IOException e) { NUnit.Framework.Assert.IsNull("Got IOException: " + e.GetLocalizedMessage(), e); } httpRequestDoneSignal.CountDown(); } private readonly Uri pathToDoc1; private readonly string docJson; private readonly CountDownLatch httpRequestDoneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestGetReplicator() { IDictionary<string, object> properties = new Dictionary<string, object>(); properties.Put("source", DefaultTestDb); properties.Put("target", GetReplicationURL().ToExternalForm()); Replication replicator = manager.GetReplicator(properties); NUnit.Framework.Assert.IsNotNull(replicator); NUnit.Framework.Assert.AreEqual(GetReplicationURL().ToExternalForm(), replicator. GetRemoteUrl().ToExternalForm()); NUnit.Framework.Assert.IsTrue(!replicator.IsPull()); NUnit.Framework.Assert.IsFalse(replicator.IsContinuous()); NUnit.Framework.Assert.IsFalse(replicator.IsRunning()); // start the replicator replicator.Start(); // now lets lookup existing replicator and stop it properties.Put("cancel", true); Replication activeReplicator = manager.GetReplicator(properties); activeReplicator.Stop(); NUnit.Framework.Assert.IsFalse(activeReplicator.IsRunning()); } /// <exception cref="System.Exception"></exception> public virtual void TestGetReplicatorWithAuth() { IDictionary<string, object> properties = GetPushReplicationParsedJson(); Replication replicator = manager.GetReplicator(properties); NUnit.Framework.Assert.IsNotNull(replicator); NUnit.Framework.Assert.IsNotNull(replicator.GetAuthorizer()); NUnit.Framework.Assert.IsTrue(replicator.GetAuthorizer() is FacebookAuthorizer); } private void RunReplication(Replication replication) { CountDownLatch replicationDoneSignal = new CountDownLatch(1); ReplicationTest.ReplicationObserver replicationObserver = new ReplicationTest.ReplicationObserver (this, replicationDoneSignal); replication.AddChangeListener(replicationObserver); replication.Start(); CountDownLatch replicationDoneSignalPolling = ReplicationWatcherThread(replication ); Log.D(Tag, "Waiting for replicator to finish"); try { bool success = replicationDoneSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); success = replicationDoneSignalPolling.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(success); Log.D(Tag, "replicator finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } private CountDownLatch ReplicationWatcherThread(Replication replication) { CountDownLatch doneSignal = new CountDownLatch(1); new Sharpen.Thread(new _Runnable_482(replication, doneSignal)).Start(); return doneSignal; } private sealed class _Runnable_482 : Runnable { public _Runnable_482(Replication replication, CountDownLatch doneSignal) { this.replication = replication; this.doneSignal = doneSignal; } public void Run() { bool started = false; bool done = false; while (!done) { if (replication.IsRunning()) { started = true; } bool statusIsDone = (replication.GetStatus() == Replication.ReplicationStatus.ReplicationStopped || replication.GetStatus() == Replication.ReplicationStatus.ReplicationIdle); if (started && statusIsDone) { done = true; } try { Sharpen.Thread.Sleep(500); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } } doneSignal.CountDown(); } private readonly Replication replication; private readonly CountDownLatch doneSignal; } /// <exception cref="System.Exception"></exception> public virtual void TestRunReplicationWithError() { HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_516(); string dbUrlString = "http://fake.test-url.com:4984/fake/"; Uri remote = new Uri(dbUrlString); bool continuous = false; Replication r1 = new Puller(database, remote, continuous, mockHttpClientFactory, manager.GetWorkExecutor()); NUnit.Framework.Assert.IsFalse(r1.IsContinuous()); RunReplication(r1); // It should have failed with a 404: NUnit.Framework.Assert.AreEqual(Replication.ReplicationStatus.ReplicationStopped, r1.GetStatus()); NUnit.Framework.Assert.AreEqual(0, r1.GetCompletedChangesCount()); NUnit.Framework.Assert.AreEqual(0, r1.GetChangesCount()); NUnit.Framework.Assert.IsNotNull(r1.GetLastError()); } private sealed class _HttpClientFactory_516 : HttpClientFactory { public _HttpClientFactory_516() { } public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); int statusCode = 500; mockHttpClient.AddResponderFailAllRequests(statusCode); return mockHttpClient; } } /// <exception cref="System.Exception"></exception> public virtual void TestReplicatorErrorStatus() { Assert.Fail(); // NOTE.ZJG: Need to remove FB & Persona login stuff. // register bogus fb token IDictionary<string, object> facebookTokenInfo = new Dictionary<string, object>(); facebookTokenInfo.Put("email", "jchris@couchbase.com"); facebookTokenInfo.Put("remote_url", GetReplicationURL().ToExternalForm()); facebookTokenInfo.Put("access_token", "fake_access_token"); string destUrl = string.Format("/_facebook_token", DefaultTestDb); IDictionary<string, object> result = (IDictionary<string, object>)SendBody("POST" , destUrl, facebookTokenInfo, Status.Ok, null); Log.V(Tag, string.Format("result %s", result)); // start a replicator IDictionary<string, object> properties = GetPullReplicationParsedJson(); Replication replicator = manager.GetReplicator(properties); replicator.Start(); bool foundError = false; for (int i = 0; i < 10; i++) { // wait a few seconds Sharpen.Thread.Sleep(5 * 1000); // expect an error since it will try to contact the sync gateway with this bogus login, // and the sync gateway will reject it. AList<object> activeTasks = (AList<object>)Send("GET", "/_active_tasks", Status.Ok , null); Log.D(Tag, "activeTasks: " + activeTasks); IDictionary<string, object> activeTaskReplication = (IDictionary<string, object>) activeTasks[0]; foundError = (activeTaskReplication.Get("error") != null); if (foundError == true) { break; } } NUnit.Framework.Assert.IsTrue(foundError); } /// <exception cref="System.Exception"></exception> public virtual void TestFetchRemoteCheckpointDoc() { HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_583(); Log.D("TEST", "testFetchRemoteCheckpointDoc() called"); string dbUrlString = "http://fake.test-url.com:4984/fake/"; Uri remote = new Uri(dbUrlString); database.SetLastSequence("1", remote, true); // otherwise fetchRemoteCheckpoint won't contact remote Replication replicator = new Pusher(database, remote, false, mockHttpClientFactory , manager.GetWorkExecutor()); CountDownLatch doneSignal = new CountDownLatch(1); ReplicationTest.ReplicationObserver replicationObserver = new ReplicationTest.ReplicationObserver (this, doneSignal); replicator.AddChangeListener(replicationObserver); replicator.FetchRemoteCheckpointDoc(); Log.D(Tag, "testFetchRemoteCheckpointDoc() Waiting for replicator to finish"); try { bool succeeded = doneSignal.Await(300, TimeUnit.Seconds); NUnit.Framework.Assert.IsTrue(succeeded); Log.D(Tag, "testFetchRemoteCheckpointDoc() replicator finished"); } catch (Exception e) { Sharpen.Runtime.PrintStackTrace(e); } string errorMessage = "Since we are passing in a mock http client that always throws " + "errors, we expect the replicator to be in an error state"; NUnit.Framework.Assert.IsNotNull(errorMessage, replicator.GetLastError()); } private sealed class _HttpClientFactory_583 : HttpClientFactory { public _HttpClientFactory_583() { } public HttpClient GetHttpClient() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); return mockHttpClient; } } /// <exception cref="System.Exception"></exception> public virtual void TestGoOffline() { Uri remote = GetReplicationURL(); CountDownLatch replicationDoneSignal = new CountDownLatch(1); Replication repl = database.CreatePullReplication(remote); repl.SetContinuous(true); repl.Start(); repl.GoOffline(); NUnit.Framework.Assert.IsTrue(repl.GetStatus() == Replication.ReplicationStatus.ReplicationOffline ); } internal class ReplicationObserver : Replication.ChangeListener { public bool replicationFinished = false; private CountDownLatch doneSignal; internal ReplicationObserver(ReplicationTest _enclosing, CountDownLatch doneSignal ) { this._enclosing = _enclosing; this.doneSignal = doneSignal; } public virtual void Changed(Replication.ChangeEvent @event) { Replication replicator = @event.GetSource(); if (!replicator.IsRunning()) { this.replicationFinished = true; string msg = string.Format("myobserver.update called, set replicationFinished to: %b" , this.replicationFinished); Log.D(ReplicationTest.Tag, msg); this.doneSignal.CountDown(); } else { string msg = string.Format("myobserver.update called, but replicator still running, so ignore it" ); Log.D(ReplicationTest.Tag, msg); } } internal virtual bool IsReplicationFinished() { return this.replicationFinished; } private readonly ReplicationTest _enclosing; } /// <exception cref="System.Exception"></exception> public virtual void TestBuildRelativeURLString() { string dbUrlString = "http://10.0.0.3:4984/todos/"; Replication replicator = new Pusher(null, new Uri(dbUrlString), false, null); string relativeUrlString = replicator.BuildRelativeURLString("foo"); string expected = "http://10.0.0.3:4984/todos/foo"; NUnit.Framework.Assert.AreEqual(expected, relativeUrlString); } /// <exception cref="System.Exception"></exception> public virtual void TestBuildRelativeURLStringWithLeadingSlash() { string dbUrlString = "http://10.0.0.3:4984/todos/"; Replication replicator = new Pusher(null, new Uri(dbUrlString), false, null); string relativeUrlString = replicator.BuildRelativeURLString("/foo"); string expected = "http://10.0.0.3:4984/todos/foo"; NUnit.Framework.Assert.AreEqual(expected, relativeUrlString); } /// <exception cref="System.Exception"></exception> public virtual void TestChannels() { Uri remote = GetReplicationURL(); Replication replicator = database.CreatePullReplication(remote); IList<string> channels = new AList<string>(); channels.AddItem("chan1"); channels.AddItem("chan2"); replicator.SetChannels(channels); NUnit.Framework.Assert.AreEqual(channels, replicator.GetChannels()); replicator.SetChannels(null); NUnit.Framework.Assert.IsTrue(replicator.GetChannels().IsEmpty()); } /// <exception cref="System.UriFormatException"></exception> public virtual void TestChannelsMore() { Database db = StartDatabase(); Uri fakeRemoteURL = new Uri("http://couchbase.com/no_such_db"); Replication r1 = db.CreatePullReplication(fakeRemoteURL); NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty()); r1.SetFilter("foo/bar"); NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty()); IDictionary<string, object> filterParams = new Dictionary<string, object>(); filterParams.Put("a", "b"); r1.SetFilterParams(filterParams); NUnit.Framework.Assert.IsTrue(r1.GetChannels().IsEmpty()); r1.SetChannels(null); NUnit.Framework.Assert.AreEqual("foo/bar", r1.GetFilter()); NUnit.Framework.Assert.AreEqual(filterParams, r1.GetFilterParams()); IList<string> channels = new AList<string>(); channels.AddItem("NBC"); channels.AddItem("MTV"); r1.SetChannels(channels); NUnit.Framework.Assert.AreEqual(channels, r1.GetChannels()); NUnit.Framework.Assert.AreEqual("sync_gateway/bychannel", r1.GetFilter()); filterParams = new Dictionary<string, object>(); filterParams.Put("channels", "NBC,MTV"); NUnit.Framework.Assert.AreEqual(filterParams, r1.GetFilterParams()); r1.SetChannels(null); NUnit.Framework.Assert.AreEqual(r1.GetFilter(), null); NUnit.Framework.Assert.AreEqual(null, r1.GetFilterParams()); } /// <exception cref="System.Exception"></exception> public virtual void TestHeaders() { CustomizableMockHttpClient mockHttpClient = new CustomizableMockHttpClient(); mockHttpClient.AddResponderThrowExceptionAllRequests(); HttpClientFactory mockHttpClientFactory = new _HttpClientFactory_741(mockHttpClient ); Uri remote = GetReplicationURL(); manager.SetDefaultHttpClientFactory(mockHttpClientFactory); Replication puller = database.CreatePullReplication(remote); IDictionary<string, object> headers = new Dictionary<string, object>(); headers.Put("foo", "bar"); puller.SetHeaders(headers); puller.Start(); Sharpen.Thread.Sleep(2000); puller.Stop(); bool foundFooHeader = false; IList<HttpWebRequest> requests = mockHttpClient.GetCapturedRequests(); foreach (HttpWebRequest request in requests) { Header[] requestHeaders = request.GetHeaders("foo"); foreach (Header requestHeader in requestHeaders) { foundFooHeader = true; NUnit.Framework.Assert.AreEqual("bar", requestHeader.GetValue()); } } NUnit.Framework.Assert.IsTrue(foundFooHeader); manager.SetDefaultHttpClientFactory(null); } private sealed class _HttpClientFactory_741 : HttpClientFactory { public _HttpClientFactory_741(CustomizableMockHttpClient mockHttpClient) { this.mockHttpClient = mockHttpClient; } public HttpClient GetHttpClient() { return mockHttpClient; } private readonly CustomizableMockHttpClient mockHttpClient; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorJson.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Specialized; using System.IO; using System.Threading; using System.Web; using System.Xml; using XmlReader = System.Xml.XmlReader; using XmlWriter = System.Xml.XmlWriter; using Thread = System.Threading.Thread; using NameValueCollection = System.Collections.Specialized.NameValueCollection; using XmlConvert = System.Xml.XmlConvert; using WriteState = System.Xml.WriteState; #endregion /// <summary> /// Responsible for primarily encoding the JSON representation of /// <see cref="Error"/> objects. /// </summary> [ Serializable ] public sealed class ErrorJson { /// <summary> /// Encodes the default JSON representation of an <see cref="Error"/> /// object to a string. /// </summary> /// <remarks> /// Only properties and collection entires with non-null /// and non-empty strings are emitted. /// </remarks> public static string EncodeString(Error error) { if (error == null) throw new ArgumentNullException("error"); StringWriter writer = new StringWriter(); Encode(error, writer); return writer.ToString(); } /// <summary> /// Encodes the default JSON representation of an <see cref="Error"/> /// object to a <see cref="TextWriter" />. /// </summary> /// <remarks> /// Only properties and collection entires with non-null /// and non-empty strings are emitted. /// </remarks> public static void Encode(Error error, TextWriter writer) { if (error == null) throw new ArgumentNullException("error"); if (writer == null) throw new ArgumentNullException("writer"); EncodeEnclosed(error, new JsonTextWriter(writer)); } private static void EncodeEnclosed(Error error, JsonTextWriter writer) { Debug.Assert(error != null); Debug.Assert(writer != null); writer.Object(); Encode(error, writer); writer.Pop(); } internal static void Encode(Error error, JsonTextWriter writer) { Debug.Assert(error != null); Debug.Assert(writer != null); Member(writer, "application", error.ApplicationName); Member(writer, "host", error.HostName); Member(writer, "type", error.Type); Member(writer, "message", error.Message); Member(writer, "source", error.Source); Member(writer, "detail", error.Detail); Member(writer, "user", error.User); Member(writer, "time", error.Time, DateTime.MinValue); Member(writer, "statusCode", error.StatusCode, 0); Member(writer, "webHostHtmlMessage", error.WebHostHtmlMessage); Member(writer, "serverVariables", error.ServerVariables); Member(writer, "queryString", error.QueryString); Member(writer, "form", error.Form); Member(writer, "cookies", error.Cookies); } private static void Member(JsonTextWriter writer, string name, int value, int defaultValue) { if (value == defaultValue) return; writer.Member(name).Number(value); } private static void Member(JsonTextWriter writer, string name, DateTime value, DateTime defaultValue) { if (value == defaultValue) return; writer.Member(name).String(value); } private static void Member(JsonTextWriter writer, string name, string value) { Debug.Assert(writer != null); Debug.AssertStringNotEmpty(name); if (value == null || value.Length == 0) return; writer.Member(name).String(value); } private static void Member(JsonTextWriter writer, string name, NameValueCollection collection) { Debug.Assert(writer != null); Debug.AssertStringNotEmpty(name); // // Bail out early if the collection is null or empty. // if (collection == null || collection.Count == 0) return; // // Save the depth, which we'll use to lazily emit the collection. // That is, if we find that there is nothing useful in it, then // we could simply avoid emitting anything. // int depth = writer.Depth; // // For each key, we get all associated values and loop through // twice. The first time round, we count strings that are // neither null nor empty. If none are found then the key is // skipped. Otherwise, second time round, we encode // strings that are neither null nor empty. If only such string // exists for a key then it is written directly, otherwise // multiple strings are naturally wrapped in an array. // foreach (string key in collection.Keys) { string[] values = collection.GetValues(key); if (values == null || values.Length == 0) continue; int count = 0; // Strings neither null nor empty. for (int i = 0; i < values.Length; i++) { string value = values[i]; if (value != null && value.Length > 0) count++; } if (count == 0) // None? continue; // Skip key // // There is at least one value so now we emit the key. // Before doing that, we check if the collection member // was ever started. If not, this would be a good time. // if (depth == writer.Depth) { writer.Member(name); writer.Object(); } writer.Member(key); if (count > 1) writer.Array(); // Wrap multiples in an array for (int i = 0; i < values.Length; i++) { string value = values[i]; if (value != null && value.Length > 0) writer.String(value); } if (count > 1) writer.Pop(); // Close multiples array } // // If we are deeper than when we began then the collection was // started so we terminate it here. // if (writer.Depth > depth) writer.Pop(); } private ErrorJson() { throw new NotSupportedException(); } } }
using VkApi.Wrapper.Objects; using VkApi.Wrapper.Responses; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace VkApi.Wrapper.Methods { public class Stories { private readonly Vkontakte _vkontakte; internal Stories(Vkontakte vkontakte) => _vkontakte = vkontakte; ///<summary> /// Allows to hide stories from chosen sources from current user's feed. ///</summary> public Task<BaseOkResponse> BanOwner(int[] ownersIds = null) { var parameters = new Dictionary<string, string>(); if (ownersIds != null) parameters.Add("owners_ids", ownersIds.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("stories.banOwner", parameters); } ///<summary> /// Allows to delete story. ///</summary> public Task<BaseOkResponse> Delete(int? ownerId = null, int? storyId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (storyId != null) parameters.Add("story_id", storyId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("stories.delete", parameters); } ///<summary> /// Returns stories available for current user. ///</summary> public Task<StoriesGetV5113Response> Get(int? ownerId = null, Boolean? extended = null, BaseUserGroupFields[] fields = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<StoriesGetV5113Response>("stories.get", parameters); } ///<summary> /// Returns list of sources hidden from current user's feed. ///</summary> public Task<StoriesGetBannedResponse> GetBanned(Boolean? extended = null, BaseUserGroupFields[] fields = null) { var parameters = new Dictionary<string, string>(); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<StoriesGetBannedResponse>("stories.getBanned", parameters); } ///<summary> /// Returns story by its ID. ///</summary> public Task<StoriesGetByIdResponse> GetById(String[] stories = null, Boolean? extended = null, BaseUserGroupFields[] fields = null) { var parameters = new Dictionary<string, string>(); if (stories != null) parameters.Add("stories", stories.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<StoriesGetByIdResponse>("stories.getById", parameters); } ///<summary> /// Returns URL for uploading a story with photo. ///</summary> public Task<StoriesGetPhotoUploadServerResponse> GetPhotoUploadServer(Boolean? addToNews = null, int[] userIds = null, String replyToStory = null, String linkText = null, String linkUrl = null, int? groupId = null, String clickableStickers = null) { var parameters = new Dictionary<string, string>(); if (addToNews != null) parameters.Add("add_to_news", addToNews.ToApiString()); if (userIds != null) parameters.Add("user_ids", userIds.ToApiString()); if (replyToStory != null) parameters.Add("reply_to_story", replyToStory.ToApiString()); if (linkText != null) parameters.Add("link_text", linkText.ToApiString()); if (linkUrl != null) parameters.Add("link_url", linkUrl.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (clickableStickers != null) parameters.Add("clickable_stickers", clickableStickers.ToApiString()); return _vkontakte.RequestAsync<StoriesGetPhotoUploadServerResponse>("stories.getPhotoUploadServer", parameters); } ///<summary> /// Returns replies to the story. ///</summary> public Task<StoriesGetV5113Response> GetReplies(int? ownerId = null, int? storyId = null, String accessKey = null, Boolean? extended = null, BaseUserGroupFields[] fields = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (storyId != null) parameters.Add("story_id", storyId.ToApiString()); if (accessKey != null) parameters.Add("access_key", accessKey.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<StoriesGetV5113Response>("stories.getReplies", parameters); } ///<summary> /// Returns stories available for current user. ///</summary> public Task<StoriesStoryStats> GetStats(int? ownerId = null, int? storyId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (storyId != null) parameters.Add("story_id", storyId.ToApiString()); return _vkontakte.RequestAsync<StoriesStoryStats>("stories.getStats", parameters); } ///<summary> /// Allows to receive URL for uploading story with video. ///</summary> public Task<StoriesGetVideoUploadServerResponse> GetVideoUploadServer(Boolean? addToNews = null, int[] userIds = null, String replyToStory = null, String linkText = null, String linkUrl = null, int? groupId = null, String clickableStickers = null) { var parameters = new Dictionary<string, string>(); if (addToNews != null) parameters.Add("add_to_news", addToNews.ToApiString()); if (userIds != null) parameters.Add("user_ids", userIds.ToApiString()); if (replyToStory != null) parameters.Add("reply_to_story", replyToStory.ToApiString()); if (linkText != null) parameters.Add("link_text", linkText.ToApiString()); if (linkUrl != null) parameters.Add("link_url", linkUrl.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (clickableStickers != null) parameters.Add("clickable_stickers", clickableStickers.ToApiString()); return _vkontakte.RequestAsync<StoriesGetVideoUploadServerResponse>("stories.getVideoUploadServer", parameters); } ///<summary> /// Returns a list of story viewers. ///</summary> public Task<StoriesGetViewersExtendedV5115Response> GetViewers(int? ownerId = null, int? storyId = null, int? count = null, int? offset = null, Boolean? extended = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (storyId != null) parameters.Add("story_id", storyId.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); return _vkontakte.RequestAsync<StoriesGetViewersExtendedV5115Response>("stories.getViewers", parameters); } ///<summary> /// Hides all replies in the last 24 hours from the user to current user's stories. ///</summary> public Task<BaseOkResponse> HideAllReplies(int? ownerId = null, int? groupId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("stories.hideAllReplies", parameters); } ///<summary> /// Hides the reply to the current user's story. ///</summary> public Task<BaseOkResponse> HideReply(int? ownerId = null, int? storyId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (storyId != null) parameters.Add("story_id", storyId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("stories.hideReply", parameters); } ///<summary> /// Allows to show stories from hidden sources in current user's feed. ///</summary> public Task<BaseOkResponse> UnbanOwner(int[] ownersIds = null) { var parameters = new Dictionary<string, string>(); if (ownersIds != null) parameters.Add("owners_ids", ownersIds.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("stories.unbanOwner", parameters); } } }
// Copyright 2020 The Tilt Brush 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 UnityEngine; namespace TiltBrush { /// SliceBrush gives each control point a quad whose normal is the direction /// of motion. The quad has uses 3 texture coordinates. U and V have the /// standard mapping from (0,0) to (1,1). W is the length in meters along the /// stroke. /// /// The curve ignores pointer orientation (except for the first knot); it /// is framed to minimize twist. class SliceBrush : GeometryBrush { const float M2U = App.METERS_TO_UNITS; const float U2M = App.UNITS_TO_METERS; const float TWOPI = 2 * Mathf.PI; const float kMinimumMove_PS = 5e-4f * M2U; const ushort kVertsInQuad = 4; const float kSolidMinLengthMeters_PS = 0.0001f; const float kSolidAspectRatio = 0.2f; public SliceBrush() : base(bCanBatch: true, upperBoundVertsPerKnot: kVertsInQuad * 2, bDoubleSided: true) { } // // GeometryBrush API // protected override void InitBrush(BrushDescriptor desc, TrTransform localPointerXf) { base.InitBrush(desc, localPointerXf); m_geometry.Layout = GetVertexLayout(desc); } override public GeometryPool.VertexLayout GetVertexLayout(BrushDescriptor desc) { return new GeometryPool.VertexLayout { uv0Size = 3, bUseNormals = true, bUseColors = true, bUseTangents = false }; } override public float GetSpawnInterval(float pressure01) { return kSolidMinLengthMeters_PS * App.METERS_TO_UNITS * POINTER_TO_LOCAL + (PressuredSize(pressure01) * kSolidAspectRatio); } override protected void ControlPointsChanged(int iKnot0) { // Updating a control point affects geometry generated by previous knot // (if there is any). The HasGeometry check is not a micro-optimization: // it also keeps us from backing up past knot 0. int start = (m_knots[iKnot0 - 1].HasGeometry) ? iKnot0 - 1 : iKnot0; // Frames knots, determines how much geometry each knot should get OnChanged_FrameKnots(start); OnChanged_MakeGeometry(start); ResizeGeometry(); } // This approximates parallel transport. static Quaternion ComputeMinimalRotationFrame( Vector3 nTangent, Quaternion qPrevFrame) { Vector3 nPrevTangent = qPrevFrame * Vector3.forward; Quaternion minimal = Quaternion.FromToRotation(nPrevTangent, nTangent); return minimal * qPrevFrame; } // Fills in any knot data needed for geometry generation. // - fill in length, qFrame // - calculate strip-break points void OnChanged_FrameKnots(int iKnot0) { Knot prev = m_knots[iKnot0-1]; for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { Knot cur = m_knots[iKnot]; bool shouldBreak = false; Vector3 vMove = cur.point.m_Pos - prev.point.m_Pos; cur.length = vMove.magnitude; if (cur.length < kMinimumMove_PS * POINTER_TO_LOCAL) { shouldBreak = true; } else { Vector3 nTangent = vMove / cur.length; if (prev.HasGeometry) { cur.qFrame = ComputeMinimalRotationFrame(nTangent, prev.qFrame); } else { Vector3 nRight, nUp; // No previous orientation; compute a reasonable starting point ComputeSurfaceFrameNew(Vector3.zero, nTangent, cur.point.m_Orient, out nRight, out nUp); cur.qFrame = Quaternion.LookRotation(nTangent, nUp); } } if (shouldBreak) { cur.qFrame = new Quaternion(0,0,0,0); } // Just mark whether or not the strip is broken // tri/vert allocation will happen next pass cur.nTri = cur.nVert = (ushort)(shouldBreak ? 0 : 1); m_knots[iKnot] = cur; prev = cur; } } // Textures are laid out so u goes along the strip, // and v goes across the strip (from left to right) void OnChanged_MakeGeometry(int iKnot0) { // Invariant: there is a previous knot. Knot prev = m_knots[iKnot0-1]; for (int iKnot = iKnot0; iKnot < m_knots.Count; ++iKnot) { // Invariant: all of prev's geometry (if any) is correct and up-to-date. // Thus, there is no need to modify anything shared with prev. Knot cur = m_knots[iKnot]; cur.iTri = prev.iTri + prev.nTri; cur.iVert = (ushort)(prev.iVert + prev.nVert); if (cur.HasGeometry) { cur.nVert = cur.nTri = 0; Vector3 rt = cur.qFrame * Vector3.right; Vector3 up = cur.qFrame * Vector3.up; Vector3 fwd = cur.qFrame * Vector3.forward; bool isStart = !prev.HasGeometry; // Verts, back half float w0; if (isStart) { float halfSize = PressuredSize(prev.smoothedPressure) * .5f; w0 = 0; MakeQuad(ref cur, prev.point.m_Pos, halfSize, up, rt, fwd, w0); } else { cur.iVert -= 4; cur.nVert += 4; w0 = m_geometry.m_Texcoord0.v3[cur.iVert].z; } // Verts, front half { float halfSize = PressuredSize(cur.smoothedPressure) * .5f; float w1 = w0 + cur.length * U2M; MakeQuad(ref cur, cur.point.m_Pos, halfSize, up, rt, fwd, w1); } } m_knots[iKnot] = cur; prev = cur; } } void MakeQuad( ref Knot k, Vector3 center, float halfSize, Vector3 up, Vector3 rt, Vector3 fwd, float w) { up *= halfSize; rt *= halfSize; // Clockwise looking down the knots // tangent is in u direction AppendVert(ref k, center - rt - up, fwd, rt, 0, 0, w); AppendVert(ref k, center - rt + up, fwd, rt, 0, 1, w); AppendVert(ref k, center + rt + up, fwd, rt, 1, 1, w); AppendVert(ref k, center + rt - up, fwd, rt, 1, 0, w); AppendTri(ref k, 0, 1, 2); AppendTri(ref k, 2, 3, 0); } /// Resizes arrays if necessary, appends data, mutates knot's vtx count void AppendVert(ref Knot k, Vector3 pos, Vector3 n, Vector3 tan, float u, float v, float w) { Color32 color = m_Color; color.a = 255; // Vector4 tan4 = tan; // tan4.w = 1; Vector3 uvw = new Vector3(u, v, w); int i = k.iVert + k.nVert++; if (i == m_geometry.m_Vertices.Count) { m_geometry.m_Vertices .Add(pos); m_geometry.m_Colors.Add(color); m_geometry.m_Normals .Add(n); //m_geometry.m_Tangents .Add(tan4); m_geometry.m_Texcoord0.v3.Add(uvw); } else { m_geometry.m_Vertices[i] = pos; m_geometry.m_Colors[i] = color; m_geometry.m_Normals[i] = n; //m_geometry.m_Tangents[i] = tan4; m_geometry.m_Texcoord0.v3[i] = uvw; } } void AppendTri(ref Knot k, int t0, int t1, int t2) { int i = (k.iTri + k.nTri++) * 3; if (i == m_geometry.m_Tris.Count) { m_geometry.m_Tris.Add(k.iVert + t0); m_geometry.m_Tris.Add(k.iVert + t2); m_geometry.m_Tris.Add(k.iVert + t1); } else { m_geometry.m_Tris[i + 0] = k.iVert + t0; m_geometry.m_Tris[i + 1] = k.iVert + t2; m_geometry.m_Tris[i + 2] = k.iVert + t1; } } bool IsPenultimate(int iKnot) { return (iKnot+1 == m_knots.Count || !m_knots[iKnot+1].HasGeometry); } } } // namespace TiltBrush
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the LabAlarmaScreening class. /// </summary> [Serializable] public partial class LabAlarmaScreeningCollection : ActiveList<LabAlarmaScreening, LabAlarmaScreeningCollection> { public LabAlarmaScreeningCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>LabAlarmaScreeningCollection</returns> public LabAlarmaScreeningCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { LabAlarmaScreening o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the LAB_AlarmaScreening table. /// </summary> [Serializable] public partial class LabAlarmaScreening : ActiveRecord<LabAlarmaScreening>, IActiveRecord { #region .ctors and Default Settings public LabAlarmaScreening() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public LabAlarmaScreening(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public LabAlarmaScreening(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public LabAlarmaScreening(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("LAB_AlarmaScreening", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAlarmaScreening = new TableSchema.TableColumn(schema); colvarIdAlarmaScreening.ColumnName = "idAlarmaScreening"; colvarIdAlarmaScreening.DataType = DbType.Int32; colvarIdAlarmaScreening.MaxLength = 0; colvarIdAlarmaScreening.AutoIncrement = true; colvarIdAlarmaScreening.IsNullable = false; colvarIdAlarmaScreening.IsPrimaryKey = true; colvarIdAlarmaScreening.IsForeignKey = false; colvarIdAlarmaScreening.IsReadOnly = false; colvarIdAlarmaScreening.DefaultSetting = @""; colvarIdAlarmaScreening.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdAlarmaScreening); TableSchema.TableColumn colvarIdSolicitudScreening = new TableSchema.TableColumn(schema); colvarIdSolicitudScreening.ColumnName = "idSolicitudScreening"; colvarIdSolicitudScreening.DataType = DbType.Int32; colvarIdSolicitudScreening.MaxLength = 0; colvarIdSolicitudScreening.AutoIncrement = false; colvarIdSolicitudScreening.IsNullable = false; colvarIdSolicitudScreening.IsPrimaryKey = false; colvarIdSolicitudScreening.IsForeignKey = true; colvarIdSolicitudScreening.IsReadOnly = false; colvarIdSolicitudScreening.DefaultSetting = @""; colvarIdSolicitudScreening.ForeignKeyTableName = "LAB_SolicitudScreening"; schema.Columns.Add(colvarIdSolicitudScreening); TableSchema.TableColumn colvarDescripcion = new TableSchema.TableColumn(schema); colvarDescripcion.ColumnName = "descripcion"; colvarDescripcion.DataType = DbType.String; colvarDescripcion.MaxLength = 500; colvarDescripcion.AutoIncrement = false; colvarDescripcion.IsNullable = false; colvarDescripcion.IsPrimaryKey = false; colvarDescripcion.IsForeignKey = false; colvarDescripcion.IsReadOnly = false; colvarDescripcion.DefaultSetting = @""; colvarDescripcion.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescripcion); TableSchema.TableColumn colvarIdUsuarioRegistro = new TableSchema.TableColumn(schema); colvarIdUsuarioRegistro.ColumnName = "idUsuarioRegistro"; colvarIdUsuarioRegistro.DataType = DbType.Int32; colvarIdUsuarioRegistro.MaxLength = 0; colvarIdUsuarioRegistro.AutoIncrement = false; colvarIdUsuarioRegistro.IsNullable = false; colvarIdUsuarioRegistro.IsPrimaryKey = false; colvarIdUsuarioRegistro.IsForeignKey = false; colvarIdUsuarioRegistro.IsReadOnly = false; colvarIdUsuarioRegistro.DefaultSetting = @""; colvarIdUsuarioRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdUsuarioRegistro); TableSchema.TableColumn colvarFechaRegistro = new TableSchema.TableColumn(schema); colvarFechaRegistro.ColumnName = "fechaRegistro"; colvarFechaRegistro.DataType = DbType.DateTime; colvarFechaRegistro.MaxLength = 0; colvarFechaRegistro.AutoIncrement = false; colvarFechaRegistro.IsNullable = false; colvarFechaRegistro.IsPrimaryKey = false; colvarFechaRegistro.IsForeignKey = false; colvarFechaRegistro.IsReadOnly = false; colvarFechaRegistro.DefaultSetting = @""; colvarFechaRegistro.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaRegistro); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("LAB_AlarmaScreening",schema); } } #endregion #region Props [XmlAttribute("IdAlarmaScreening")] [Bindable(true)] public int IdAlarmaScreening { get { return GetColumnValue<int>(Columns.IdAlarmaScreening); } set { SetColumnValue(Columns.IdAlarmaScreening, value); } } [XmlAttribute("IdSolicitudScreening")] [Bindable(true)] public int IdSolicitudScreening { get { return GetColumnValue<int>(Columns.IdSolicitudScreening); } set { SetColumnValue(Columns.IdSolicitudScreening, value); } } [XmlAttribute("Descripcion")] [Bindable(true)] public string Descripcion { get { return GetColumnValue<string>(Columns.Descripcion); } set { SetColumnValue(Columns.Descripcion, value); } } [XmlAttribute("IdUsuarioRegistro")] [Bindable(true)] public int IdUsuarioRegistro { get { return GetColumnValue<int>(Columns.IdUsuarioRegistro); } set { SetColumnValue(Columns.IdUsuarioRegistro, value); } } [XmlAttribute("FechaRegistro")] [Bindable(true)] public DateTime FechaRegistro { get { return GetColumnValue<DateTime>(Columns.FechaRegistro); } set { SetColumnValue(Columns.FechaRegistro, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a LabSolicitudScreening ActiveRecord object related to this LabAlarmaScreening /// /// </summary> public DalSic.LabSolicitudScreening LabSolicitudScreening { get { return DalSic.LabSolicitudScreening.FetchByID(this.IdSolicitudScreening); } set { SetColumnValue("idSolicitudScreening", value.IdSolicitudScreening); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdSolicitudScreening,string varDescripcion,int varIdUsuarioRegistro,DateTime varFechaRegistro) { LabAlarmaScreening item = new LabAlarmaScreening(); item.IdSolicitudScreening = varIdSolicitudScreening; item.Descripcion = varDescripcion; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdAlarmaScreening,int varIdSolicitudScreening,string varDescripcion,int varIdUsuarioRegistro,DateTime varFechaRegistro) { LabAlarmaScreening item = new LabAlarmaScreening(); item.IdAlarmaScreening = varIdAlarmaScreening; item.IdSolicitudScreening = varIdSolicitudScreening; item.Descripcion = varDescripcion; item.IdUsuarioRegistro = varIdUsuarioRegistro; item.FechaRegistro = varFechaRegistro; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdAlarmaScreeningColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdSolicitudScreeningColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescripcionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn IdUsuarioRegistroColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaRegistroColumn { get { return Schema.Columns[4]; } } #endregion #region Columns Struct public struct Columns { public static string IdAlarmaScreening = @"idAlarmaScreening"; public static string IdSolicitudScreening = @"idSolicitudScreening"; public static string Descripcion = @"descripcion"; public static string IdUsuarioRegistro = @"idUsuarioRegistro"; public static string FechaRegistro = @"fechaRegistro"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
//! \file ImageDRG.cs //! \date Fri Aug 22 05:58:40 2014 //! \brief Digital Romance System image format implementation. // // Copyright (C) 2014-2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Compression; using GameRes.Utility; namespace GameRes.Formats.Ikura { internal class DgdMetaData : ImageMetaData { public bool IsEncrypted; } [Export(typeof(ImageFormat))] public class DrgFormat : ImageFormat { public override string Tag { get { return "DRG"; } } public override string Description { get { return "Digital Romance System image format"; } } public override uint Signature { get { return ~0x4c4c5546u; } } // 'FULL' public override bool CanWrite { get { return true; } } static readonly byte[] DefaultKey = { 0x4D, 0x39, 0x38, 0x31, 0x31, 0x31, 0x33, 0x4D }; // "M981113M" public DrgFormat () { Extensions = new string[] { "drg", "ggd", "dgd" }; Signatures = new uint[] { ~0x4c4c5546u, ~0x45555254u, ~0x48474948u }; } public override void Write (Stream file, ImageData image) { using (var writer = new Writer (file)) { writer.Pack (image.Bitmap); } } public override ImageMetaData ReadMetaData (IBinaryStream stream) { uint signature = ~stream.Signature; int bpp; switch (signature) { case 0x4c4c5546: /* fall through */ case 0x45555254: bpp = 24; break; case 0x48474948: bpp = 16; break; default: return null; } stream.Position = 4; uint width = stream.ReadUInt16(); uint height = stream.ReadUInt16(); return new DgdMetaData { Width = width, Height = height, BPP = bpp, // DGD extensions doesn't always mean encrypted contents XXX // IsEncrypted = stream.Name.HasExtension ("dgd"), IsEncrypted = false, }; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { PixelFormat format; if (24 == info.BPP) format = PixelFormats.Bgr24; else format = PixelFormats.Bgr565; file.Position = 8; var meta = (DgdMetaData)info; var input = file.AsStream; if (meta.IsEncrypted) input = OpenEcnryptedStream (input, DefaultKey); int stride = ((int)info.Width * info.BPP / 8 + 3) & ~3; var pixel_data = DecodeStream (input, stride*(int)info.Height); if (null == pixel_data) throw new InvalidFormatException(); return ImageData.Create (info, format, null, pixel_data, stride); } Stream OpenEcnryptedStream (Stream input, byte[] key) { if (key.Length != 8) input = new StreamRegion (input, 8, true); return new ByteStringEncryptedStream (input, key, true); } byte[] DecodeStream (Stream input, int pixel_count) { byte[] output = new byte[pixel_count]; for (int out_pos = 0; out_pos < output.Length; ) { int opcode = input.ReadByte(); if (-1 == opcode) break; int count, src_offset; int remaining = output.Length - out_pos; switch (opcode) { case 0: count = Math.Min (3 * input.ReadByte(), remaining); src_offset = out_pos - 3; if (count < 0 || src_offset < 0) return null; Binary.CopyOverlapped (output, src_offset, out_pos, count); break; case 1: count = Math.Min (3 * input.ReadByte(), remaining); src_offset = out_pos - 3 * input.ReadByte(); if (count < 0 || src_offset < 0 || src_offset == out_pos) return null; Binary.CopyOverlapped (output, src_offset, out_pos, count); break; case 2: { count = Math.Min (3 * input.ReadByte(), remaining); int off_lo = input.ReadByte(); int off_hi = input.ReadByte(); src_offset = out_pos - 3 * (off_hi << 8 | off_lo); if (count < 0 || src_offset < 0 || src_offset == out_pos) return null; Binary.CopyOverlapped (output, src_offset, out_pos, count); break; } case 3: count = Math.Min (3, remaining); src_offset = out_pos - 3 * input.ReadByte(); if (src_offset < 0 || src_offset == out_pos) return null; Buffer.BlockCopy (output, src_offset, output, out_pos, count); break; case 4: { count = Math.Min (3, remaining); int off_lo = input.ReadByte(); int off_hi = input.ReadByte(); src_offset = out_pos - 3 * (off_hi << 8 | off_lo); if (src_offset < 0 || src_offset == out_pos) return null; Buffer.BlockCopy (output, src_offset, output, out_pos, count); break; } default: count = Math.Min (3*(opcode - 4), remaining); input.Read (output, out_pos, count); break; } out_pos += count; } return output; } internal class Writer : IDisposable { BinaryWriter m_out; uint[] m_input; const int MaxWindowSize = 0xfffe; const int MaxMatchSize = 0xff; struct WindowPosition { public ushort Offset; public ushort Length; } public Writer (Stream output) { m_out = new BinaryWriter (output, Encoding.ASCII, true); } void WriteHeader (int width, int height) { m_out.Write (~0x4c4c5546u); m_out.Write ((ushort)width); m_out.Write ((ushort)height); } void PrepareInput (BitmapSource bitmap) { int width = bitmap.PixelWidth; int height = bitmap.PixelHeight; int pixels = width*height; m_input = new uint[pixels]; if (bitmap.Format != PixelFormats.Bgr32) { var converted_bitmap = new FormatConvertedBitmap(); converted_bitmap.BeginInit(); converted_bitmap.Source = bitmap; converted_bitmap.DestinationFormat = PixelFormats.Bgr32; converted_bitmap.EndInit(); bitmap = converted_bitmap; } unsafe { fixed (uint* buffer = m_input) { bitmap.CopyPixels (Int32Rect.Empty, (IntPtr)buffer, pixels*4, width*4); } } WriteHeader (width, height); } List<byte> m_buffer = new List<byte>(); int m_buffer_size; Dictionary<uint, SortedSet<int>> m_dict = new Dictionary<uint, SortedSet<int>> (MaxWindowSize); public void Pack (BitmapSource bitmap) { PrepareInput (bitmap); m_dict.Clear(); m_buffer.Clear(); m_buffer_size = 0; int last = m_input.Length; int current = 0; int win_begin = current; int win_end = current; while (current != last) { int new_win_end = current; int window_size = Math.Min (new_win_end - win_begin, MaxWindowSize); int new_win_begin = new_win_end - window_size; AdjustWindow (ref win_begin, ref win_end, new_win_begin, new_win_end); var win_pos = FindLongest (win_begin, win_end, current, last); if (win_pos.Length > 0) { Flush(); WritePos (win_pos, current - win_pos.Offset); current += win_pos.Length; } else { WritePixel (m_input[current++]); } } Flush(); } void AdjustWindow (ref int win_begin, ref int win_end, int new_begin, int new_end) { while (win_begin != new_begin) { var pixel = m_input[win_begin]; SortedSet<int> pos = m_dict[pixel]; pos.Remove (win_begin); if (0 == pos.Count) m_dict.Remove (pixel); ++win_begin; } while (win_end != new_end) { var pixel = m_input[win_end]; SortedSet<int> pos; if (!m_dict.TryGetValue (pixel, out pos)) { pos = new SortedSet<int>(); m_dict[pixel] = pos; } pos.Add (win_end); ++win_end; } } void WritePixel (uint pixel) { if (0xff-4 == m_buffer_size) Flush(); m_buffer.Add ((byte)pixel); m_buffer.Add ((byte)(pixel >> 8)); m_buffer.Add ((byte)(pixel >> 16)); ++m_buffer_size; } void Flush () { if (0 != m_buffer.Count) { m_out.Write ((byte)(m_buffer_size+4)); foreach (var b in m_buffer) m_out.Write (b); m_buffer.Clear(); m_buffer_size = 0; } } int Mismatch (int first1, int last1, int first2) { while (first1 != last1 && m_input[first1] == m_input[first2]) { ++first1; ++first2; } return first2; } WindowPosition FindLongest (int win_begin, int win_end, int buf_begin, int buf_end) { buf_end = Math.Min (buf_begin + MaxMatchSize, buf_end); WindowPosition pos = new WindowPosition { Offset = 0, Length = 0 }; if (win_begin == win_end) return pos; SortedSet<int> found; if (m_dict.TryGetValue (m_input[buf_begin], out found)) { foreach (var win_pos in found.Reverse()) { var match_end = Mismatch (buf_begin+1, buf_end, win_pos+1); int weight = match_end - win_pos; int distance = buf_begin - win_pos; if (weight > pos.Length) { pos.Offset = (ushort)distance; pos.Length = (ushort)weight; if (MaxMatchSize == weight) break; } } } return pos; } void WritePos (WindowPosition pos, int buf) { if (1 == pos.Offset) { uint pixel = m_input[buf]; if (1 == pos.Length || -1 == Array.FindIndex (m_input, buf+1, pos.Length-1, x => x != pixel)) { m_out.Write ((byte)0); m_out.Write ((byte)pos.Length); } else { m_out.Write ((byte)1); m_out.Write ((byte)pos.Length); m_out.Write ((byte)1); } } else if (1 == pos.Length) { if (pos.Offset < 0x100) { m_out.Write ((byte)3); m_out.Write ((byte)pos.Offset); } else { m_out.Write ((byte)4); m_out.Write (pos.Offset); } } else if (pos.Offset < 0x100) { m_out.Write ((byte)1); m_out.Write ((byte)pos.Length); m_out.Write ((byte)pos.Offset); } else { m_out.Write ((byte)2); m_out.Write ((byte)pos.Length); m_out.Write (pos.Offset); } } #region IDisposable Members bool disposed = false; public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (!disposed) { if (disposing) { m_out.Dispose(); } disposed = true; } } #endregion } } internal class GgdMetaData : ImageMetaData { public uint HeaderSize; public uint BitmapSize; public bool Flipped; } [Export(typeof(ImageFormat))] public class DrgIndexedFormat : ImageFormat { public override string Tag { get { return "GGD"; } } public override string Description { get { return "Digital Romance System indexed image format"; } } public override uint Signature { get { return ~0x47363532u; } } // '256G' public override ImageMetaData ReadMetaData (IBinaryStream file) { file.Position = 4; var info = new GgdMetaData { BPP = 8 }; info.HeaderSize = file.ReadUInt32(); info.Width = file.ReadUInt32(); int height = file.ReadInt32(); if (height < 0) { height = -height; info.Flipped = true; } info.Height = (uint)height; file.ReadInt64(); info.BitmapSize = file.ReadUInt32(); return info; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var meta = (GgdMetaData)info; file.Position = meta.HeaderSize + 4; var palette_data = new byte[0x400]; if (palette_data.Length != file.Read (palette_data, 0, palette_data.Length)) throw new InvalidFormatException(); var colors = new Color[256]; for (int i = 0; i < 256; ++i) { colors[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]); } file.Seek (4, SeekOrigin.Current); int input_size = (int)(file.Length - file.Position); using (var reader = new LzssReader (file.AsStream, input_size, (int)meta.BitmapSize)) { reader.Unpack(); var palette = new BitmapPalette (colors); int stride = ((int)meta.Width + 3) & ~3; return ImageData.Create (info, PixelFormats.Indexed8, palette, reader.Data, stride); } } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("DrgIndexedFormat.Write not implemented"); } } [Export(typeof(ImageFormat))] public class Gga0Format : ImageFormat { public override string Tag { get { return "GG2"; } } public override string Description { get { return "IKURA GDL image format"; } } public override uint Signature { get { return 0x30414747u; } } // 'GGA0' public Gga0Format () { Extensions = new string[] { "gg1", "gg2", "gg3", "gg0" }; } internal class GgaMetaData : ImageMetaData { public uint Flags; public uint HeaderSize; public uint CompSize; } public override void Write (Stream file, ImageData image) { throw new NotImplementedException ("GgaFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (24); if (!header.AsciiEqual ("GGA00000")) return null; return new GgaMetaData { Width = header.ToUInt16 (8), Height = header.ToUInt16 (10), BPP = header[14], Flags = header[15], HeaderSize = header.ToUInt32 (16), CompSize = header.ToUInt32 (20) }; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var meta = (GgaMetaData)info; file.Position = meta.HeaderSize; var pixel_data = DecodeStream (file, meta); PixelFormat format = 0 == (meta.Flags & 1) ? PixelFormats.Bgr32 : PixelFormats.Bgra32; return ImageData.Create (info, format, null, pixel_data); } byte[] DecodeStream (IBinaryStream input, GgaMetaData meta) { int dst = 0; var output = new byte[meta.Width*meta.Height*4]; var end_pos = input.Position + meta.CompSize; while (input.Position < end_pos) { int code = input.ReadByte(); switch (code) { case 0: { int src = dst - 4; int count = input.ReadByte() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 1: { int src = dst - 4; int count = input.ReadUInt16() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 2: { int l = input.ReadByte(); int src = dst - (l << 2); System.Buffer.BlockCopy (output, src, output, dst, 4); dst += 4; break; } case 3: { int l = input.ReadUInt16(); int src = dst - (l << 2); System.Buffer.BlockCopy (output, src, output, dst, 4); dst += 4; break; } case 4: { int l = input.ReadByte(); int src = dst - (l << 2); int count = input.ReadByte() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 5: { int l = input.ReadByte(); int src = dst - (l << 2); int count = input.ReadUInt16() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 6: { int l = input.ReadUInt16(); int src = dst - (l << 2); int count = input.ReadByte() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 7: { int l = input.ReadUInt16(); int src = dst - (l << 2); int count = input.ReadUInt16() * 4; Binary.CopyOverlapped (output, src, dst, count); dst += count; break; } case 8: { System.Buffer.BlockCopy (output, dst-4, output, dst, 4); dst += 4; break; } case 9: { int src = dst - (int)meta.Width * 4; System.Buffer.BlockCopy (output, src, output, dst, 4); dst += 4; break; } case 0x0a: { int src = dst - ((int)meta.Width * 4 + 4); System.Buffer.BlockCopy (output, src, output, dst, 4); dst += 4; break; } case 0x0b: { int src = dst - ((int)meta.Width * 4 - 4); System.Buffer.BlockCopy (output, src, output, dst, 4); dst += 4; break; } default: { int count = (code-11)*4; if (count != input.Read (output, dst, count)) throw new InvalidFormatException ("Unexpected end of input"); dst += count; break; } } } return output; } } }
// 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.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { internal static partial class ProcessManager { /// <summary>Gets whether the process with the specified ID is currently running.</summary> /// <param name="processId">The process ID.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId) { return IsProcessRunning(processId, "."); } /// <summary>Gets whether the process with the specified ID on the specified machine is currently running.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>true if the process is running; otherwise, false.</returns> public static bool IsProcessRunning(int processId, string machineName) { // Performance optimization for the local machine: // First try to OpenProcess by id, if valid handle is returned, the process is definitely running // Otherwise enumerate all processes and compare ids if (!IsRemoteMachine(machineName)) { using (SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, false, processId)) { if (!processHandle.IsInvalid) { return true; } } } return Array.IndexOf(GetProcessIds(machineName), processId) >= 0; } /// <summary>Gets the ProcessInfo for the specified process ID on the specified machine.</summary> /// <param name="processId">The process ID.</param> /// <param name="machineName">The machine name.</param> /// <returns>The ProcessInfo for the process if it could be found; otherwise, null.</returns> public static ProcessInfo GetProcessInfo(int processId, string machineName) { ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); foreach (ProcessInfo processInfo in processInfos) { if (processInfo.ProcessId == processId) { return processInfo; } } return null; } /// <summary>Gets process infos for each process on the specified machine.</summary> /// <param name="machineName">The target machine.</param> /// <returns>An array of process infos, one per found process.</returns> public static ProcessInfo[] GetProcessInfos(string machineName) { return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessInfos(machineName, true) : NtProcessInfoHelper.GetProcessInfos(); // Do not use performance counter for local machine } /// <summary>Gets the IDs of all processes on the specified machine.</summary> /// <param name="machineName">The machine to examine.</param> /// <returns>An array of process IDs from the specified machine.</returns> public static int[] GetProcessIds(string machineName) { // Due to the lack of support for EnumModules() on coresysserver, we rely // on PerformanceCounters to get the ProcessIds for both remote desktop // and the local machine, unlike Desktop on which we rely on PCs only for // remote machines. return IsRemoteMachine(machineName) ? NtProcessManager.GetProcessIds(machineName, true) : GetProcessIds(); } /// <summary>Gets the IDs of all processes on the current machine.</summary> public static int[] GetProcessIds() { return NtProcessManager.GetProcessIds(); } /// <summary>Gets the ID of a process from a handle to the process.</summary> /// <param name="processHandle">The handle.</param> /// <returns>The process ID.</returns> public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { return NtProcessManager.GetProcessIdFromHandle(processHandle); } /// <summary>Gets an array of module infos for the specified process.</summary> /// <param name="processId">The ID of the process whose modules should be enumerated.</param> /// <returns>The array of modules.</returns> public static ProcessModuleCollection GetModules(int processId) { return NtProcessManager.GetModules(processId); } /// <summary>Gets whether the named machine is remote or local.</summary> /// <param name="machineName">The machine name.</param> /// <returns>true if the machine is remote; false if it's local.</returns> public static bool IsRemoteMachine(string machineName) { if (machineName == null) throw new ArgumentNullException(nameof(machineName)); if (machineName.Length == 0) throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); string baseName; if (machineName.StartsWith("\\", StringComparison.Ordinal)) baseName = machineName.Substring(2); else baseName = machineName; if (baseName.Equals(".")) return false; if (String.Compare(Interop.Kernel32.GetComputerName(), baseName, StringComparison.OrdinalIgnoreCase) == 0) return false; return true; } public static IntPtr GetMainWindowHandle(int processId) { MainWindowFinder finder = new MainWindowFinder(); return finder.FindMainWindow(processId); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- static ProcessManager() { // In order to query information (OpenProcess) on some protected processes // like csrss, we need SeDebugPrivilege privilege. // After removing the dependency on Performance Counter, we don't have a chance // to run the code in CLR performance counter to ask for this privilege. // So we will try to get the privilege here. // We could fail if the user account doesn't have right to do this, but that's fair. Interop.Advapi32.LUID luid = new Interop.Advapi32.LUID(); if (!Interop.Advapi32.LookupPrivilegeValue(null, Interop.Advapi32.SeDebugPrivilege, out luid)) { return; } SafeTokenHandle tokenHandle = null; try { if (!Interop.Advapi32.OpenProcessToken( Interop.Kernel32.GetCurrentProcess(), Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out tokenHandle)) { return; } Interop.Advapi32.TokenPrivileges tp = new Interop.Advapi32.TokenPrivileges(); tp.Luid = luid; tp.Attributes = Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED; // AdjustTokenPrivileges can return true even if it didn't succeed (when ERROR_NOT_ALL_ASSIGNED is returned). Interop.Advapi32.AdjustTokenPrivileges(tokenHandle, false, tp, 0, IntPtr.Zero, IntPtr.Zero); } finally { if (tokenHandle != null) { tokenHandle.Dispose(); } } } public static SafeProcessHandle OpenProcess(int processId, int access, bool throwIfExited) { SafeProcessHandle processHandle = Interop.Kernel32.OpenProcess(access, false, processId); int result = Marshal.GetLastWin32Error(); if (!processHandle.IsInvalid) { return processHandle; } if (processId == 0) { throw new Win32Exception(5); } // If the handle is invalid because the process has exited, only throw an exception if throwIfExited is true. if (!IsProcessRunning(processId)) { if (throwIfExited) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, processId.ToString(CultureInfo.CurrentCulture))); } else { return SafeProcessHandle.InvalidHandle; } } throw new Win32Exception(result); } public static SafeThreadHandle OpenThread(int threadId, int access) { SafeThreadHandle threadHandle = Interop.Kernel32.OpenThread(access, false, threadId); int result = Marshal.GetLastWin32Error(); if (threadHandle.IsInvalid) { if (result == Interop.Errors.ERROR_INVALID_PARAMETER) throw new InvalidOperationException(SR.Format(SR.ThreadExited, threadId.ToString(CultureInfo.CurrentCulture))); throw new Win32Exception(result); } return threadHandle; } } /// <devdoc> /// This static class provides the process api for the WinNt platform. /// We use the performance counter api to query process and thread /// information. Module information is obtained using PSAPI. /// </devdoc> /// <internalonly/> internal static class NtProcessManager { private const int ProcessPerfCounterId = 230; private const int ThreadPerfCounterId = 232; private const string PerfCounterQueryString = "230 232"; internal const int IdleProcessID = 0; private static readonly Dictionary<String, ValueId> s_valueIds = new Dictionary<string, ValueId>(19) { { "Pool Paged Bytes", ValueId.PoolPagedBytes }, { "Pool Nonpaged Bytes", ValueId.PoolNonpagedBytes }, { "Elapsed Time", ValueId.ElapsedTime }, { "Virtual Bytes Peak", ValueId.VirtualBytesPeak }, { "Virtual Bytes", ValueId.VirtualBytes }, { "Private Bytes", ValueId.PrivateBytes }, { "Page File Bytes", ValueId.PageFileBytes }, { "Page File Bytes Peak", ValueId.PageFileBytesPeak }, { "Working Set Peak", ValueId.WorkingSetPeak }, { "Working Set", ValueId.WorkingSet }, { "ID Thread", ValueId.ThreadId }, { "ID Process", ValueId.ProcessId }, { "Priority Base", ValueId.BasePriority }, { "Priority Current", ValueId.CurrentPriority }, { "% User Time", ValueId.UserTime }, { "% Privileged Time", ValueId.PrivilegedTime }, { "Start Address", ValueId.StartAddress }, { "Thread State", ValueId.ThreadState }, { "Thread Wait Reason", ValueId.ThreadWaitReason } }; internal static int SystemProcessID { get { const int systemProcessIDOnXP = 4; return systemProcessIDOnXP; } } public static int[] GetProcessIds(string machineName, bool isRemoteMachine) { ProcessInfo[] infos = GetProcessInfos(machineName, isRemoteMachine); int[] ids = new int[infos.Length]; for (int i = 0; i < infos.Length; i++) ids[i] = infos[i].ProcessId; return ids; } public static int[] GetProcessIds() { int[] processIds = new int[256]; int size; for (; ; ) { if (!Interop.Kernel32.EnumProcesses(processIds, processIds.Length * 4, out size)) throw new Win32Exception(); if (size == processIds.Length * 4) { processIds = new int[processIds.Length * 2]; continue; } break; } int[] ids = new int[size / 4]; Array.Copy(processIds, 0, ids, 0, ids.Length); return ids; } public static ProcessModuleCollection GetModules(int processId) { return GetModules(processId, firstModuleOnly: false); } public static ProcessModule GetFirstModule(int processId) { ProcessModuleCollection modules = GetModules(processId, firstModuleOnly: true); return modules.Count == 0 ? null : modules[0]; } private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly) { // preserving Everett behavior. if (processId == SystemProcessID || processId == IdleProcessID) { // system process and idle process doesn't have any modules throw new Win32Exception(Interop.Errors.EFail, SR.EnumProcessModuleFailed); } SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle; try { processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true); IntPtr[] moduleHandles = new IntPtr[64]; GCHandle moduleHandlesArrayHandle = new GCHandle(); int moduleCount = 0; for (; ; ) { bool enumResult = false; try { moduleHandlesArrayHandle = GCHandle.Alloc(moduleHandles, GCHandleType.Pinned); enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); // The API we need to use to enumerate process modules differs on two factors: // 1) If our process is running in WOW64. // 2) The bitness of the process we wish to introspect. // // If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process // we can call psapi!EnumProcessModules. // // If we are running in WOW64 and we want to inspect the modules of a 64 bit process then // psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't // do the enumeration at all. So we'll detect this case and bail out. // // Also, EnumProcessModules is not a reliable method to get the modules for a process. // If OS loader is touching module information, this method might fail and copy part of the data. // This is no easy solution to this problem. The only reliable way to fix this is to // suspend all the threads in target process. Of course we don't want to do this in Process class. // So we just to try avoid the race by calling the same method 50 (an arbitrary number) times. // if (!enumResult) { bool sourceProcessIsWow64 = false; bool targetProcessIsWow64 = false; SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle; try { hCurProcess = ProcessManager.OpenProcess(unchecked((int)Interop.Kernel32.GetCurrentProcessId()), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true); bool wow64Ret; wow64Ret = Interop.Kernel32.IsWow64Process(hCurProcess, ref sourceProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } wow64Ret = Interop.Kernel32.IsWow64Process(processHandle, ref targetProcessIsWow64); if (!wow64Ret) { throw new Win32Exception(); } if (sourceProcessIsWow64 && !targetProcessIsWow64) { // Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user. throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow); } } finally { if (hCurProcess != SafeProcessHandle.InvalidHandle) { hCurProcess.Dispose(); } } // If the failure wasn't due to Wow64, try again. for (int i = 0; i < 50; i++) { enumResult = Interop.Kernel32.EnumProcessModules(processHandle, moduleHandlesArrayHandle.AddrOfPinnedObject(), moduleHandles.Length * IntPtr.Size, ref moduleCount); if (enumResult) { break; } Thread.Sleep(1); } } } finally { moduleHandlesArrayHandle.Free(); } if (!enumResult) { throw new Win32Exception(); } moduleCount /= IntPtr.Size; if (moduleCount <= moduleHandles.Length) break; moduleHandles = new IntPtr[moduleHandles.Length * 2]; } var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : moduleCount); char[] chars = new char[1024]; for (int i = 0; i < moduleCount; i++) { if (i > 0) { // If the user is only interested in the main module, break now. // This avoid some waste of time. In addition, if the application unloads a DLL // we will not get an exception. if (firstModuleOnly) { break; } } IntPtr moduleHandle = moduleHandles[i]; Interop.Kernel32.NtModuleInfo ntModuleInfo; if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo)) { HandleError(); continue; } var module = new ProcessModule() { ModuleMemorySize = ntModuleInfo.SizeOfImage, EntryPointAddress = ntModuleInfo.EntryPoint, BaseAddress = ntModuleInfo.BaseOfDll }; int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.ModuleName = new string(chars, 0, length); length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length); if (length == 0) { HandleError(); continue; } module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ? new string(chars, 4, length - 4) : new string(chars, 0, length); modules.Add(module); } return modules; } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "Process - CloseHandle(process)"); #endif if (!processHandle.IsInvalid) { processHandle.Dispose(); } } } private static void HandleError() { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_PARTIAL_COPY: // It's possible that another thread caused this module to become // unloaded (e.g FreeLibrary was called on the module). Ignore it and // move on. break; default: throw new Win32Exception(lastError); } } public static int GetProcessIdFromHandle(SafeProcessHandle processHandle) { Interop.NtDll.NtProcessBasicInfo info = new Interop.NtDll.NtProcessBasicInfo(); int status = Interop.NtDll.NtQueryInformationProcess(processHandle, Interop.NtDll.NtQueryProcessBasicInfo, info, (int)Marshal.SizeOf(info), null); if (status != 0) { throw new InvalidOperationException(SR.CantGetProcessId, new Win32Exception(status)); } // We should change the signature of this function and ID property in process class. return info.UniqueProcessId.ToInt32(); } public static ProcessInfo[] GetProcessInfos(string machineName, bool isRemoteMachine) { PerformanceCounterLib library = null; try { library = PerformanceCounterLib.GetPerformanceCounterLib(machineName, new CultureInfo("en")); return GetProcessInfos(library); } catch (Exception e) { if (isRemoteMachine) { throw new InvalidOperationException(SR.CouldntConnectToRemoteMachine, e); } else { throw e; } } // We don't want to call library.Close() here because that would cause us to unload all of the perflibs. // On the next call to GetProcessInfos, we'd have to load them all up again, which is SLOW! } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library) { ProcessInfo[] processInfos; int retryCount = 5; do { try { byte[] dataPtr = library.GetPerformanceData(PerfCounterQueryString); processInfos = GetProcessInfos(library, ProcessPerfCounterId, ThreadPerfCounterId, dataPtr); } catch (Exception e) { throw new InvalidOperationException(SR.CouldntGetProcessInfos, e); } --retryCount; } while (processInfos.Length == 0 && retryCount != 0); if (processInfos.Length == 0) throw new InvalidOperationException(SR.ProcessDisabled); return processInfos; } static ProcessInfo[] GetProcessInfos(PerformanceCounterLib library, int processIndex, int threadIndex, byte[] data) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos()"); #endif Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(); List<ThreadInfo> threadInfos = new List<ThreadInfo>(); GCHandle dataHandle = new GCHandle(); try { dataHandle = GCHandle.Alloc(data, GCHandleType.Pinned); IntPtr dataBlockPtr = dataHandle.AddrOfPinnedObject(); Interop.Advapi32.PERF_DATA_BLOCK dataBlock = new Interop.Advapi32.PERF_DATA_BLOCK(); Marshal.PtrToStructure(dataBlockPtr, dataBlock); IntPtr typePtr = (IntPtr)((long)dataBlockPtr + dataBlock.HeaderLength); Interop.Advapi32.PERF_INSTANCE_DEFINITION instance = new Interop.Advapi32.PERF_INSTANCE_DEFINITION(); Interop.Advapi32.PERF_COUNTER_BLOCK counterBlock = new Interop.Advapi32.PERF_COUNTER_BLOCK(); for (int i = 0; i < dataBlock.NumObjectTypes; i++) { Interop.Advapi32.PERF_OBJECT_TYPE type = new Interop.Advapi32.PERF_OBJECT_TYPE(); Marshal.PtrToStructure(typePtr, type); IntPtr instancePtr = (IntPtr)((long)typePtr + type.DefinitionLength); IntPtr counterPtr = (IntPtr)((long)typePtr + type.HeaderLength); List<Interop.Advapi32.PERF_COUNTER_DEFINITION> counterList = new List<Interop.Advapi32.PERF_COUNTER_DEFINITION>(); for (int j = 0; j < type.NumCounters; j++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = new Interop.Advapi32.PERF_COUNTER_DEFINITION(); Marshal.PtrToStructure(counterPtr, counter); string counterName = library.GetCounterName(counter.CounterNameTitleIndex); if (type.ObjectNameTitleIndex == processIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); else if (type.ObjectNameTitleIndex == threadIndex) counter.CounterNameTitlePtr = (int)GetValueId(counterName); counterList.Add(counter); counterPtr = (IntPtr)((long)counterPtr + counter.ByteLength); } Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters = counterList.ToArray(); for (int j = 0; j < type.NumInstances; j++) { Marshal.PtrToStructure(instancePtr, instance); IntPtr namePtr = (IntPtr)((long)instancePtr + instance.NameOffset); string instanceName = Marshal.PtrToStringUni(namePtr); if (instanceName.Equals("_Total")) continue; IntPtr counterBlockPtr = (IntPtr)((long)instancePtr + instance.ByteLength); Marshal.PtrToStructure(counterBlockPtr, counterBlock); if (type.ObjectNameTitleIndex == processIndex) { ProcessInfo processInfo = GetProcessInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (processInfo.ProcessId == 0 && string.Compare(instanceName, "Idle", StringComparison.OrdinalIgnoreCase) != 0) { // Sometimes we'll get a process structure that is not completely filled in. // We can catch some of these by looking for non-"idle" processes that have id 0 // and ignoring those. #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a non-idle process with id 0; ignoring."); #endif } else { if (processInfos.ContainsKey(processInfo.ProcessId)) { // We've found two entries in the perfcounters that claim to be the // same process. We throw an exception. Is this really going to be // helpful to the user? Should we just ignore? #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - found a duplicate process id"); #endif } else { // the performance counters keep a 15 character prefix of the exe name, and then delete the ".exe", // if it's in the first 15. The problem is that sometimes that will leave us with part of ".exe" // at the end. If instanceName ends in ".", ".e", or ".ex" we remove it. string processName = instanceName; if (processName.Length == 15) { if (instanceName.EndsWith(".", StringComparison.Ordinal)) processName = instanceName.Substring(0, 14); else if (instanceName.EndsWith(".e", StringComparison.Ordinal)) processName = instanceName.Substring(0, 13); else if (instanceName.EndsWith(".ex", StringComparison.Ordinal)) processName = instanceName.Substring(0, 12); } processInfo.ProcessName = processName; processInfos.Add(processInfo.ProcessId, processInfo); } } } else if (type.ObjectNameTitleIndex == threadIndex) { ThreadInfo threadInfo = GetThreadInfo(type, (IntPtr)((long)instancePtr + instance.ByteLength), counters); if (threadInfo._threadId != 0) threadInfos.Add(threadInfo); } instancePtr = (IntPtr)((long)instancePtr + instance.ByteLength + counterBlock.ByteLength); } typePtr = (IntPtr)((long)typePtr + type.TotalByteLength); } } finally { if (dataHandle.IsAllocated) dataHandle.Free(); } for (int i = 0; i < threadInfos.Count; i++) { ThreadInfo threadInfo = (ThreadInfo)threadInfos[i]; ProcessInfo processInfo; if (processInfos.TryGetValue(threadInfo._processId, out processInfo)) { processInfo._threadInfoList.Add(threadInfo); } } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } static ThreadInfo GetThreadInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ThreadInfo threadInfo = new ThreadInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: threadInfo._processId = (int)value; break; case ValueId.ThreadId: threadInfo._threadId = (ulong)value; break; case ValueId.BasePriority: threadInfo._basePriority = (int)value; break; case ValueId.CurrentPriority: threadInfo._currentPriority = (int)value; break; case ValueId.StartAddress: threadInfo._startAddress = (IntPtr)value; break; case ValueId.ThreadState: threadInfo._threadState = (ThreadState)value; break; case ValueId.ThreadWaitReason: threadInfo._threadWaitReason = GetThreadWaitReason((int)value); break; } } return threadInfo; } internal static ThreadWaitReason GetThreadWaitReason(int value) { switch (value) { case 0: case 7: return ThreadWaitReason.Executive; case 1: case 8: return ThreadWaitReason.FreePage; case 2: case 9: return ThreadWaitReason.PageIn; case 3: case 10: return ThreadWaitReason.SystemAllocation; case 4: case 11: return ThreadWaitReason.ExecutionDelay; case 5: case 12: return ThreadWaitReason.Suspended; case 6: case 13: return ThreadWaitReason.UserRequest; case 14: return ThreadWaitReason.EventPairHigh; ; case 15: return ThreadWaitReason.EventPairLow; case 16: return ThreadWaitReason.LpcReceive; case 17: return ThreadWaitReason.LpcReply; case 18: return ThreadWaitReason.VirtualMemory; case 19: return ThreadWaitReason.PageOut; default: return ThreadWaitReason.Unknown; } } static ProcessInfo GetProcessInfo(Interop.Advapi32.PERF_OBJECT_TYPE type, IntPtr instancePtr, Interop.Advapi32.PERF_COUNTER_DEFINITION[] counters) { ProcessInfo processInfo = new ProcessInfo(); for (int i = 0; i < counters.Length; i++) { Interop.Advapi32.PERF_COUNTER_DEFINITION counter = counters[i]; long value = ReadCounterValue(counter.CounterType, (IntPtr)((long)instancePtr + counter.CounterOffset)); switch ((ValueId)counter.CounterNameTitlePtr) { case ValueId.ProcessId: processInfo.ProcessId = (int)value; break; case ValueId.PoolPagedBytes: processInfo.PoolPagedBytes = value; break; case ValueId.PoolNonpagedBytes: processInfo.PoolNonPagedBytes = value; break; case ValueId.VirtualBytes: processInfo.VirtualBytes = value; break; case ValueId.VirtualBytesPeak: processInfo.VirtualBytesPeak = value; break; case ValueId.WorkingSetPeak: processInfo.WorkingSetPeak = value; break; case ValueId.WorkingSet: processInfo.WorkingSet = value; break; case ValueId.PageFileBytesPeak: processInfo.PageFileBytesPeak = value; break; case ValueId.PageFileBytes: processInfo.PageFileBytes = value; break; case ValueId.PrivateBytes: processInfo.PrivateBytes = value; break; case ValueId.BasePriority: processInfo.BasePriority = (int)value; break; case ValueId.HandleCount: processInfo.HandleCount = (int)value; break; } } return processInfo; } static ValueId GetValueId(string counterName) { if (counterName != null) { ValueId id; if (s_valueIds.TryGetValue(counterName, out id)) return id; } return ValueId.Unknown; } static long ReadCounterValue(int counterType, IntPtr dataPtr) { if ((counterType & Interop.Advapi32.PerfCounterOptions.NtPerfCounterSizeLarge) != 0) return Marshal.ReadInt64(dataPtr); else return (long)Marshal.ReadInt32(dataPtr); } enum ValueId { Unknown = -1, HandleCount, PoolPagedBytes, PoolNonpagedBytes, ElapsedTime, VirtualBytesPeak, VirtualBytes, PrivateBytes, PageFileBytes, PageFileBytesPeak, WorkingSetPeak, WorkingSet, ThreadId, ProcessId, BasePriority, CurrentPriority, UserTime, PrivilegedTime, StartAddress, ThreadState, ThreadWaitReason } } internal static class NtProcessInfoHelper { private static int GetNewBufferSize(int existingBufferSize, int requiredSize) { if (requiredSize == 0) { // // On some old OS like win2000, requiredSize will not be set if the buffer // passed to NtQuerySystemInformation is not enough. // int newSize = existingBufferSize * 2; if (newSize < existingBufferSize) { // In reality, we should never overflow. // Adding the code here just in case it happens. throw new OutOfMemoryException(); } return newSize; } else { // allocating a few more kilo bytes just in case there are some new process // kicked in since new call to NtQuerySystemInformation int newSize = requiredSize + 1024 * 10; if (newSize < requiredSize) { throw new OutOfMemoryException(); } return newSize; } } public static ProcessInfo[] GetProcessInfos() { int requiredSize = 0; int status; ProcessInfo[] processInfos; GCHandle bufferHandle = new GCHandle(); // Start with the default buffer size. int bufferSize = DefaultCachedBufferSize; // Get the cached buffer. long[] buffer = Interlocked.Exchange(ref CachedBuffer, null); try { do { if (buffer == null) { // Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned. buffer = new long[(bufferSize + 7) / 8]; } else { // If we have cached buffer, set the size properly. bufferSize = buffer.Length * sizeof(long); } bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned); status = Interop.NtDll.NtQuerySystemInformation( Interop.NtDll.NtQuerySystemProcessInformation, bufferHandle.AddrOfPinnedObject(), bufferSize, out requiredSize); if (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH) { if (bufferHandle.IsAllocated) bufferHandle.Free(); buffer = null; bufferSize = GetNewBufferSize(bufferSize, requiredSize); } } while (unchecked((uint)status) == Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH); if (status < 0) { // see definition of NT_SUCCESS(Status) in SDK throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception(status)); } // Parse the data block to get process information processInfos = GetProcessInfos(bufferHandle.AddrOfPinnedObject()); } finally { // Cache the final buffer for use on the next call. Interlocked.Exchange(ref CachedBuffer, buffer); if (bufferHandle.IsAllocated) bufferHandle.Free(); } return processInfos; } // Use a smaller buffer size on debug to ensure we hit the retry path. #if DEBUG private const int DefaultCachedBufferSize = 1024; #else private const int DefaultCachedBufferSize = 128 * 1024; #endif // Cache a single buffer for use in GetProcessInfos(). private static long[] CachedBuffer; static ProcessInfo[] GetProcessInfos(IntPtr dataPtr) { // 60 is a reasonable number for processes on a normal machine. Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60); long totalOffset = 0; while (true) { IntPtr currentPtr = (IntPtr)((long)dataPtr + totalOffset); SystemProcessInformation pi = new SystemProcessInformation(); Marshal.PtrToStructure(currentPtr, pi); // get information for a process ProcessInfo processInfo = new ProcessInfo(); // Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD. processInfo.ProcessId = pi.UniqueProcessId.ToInt32(); processInfo.SessionId = (int)pi.SessionId; processInfo.PoolPagedBytes = (long)pi.QuotaPagedPoolUsage; ; processInfo.PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage; processInfo.VirtualBytes = (long)pi.VirtualSize; processInfo.VirtualBytesPeak = (long)pi.PeakVirtualSize; processInfo.WorkingSetPeak = (long)pi.PeakWorkingSetSize; processInfo.WorkingSet = (long)pi.WorkingSetSize; processInfo.PageFileBytesPeak = (long)pi.PeakPagefileUsage; processInfo.PageFileBytes = (long)pi.PagefileUsage; processInfo.PrivateBytes = (long)pi.PrivatePageCount; processInfo.BasePriority = pi.BasePriority; processInfo.HandleCount = (int)pi.HandleCount; if (pi.NamePtr == IntPtr.Zero) { if (processInfo.ProcessId == NtProcessManager.SystemProcessID) { processInfo.ProcessName = "System"; } else if (processInfo.ProcessId == NtProcessManager.IdleProcessID) { processInfo.ProcessName = "Idle"; } else { // for normal process without name, using the process ID. processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture); } } else { string processName = GetProcessShortName(Marshal.PtrToStringUni(pi.NamePtr, pi.NameLength / sizeof(char))); processInfo.ProcessName = processName; } // get the threads for current process processInfos[processInfo.ProcessId] = processInfo; currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(pi)); int i = 0; while (i < pi.NumberOfThreads) { SystemThreadInformation ti = new SystemThreadInformation(); Marshal.PtrToStructure(currentPtr, ti); ThreadInfo threadInfo = new ThreadInfo(); threadInfo._processId = (int)ti.UniqueProcess; threadInfo._threadId = (ulong)ti.UniqueThread; threadInfo._basePriority = ti.BasePriority; threadInfo._currentPriority = ti.Priority; threadInfo._startAddress = ti.StartAddress; threadInfo._threadState = (ThreadState)ti.ThreadState; threadInfo._threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason); processInfo._threadInfoList.Add(threadInfo); currentPtr = (IntPtr)((long)currentPtr + Marshal.SizeOf(ti)); i++; } if (pi.NextEntryOffset == 0) { break; } totalOffset += pi.NextEntryOffset; } ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count]; processInfos.Values.CopyTo(temp, 0); return temp; } // This function generates the short form of process name. // // This is from GetProcessShortName in NT code base. // Check base\screg\winreg\perfdlls\process\perfsprc.c for details. internal static string GetProcessShortName(String name) { if (String.IsNullOrEmpty(name)) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(Process._processTracing.TraceVerbose, "GetProcessInfos() - unexpected blank ProcessName"); #endif return String.Empty; } int slash = -1; int period = -1; for (int i = 0; i < name.Length; i++) { if (name[i] == '\\') slash = i; else if (name[i] == '.') period = i; } if (period == -1) period = name.Length - 1; // set to end of string else { // if a period was found, then see if the extension is // .EXE, if so drop it, if not, then use end of string // (i.e. include extension in name) String extension = name.Substring(period); if (String.Equals(".exe", extension, StringComparison.OrdinalIgnoreCase)) period--; // point to character before period else period = name.Length - 1; // set to end of string } if (slash == -1) slash = 0; // set to start of string else slash++; // point to character next to slash // copy characters between period (or end of string) and // slash (or start of string) to make image name return name.Substring(slash, period - slash + 1); } // native struct defined in ntexapi.h [StructLayout(LayoutKind.Sequential)] internal class SystemProcessInformation { internal uint NextEntryOffset; internal uint NumberOfThreads; private long _SpareLi1; private long _SpareLi2; private long _SpareLi3; private long _CreateTime; private long _UserTime; private long _KernelTime; internal ushort NameLength; // UNICODE_STRING internal ushort MaximumNameLength; internal IntPtr NamePtr; // This will point into the data block returned by NtQuerySystemInformation internal int BasePriority; internal IntPtr UniqueProcessId; internal IntPtr InheritedFromUniqueProcessId; internal uint HandleCount; internal uint SessionId; internal UIntPtr PageDirectoryBase; internal UIntPtr PeakVirtualSize; // SIZE_T internal UIntPtr VirtualSize; internal uint PageFaultCount; internal UIntPtr PeakWorkingSetSize; internal UIntPtr WorkingSetSize; internal UIntPtr QuotaPeakPagedPoolUsage; internal UIntPtr QuotaPagedPoolUsage; internal UIntPtr QuotaPeakNonPagedPoolUsage; internal UIntPtr QuotaNonPagedPoolUsage; internal UIntPtr PagefileUsage; internal UIntPtr PeakPagefileUsage; internal UIntPtr PrivatePageCount; private long _ReadOperationCount; private long _WriteOperationCount; private long _OtherOperationCount; private long _ReadTransferCount; private long _WriteTransferCount; private long _OtherTransferCount; } [StructLayout(LayoutKind.Sequential)] internal class SystemThreadInformation { private long _KernelTime; private long _UserTime; private long _CreateTime; private uint _WaitTime; internal IntPtr StartAddress; internal IntPtr UniqueProcess; internal IntPtr UniqueThread; internal int Priority; internal int BasePriority; internal uint ContextSwitches; internal uint ThreadState; internal uint WaitReason; } } internal sealed class MainWindowFinder { private const int GW_OWNER = 4; private IntPtr _bestHandle; private int _processId; public IntPtr FindMainWindow(int processId) { _bestHandle = (IntPtr)0; _processId = processId; Interop.User32.EnumThreadWindowsCallback callback = new Interop.User32.EnumThreadWindowsCallback(EnumWindowsCallback); Interop.User32.EnumWindows(callback, IntPtr.Zero); GC.KeepAlive(callback); return _bestHandle; } private bool IsMainWindow(IntPtr handle) { if (Interop.User32.GetWindow(handle, GW_OWNER) != (IntPtr)0 || !Interop.User32.IsWindowVisible(handle)) return false; return true; } private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter) { int processId; Interop.User32.GetWindowThreadProcessId(handle, out processId); if (processId == _processId) { if (IsMainWindow(handle)) { _bestHandle = handle; return false; } } return true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Linq; using NHibernate; using NHibernate.Collection; using NHibernate.DebugHelpers; using NHibernate.Engine; using NHibernate.Loader; using NHibernate.Persister.Collection; using NHibernate.Type; using NHibernate.Util; namespace Nerula.Test { //add to your configuration: //configuration.Properties[Environment.CollectionTypeFactoryClass] // = typeof(Net4CollectionTypeFactory).AssemblyQualifiedName; public class Net4CollectionTypeFactory : DefaultCollectionTypeFactory { public override CollectionType Set<T>(string role, string propertyRef, bool embedded) { return new GenericSetType<T>(role, propertyRef); } public override CollectionType SortedSet<T>(string role, string propertyRef, bool embedded, IComparer<T> comparer) { return new GenericSortedSetType<T>(role, propertyRef, comparer); } } [Serializable] public class GenericSortedSetType<T> : GenericSetType<T> { private readonly IComparer<T> comparer; public GenericSortedSetType(string role, string propertyRef, IComparer<T> comparer) : base(role, propertyRef) { this.comparer = comparer; } public override object Instantiate(int anticipatedSize) { return new SortedSet<T>(this.comparer); } public IComparer<T> Comparer { get { return this.comparer; } } } /// <summary> /// An <see cref="IType"/> that maps an <see cref="ISet{T}"/> collection /// to the database. /// </summary> [Serializable] public class GenericSetType<T> : SetType { /// <summary> /// Initializes a new instance of a <see cref="GenericSetType{T}"/> class for /// a specific role. /// </summary> /// <param name="role">The role the persistent collection is in.</param> /// <param name="propertyRef">The name of the property in the /// owner object containing the collection ID, or <see langword="null" /> if it is /// the primary key.</param> public GenericSetType(string role, string propertyRef) : base(role, propertyRef, false) { } public override Type ReturnedClass { get { return typeof (ISet<T>); } } /// <summary> /// Instantiates a new <see cref="IPersistentCollection"/> for the set. /// </summary> /// <param name="session">The current <see cref="ISessionImplementor"/> for the set.</param> /// <param name="persister">The current <see cref="ICollectionPersister" /> for the set.</param> /// <param name="key"></param> public override IPersistentCollection Instantiate(ISessionImplementor session, ICollectionPersister persister, object key) { return new PersistentGenericSet<T>(session); } /// <summary> /// Wraps an <see cref="IList{T}"/> in a <see cref="PersistentGenericSet&lt;T&gt;"/>. /// </summary> /// <param name="session">The <see cref="ISessionImplementor"/> for the collection to be a part of.</param> /// <param name="collection">The unwrapped <see cref="IList{T}"/>.</param> /// <returns> /// An <see cref="PersistentGenericSet&lt;T&gt;"/> that wraps the non NHibernate <see cref="IList{T}"/>. /// </returns> public override IPersistentCollection Wrap(ISessionImplementor session, object collection) { var set = collection as ISet<T>; if (set == null) { var stronglyTypedCollection = collection as ICollection<T>; if (stronglyTypedCollection == null) throw new HibernateException(Role + " must be an implementation of ISet<T> or ICollection<T>"); set = new HashSet<T>(stronglyTypedCollection); } return new PersistentGenericSet<T>(session, set); } public override object Instantiate(int anticipatedSize) { return new HashSet<T>(); } protected override void Clear(object collection) { ((ISet<T>)collection).Clear(); } protected override void Add(object collection, object element) { ((ISet<T>)collection).Add((T)element); } } /// <summary> /// A persistent wrapper for an <see cref="ISet{T}"/> /// </summary> [Serializable] [DebuggerTypeProxy(typeof (CollectionProxy<>))] public class PersistentGenericSet<T> : AbstractPersistentCollection, ISet<T> { /// <summary> /// The <see cref="ISet{T}"/> that NHibernate is wrapping. /// </summary> protected ISet<T> set; /// <summary> /// A temporary list that holds the objects while the PersistentSet is being /// populated from the database. /// </summary> /// <remarks> /// This is necessary to ensure that the object being added to the PersistentSet doesn't /// have its' <c>GetHashCode()</c> and <c>Equals()</c> methods called during the load /// process. /// </remarks> [NonSerialized] private IList<T> tempList; public PersistentGenericSet() { } // needed for serialization /// <summary> /// Constructor matching super. /// Instantiates a lazy set (the underlying set is un-initialized). /// </summary> /// <param name="session">The session to which this set will belong. </param> public PersistentGenericSet(ISessionImplementor session) : base(session) { } /// <summary> /// Instantiates a non-lazy set (the underlying set is constructed /// from the incoming set reference). /// </summary> /// <param name="session">The session to which this set will belong. </param> /// <param name="original">The underlying set data. </param> public PersistentGenericSet(ISessionImplementor session, ISet<T> original) : base(session) { // Sets can be just a view of a part of another collection. // do we need to copy it to be sure it won't be changing // underneath us? // ie. this.set.addAll(set); set = original; SetInitialized(); IsDirectlyAccessible = true; } public override bool RowUpdatePossible { get { return false; } } public override bool Empty { get { return set.Count == 0; } } public bool IsEmpty { get { return ReadSize() ? CachedSize == 0 : (set.Count == 0); } } public object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } #region ISet<T> Members IEnumerator<T> IEnumerable<T>.GetEnumerator() { Read(); return set.GetEnumerator(); } public bool Contains(T o) { bool? exists = ReadElementExistence(o); return exists == null ? set.Contains(o) : exists.Value; } public void CopyTo(T[] array, int arrayIndex) { Read(); Array.Copy(set.ToArray(), 0, array, arrayIndex, Count); } //public bool ContainsAll(ICollection c) //{ // Read(); // return set.ContainsAll(c); //} public bool Add(T o) { bool? exists = IsOperationQueueEnabled ? ReadElementExistence(o) : null; if (!exists.HasValue) { Initialize(true); if (set.Add(o)) { Dirty(); return true; } return false; } if (exists.Value) { return false; } QueueOperation(new SimpleAddDelayedOperation(this, o)); return true; } public void UnionWith(IEnumerable<T> other) { Read(); set.UnionWith(other); } public void IntersectWith(IEnumerable<T> other) { Read(); set.IntersectWith(other); } public void ExceptWith(IEnumerable<T> other) { Read(); set.ExceptWith(other); } public void SymmetricExceptWith(IEnumerable<T> other) { Read(); set.SymmetricExceptWith(other); } public bool IsSubsetOf(IEnumerable<T> other) { Read(); return set.IsProperSupersetOf(other); } public bool IsSupersetOf(IEnumerable<T> other) { Read(); return set.IsSupersetOf(other); } public bool IsProperSupersetOf(IEnumerable<T> other) { Read(); return set.IsProperSupersetOf(other); } public bool IsProperSubsetOf(IEnumerable<T> other) { Read(); return set.IsProperSubsetOf(other); } public bool Overlaps(IEnumerable<T> other) { Read(); return set.Overlaps(other); } public bool SetEquals(IEnumerable<T> other) { Read(); return set.SetEquals(other); } public bool Remove(T o) { bool? exists = PutQueueEnabled ? ReadElementExistence(o) : null; if (!exists.HasValue) { Initialize(true); if (set.Remove(o)) { Dirty(); return true; } return false; } if (exists.Value) { QueueOperation(new SimpleRemoveDelayedOperation(this, o)); return true; } return false; } void ICollection<T>.Add(T item) { Add(item); } public void Clear() { if (ClearQueueEnabled) { QueueOperation(new ClearDelayedOperation(this)); } else { Initialize(true); if (set.Count != 0) { set.Clear(); Dirty(); } } } public int Count { get { return ReadSize() ? CachedSize : set.Count; } } public bool IsReadOnly { get { return false; } } public IEnumerator GetEnumerator() { Read(); return set.GetEnumerator(); } #endregion #region DelayedOperations #region Nested type: ClearDelayedOperation protected sealed class ClearDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; public ClearDelayedOperation(PersistentGenericSet<T> enclosingInstance) { this.enclosingInstance = enclosingInstance; } #region IDelayedOperation Members public object AddedInstance { get { return null; } } public object Orphan { get { throw new NotSupportedException("queued clear cannot be used with orphan delete"); } } public void Operate() { enclosingInstance.set.Clear(); } #endregion } #endregion #region Nested type: SimpleAddDelayedOperation protected sealed class SimpleAddDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; private readonly T value; public SimpleAddDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value) { this.enclosingInstance = enclosingInstance; this.value = value; } #region IDelayedOperation Members public object AddedInstance { get { return value; } } public object Orphan { get { return null; } } public void Operate() { enclosingInstance.set.Add(value); } #endregion } #endregion #region Nested type: SimpleRemoveDelayedOperation protected sealed class SimpleRemoveDelayedOperation : IDelayedOperation { private readonly PersistentGenericSet<T> enclosingInstance; private readonly T value; public SimpleRemoveDelayedOperation(PersistentGenericSet<T> enclosingInstance, T value) { this.enclosingInstance = enclosingInstance; this.value = value; } #region IDelayedOperation Members public object AddedInstance { get { return null; } } public object Orphan { get { return value; } } public void Operate() { enclosingInstance.set.Remove(value); } #endregion } #endregion #endregion public override ICollection GetSnapshot(ICollectionPersister persister) { var entityMode = Session.EntityMode; var clonedSet = new SetSnapShot<T>(set.Count); var enumerable = from object current in set select persister.ElementType.DeepCopy(current, entityMode, persister.Factory); foreach (var copied in enumerable) { clonedSet.Add((T)copied); } return clonedSet; } public override ICollection GetOrphans(object snapshot, string entityName) { var sn = new SetSnapShot<object>((IEnumerable<object>) snapshot); if (set.Count == 0) return sn; if (((ICollection) sn).Count == 0) return sn; return GetOrphans(sn, set.ToArray(), entityName, Session); } public override bool EqualsSnapshot(ICollectionPersister persister) { var elementType = persister.ElementType; var snapshot = (ISetSnapshot<T>) GetSnapshot(); if (((ICollection) snapshot).Count != set.Count) { return false; } return !(from object obj in set let oldValue = snapshot[(T)obj] where oldValue == null || elementType.IsDirty(oldValue, obj, Session) select obj).Any(); } public override bool IsSnapshotEmpty(object snapshot) { return ((ICollection) snapshot).Count == 0; } public override void BeforeInitialize(ICollectionPersister persister, int anticipatedSize) { set = (ISet<T>) persister.CollectionType.Instantiate(anticipatedSize); } /// <summary> /// Initializes this PersistentSet from the cached values. /// </summary> /// <param name="persister">The CollectionPersister to use to reassemble the PersistentSet.</param> /// <param name="disassembled">The disassembled PersistentSet.</param> /// <param name="owner">The owner object.</param> public override void InitializeFromCache(ICollectionPersister persister, object disassembled, object owner) { var array = (object[]) disassembled; int size = array.Length; BeforeInitialize(persister, size); for (int i = 0; i < size; i++) { var element = (T) persister.ElementType.Assemble(array[i], Session, owner); if (element != null) { set.Add(element); } } SetInitialized(); } public override string ToString() { Read(); return StringHelper.CollectionToString(set.ToArray()); } public override object ReadFrom(IDataReader rs, ICollectionPersister role, ICollectionAliases descriptor, object owner) { var element = (T) role.ReadElement(rs, owner, descriptor.SuffixedElementAliases, Session); if (element != null) { tempList.Add(element); } return element; } /// <summary> /// Set up the temporary List that will be used in the EndRead() /// to fully create the set. /// </summary> public override void BeginRead() { base.BeginRead(); tempList = new List<T>(); } /// <summary> /// Takes the contents stored in the temporary list created during <c>BeginRead()</c> /// that was populated during <c>ReadFrom()</c> and write it to the underlying /// PersistentSet. /// </summary> public override bool EndRead(ICollectionPersister persister) { foreach (T item in tempList) { set.Add(item); } tempList = null; SetInitialized(); return true; } public override IEnumerable Entries(ICollectionPersister persister) { return set; } public override object Disassemble(ICollectionPersister persister) { var result = new object[set.Count]; int i = 0; foreach (object obj in set) { result[i++] = persister.ElementType.Disassemble(obj, Session, null); } return result; } public override IEnumerable GetDeletes(ICollectionPersister persister, bool indexIsFormula) { IType elementType = persister.ElementType; var sn = (ISetSnapshot<T>) GetSnapshot(); var deletes = new List<T>(((ICollection<T>) sn).Count); deletes.AddRange(sn.Where(obj => !set.Contains(obj))); deletes.AddRange(from obj in set let oldValue = sn[obj] where oldValue != null && elementType.IsDirty(obj, oldValue, Session) select oldValue); return deletes; } public override bool NeedsInserting(object entry, int i, IType elemType) { var sn = (ISetSnapshot<T>) GetSnapshot(); object oldKey = sn[(T)entry]; // note that it might be better to iterate the snapshot but this is safe, // assuming the user implements equals() properly, as required by the PersistentSet // contract! return oldKey == null || elemType.IsDirty(oldKey, entry, Session); } public override bool NeedsUpdating(object entry, int i, IType elemType) { return false; } public override object GetIndex(object entry, int i, ICollectionPersister persister) { throw new NotSupportedException("Sets don't have indexes"); } public override object GetElement(object entry) { return entry; } public override object GetSnapshotElement(object entry, int i) { throw new NotSupportedException("Sets don't support updating by element"); } public new void Read() { base.Read(); } public override bool Equals(object other) { var that = other as ISet<T>; if (that == null) { return false; } Read(); return set.SequenceEqual(that); } public override int GetHashCode() { Read(); return set.GetHashCode(); } public override bool EntryExists(object entry, int i) { return true; } public override bool IsWrapper(object collection) { return set == collection; } public void CopyTo(Array array, int index) { // NH : we really need to initialize the set ? Read(); Array.Copy(set.ToArray(), 0, array, index, Count); } #region Nested type: ISetSnapshot private interface ISetSnapshot<TItem> : ICollection<TItem>, ICollection { TItem this[TItem element] { get; } } #endregion #region Nested type: SetSnapShot [Serializable] private class SetSnapShot<TItem> : ISetSnapshot<TItem> { private readonly List<TItem> elements; private SetSnapShot() { elements = new List<TItem>(); } public SetSnapShot(int capacity) { elements = new List<TItem>(capacity); } public SetSnapShot(IEnumerable<TItem> collection) { elements = new List<TItem>(collection); } #region ISetSnapshot<T> Members public IEnumerator<TItem> GetEnumerator() { return elements.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(TItem item) { elements.Add(item); } public void Clear() { throw new InvalidOperationException(); } public bool Contains(TItem item) { return elements.Contains(item); } public void CopyTo(TItem[] array, int arrayIndex) { elements.CopyTo(array, arrayIndex); } public bool Remove(TItem item) { throw new InvalidOperationException(); } public void CopyTo(Array array, int index) { ((ICollection) elements).CopyTo(array, index); } int ICollection.Count { get { return elements.Count; } } public object SyncRoot { get { return ((ICollection) elements).SyncRoot; } } public bool IsSynchronized { get { return ((ICollection) elements).IsSynchronized; } } int ICollection<TItem>.Count { get { return elements.Count; } } public bool IsReadOnly { get { return ((ICollection<TItem>) elements).IsReadOnly; } } public TItem this[TItem element] { get { int idx = elements.IndexOf(element); if (idx >= 0) { return elements[idx]; } return default(TItem); } } #endregion } #endregion } }
// Copyright (c) 2012, Event Store LLP // 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 Event Store LLP 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.Diagnostics.Contracts; using EventStore.Common.Log; using EventStore.Core.Bus; using EventStore.Core.Data; using EventStore.Core.TransactionLog.LogRecords; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public abstract class CoreProjectionCheckpointManager : IProjectionCheckpointManager, ICoreProjectionCheckpointManager, IEmittedEventWriter { protected readonly ProjectionNamesBuilder _namingBuilder; protected readonly ProjectionConfig _projectionConfig; protected readonly ILogger _logger; private readonly bool _usePersistentCheckpoints; private readonly bool _producesRunningResults; private readonly IPublisher _publisher; private readonly Guid _projectionCorrelationId; private readonly CheckpointTag _zeroTag; protected ProjectionCheckpoint _currentCheckpoint; private ProjectionCheckpoint _closingCheckpoint; internal CheckpointTag _requestedCheckpointPosition; private bool _inCheckpoint; private PartitionState _requestedCheckpointState; private CheckpointTag _lastCompletedCheckpointPosition; private readonly PositionTracker _lastProcessedEventPosition; private float _lastProcessedEventProgress; private int _eventsProcessedAfterRestart; private bool _started; protected bool _stopping; protected bool _stopped; private PartitionState _currentProjectionState; protected CoreProjectionCheckpointManager( IPublisher publisher, Guid projectionCorrelationId, ProjectionConfig projectionConfig, string name, PositionTagger positionTagger, ProjectionNamesBuilder namingBuilder, bool usePersistentCheckpoints, bool producesRunningResults) { if (publisher == null) throw new ArgumentNullException("publisher"); if (projectionConfig == null) throw new ArgumentNullException("projectionConfig"); if (name == null) throw new ArgumentNullException("name"); if (positionTagger == null) throw new ArgumentNullException("positionTagger"); if (namingBuilder == null) throw new ArgumentNullException("namingBuilder"); if (name == "") throw new ArgumentException("name"); _lastProcessedEventPosition = new PositionTracker(positionTagger); _zeroTag = positionTagger.MakeZeroCheckpointTag(); _publisher = publisher; _projectionCorrelationId = projectionCorrelationId; _projectionConfig = projectionConfig; _logger = LogManager.GetLoggerFor<CoreProjectionCheckpointManager>(); _namingBuilder = namingBuilder; _usePersistentCheckpoints = usePersistentCheckpoints; _producesRunningResults = producesRunningResults; _requestedCheckpointState = new PartitionState("", null, _zeroTag); _currentProjectionState = new PartitionState("", null, _zeroTag); } protected abstract ProjectionCheckpoint CreateProjectionCheckpoint(CheckpointTag checkpointPosition); protected abstract void BeginWriteCheckpoint( CheckpointTag requestedCheckpointPosition, string requestedCheckpointState); protected abstract void CapturePartitionStateUpdated(string partition, PartitionState oldState, PartitionState newState); protected abstract void EmitPartitionCheckpoints(); public abstract void RecordEventOrder(ResolvedEvent resolvedEvent, CheckpointTag orderCheckpointTag, Action committed); public abstract void BeginLoadPartitionStateAt( string statePartition, CheckpointTag requestedStateCheckpointTag, Action<PartitionState> loadCompleted); public abstract void PartitionCompleted(string partition); public virtual void Initialize() { if (_currentCheckpoint != null) _currentCheckpoint.Dispose(); if (_closingCheckpoint != null) _closingCheckpoint.Dispose(); _currentCheckpoint = null; _closingCheckpoint = null; _requestedCheckpointPosition = null; _inCheckpoint = false; _requestedCheckpointState = new PartitionState("", null, _zeroTag); _lastCompletedCheckpointPosition = null; _lastProcessedEventPosition.Initialize(); _lastProcessedEventProgress = -1; _eventsProcessedAfterRestart = 0; _started = false; _stopping = false; _stopped = false; _currentProjectionState = new PartitionState("", null, _zeroTag); } public virtual void Start(CheckpointTag checkpointTag) { Contract.Requires(_currentCheckpoint == null); if (_started) throw new InvalidOperationException("Already started"); _started = true; _lastProcessedEventPosition.UpdateByCheckpointTagInitial(checkpointTag); _lastProcessedEventProgress = -1; _lastCompletedCheckpointPosition = checkpointTag; _requestedCheckpointPosition = null; _currentCheckpoint = CreateProjectionCheckpoint(_lastProcessedEventPosition.LastTag); _currentCheckpoint.Start(); } public void Stopping() { EnsureStarted(); if (_stopping) throw new InvalidOperationException("Already stopping"); _stopping = true; RequestCheckpointToStop(); } public void Stopped() { EnsureStarted(); _started = false; _stopped = true; } public virtual void GetStatistics(ProjectionStatistics info) { info.Position = _lastProcessedEventPosition.LastTag; info.Progress = _lastProcessedEventProgress; info.LastCheckpoint = _lastCompletedCheckpointPosition != null ? _lastCompletedCheckpointPosition.ToString() : ""; info.EventsProcessedAfterRestart = _eventsProcessedAfterRestart; info.WritePendingEventsBeforeCheckpoint = _closingCheckpoint != null ? _closingCheckpoint.GetWritePendingEvents() : 0; info.WritePendingEventsAfterCheckpoint = (_currentCheckpoint != null ? _currentCheckpoint.GetWritePendingEvents() : 0); info.ReadsInProgress = /*_readDispatcher.ActiveRequestCount*/ + + (_closingCheckpoint != null ? _closingCheckpoint.GetReadsInProgress() : 0) + (_currentCheckpoint != null ? _currentCheckpoint.GetReadsInProgress() : 0); info.WritesInProgress = (_closingCheckpoint != null ? _closingCheckpoint.GetWritesInProgress() : 0) + (_currentCheckpoint != null ? _currentCheckpoint.GetWritesInProgress() : 0); info.CheckpointStatus = _inCheckpoint ? "Requested" : ""; } public void StateUpdated( string partition, PartitionState oldState, PartitionState newState) { if (_stopped) return; EnsureStarted(); if (_stopping) throw new InvalidOperationException("Stopping"); if (_usePersistentCheckpoints && partition != "") CapturePartitionStateUpdated(partition, oldState, newState); if (partition == "" && newState.State == null) // ignore non-root partitions and non-changed states throw new NotSupportedException("Internal check"); if (partition == "") _currentProjectionState = newState; } public void EventProcessed(CheckpointTag checkpointTag, float progress) { if (_stopped) return; EnsureStarted(); if (_stopping) throw new InvalidOperationException("Stopping"); _eventsProcessedAfterRestart++; _lastProcessedEventPosition.UpdateByCheckpointTagForward(checkpointTag); _lastProcessedEventProgress = progress; // running state only } public void EventsEmitted(EmittedEventEnvelope[] scheduledWrites, Guid causedBy, string correlationId) { if (_stopped) return; EnsureStarted(); if (_stopping) throw new InvalidOperationException("Stopping"); if (scheduledWrites != null) { foreach (var @event in scheduledWrites) { var emittedEvent = @event.Event; emittedEvent.SetCausedBy(causedBy); emittedEvent.SetCorrelationId(correlationId); } _currentCheckpoint.ValidateOrderAndEmitEvents(scheduledWrites); } } public bool CheckpointSuggested(CheckpointTag checkpointTag, float progress) { if (!_usePersistentCheckpoints) throw new InvalidOperationException("Checkpoints are not used"); if (_stopped || _stopping) return true; EnsureStarted(); if (checkpointTag != _lastProcessedEventPosition.LastTag) // allow checkpoint at the current position _lastProcessedEventPosition.UpdateByCheckpointTagForward(checkpointTag); _lastProcessedEventProgress = progress; return RequestCheckpoint(_lastProcessedEventPosition); } public void Progress(float progress) { if (_stopping || _stopped) return; EnsureStarted(); _lastProcessedEventProgress = progress; } public CheckpointTag LastProcessedEventPosition { get { return _lastProcessedEventPosition.LastTag; } } public void Handle(CoreProjectionProcessingMessage.ReadyForCheckpoint message) { // ignore any messages - typically when faulted if (_stopped) return; // ignore any messages from previous checkpoints probably before RestartRequested if (message.Sender != _closingCheckpoint) return; if (!_inCheckpoint) throw new InvalidOperationException(); if (_usePersistentCheckpoints) BeginWriteCheckpoint(_requestedCheckpointPosition, _requestedCheckpointState.Serialize()); else CheckpointWritten(_requestedCheckpointPosition); } public void Handle(CoreProjectionProcessingMessage.RestartRequested message) { if (_stopped) return; RequestRestart(message.Reason); } public void Handle(CoreProjectionProcessingMessage.Failed message) { if (_stopped) return; Failed(message.Reason); } protected void PrerecordedEventsLoaded(CheckpointTag checkpointTag) { _publisher.Publish( new CoreProjectionProcessingMessage.PrerecordedEventsLoaded(_projectionCorrelationId, checkpointTag)); } private void RequestCheckpointToStop() { EnsureStarted(); if (!_stopping) throw new InvalidOperationException("Not stopping"); if (_inCheckpoint) // checkpoint in progress. no other writes will happen, so we can stop here. return; // do not request checkpoint if no events were processed since last checkpoint //NOTE: we ignore _usePersistentCheckpoints flag as we need to flush final writes before query object // has been disposed if (/* _usePersistentCheckpoints && */ _lastCompletedCheckpointPosition < _lastProcessedEventPosition.LastTag) { RequestCheckpoint(_lastProcessedEventPosition, forcePrepareCheckpoint: true); return; } _publisher.Publish( new CoreProjectionProcessingMessage.CheckpointCompleted( _projectionCorrelationId, _lastCompletedCheckpointPosition)); } protected void EnsureStarted() { if (!_started) throw new InvalidOperationException("Not started"); } /// <returns>true - if checkpoint has beem completed in-sync</returns> private bool RequestCheckpoint(PositionTracker lastProcessedEventPosition, bool forcePrepareCheckpoint = false) { if (!forcePrepareCheckpoint && !_usePersistentCheckpoints) throw new InvalidOperationException("Checkpoints are not allowed"); if (_inCheckpoint) throw new InvalidOperationException("Checkpoint in progress"); return StartCheckpoint(lastProcessedEventPosition, _currentProjectionState); } /// <returns>true - if checkpoint has been completed in-sync</returns> private bool StartCheckpoint(PositionTracker lastProcessedEventPosition, PartitionState projectionState) { Contract.Requires(_closingCheckpoint == null); if (projectionState == null) throw new ArgumentNullException("projectionState"); CheckpointTag requestedCheckpointPosition = lastProcessedEventPosition.LastTag; if (requestedCheckpointPosition == _lastCompletedCheckpointPosition) return true; // either suggested or requested to stop if (_usePersistentCheckpoints) // do not emit any events if we do not use persistent checkpoints EmitPartitionCheckpoints(); _inCheckpoint = true; _requestedCheckpointPosition = requestedCheckpointPosition; _requestedCheckpointState = projectionState; _closingCheckpoint = _currentCheckpoint; _currentCheckpoint = CreateProjectionCheckpoint(requestedCheckpointPosition); // checkpoint only after assigning new current checkpoint, as it may call back immediately _closingCheckpoint.Prepare(requestedCheckpointPosition); return false; // even if prepare completes in sync it notifies the world by a message } protected void SendPrerecordedEvent( EventStore.Core.Data.ResolvedEvent pair, CheckpointTag positionTag, long prerecordedEventMessageSequenceNumber) { var position = pair.OriginalEvent; var committedEvent = new ReaderSubscriptionMessage.CommittedEventDistributed( Guid.Empty, new ResolvedEvent( position.EventStreamId, position.EventNumber, pair.Event.EventStreamId, pair.Event.EventNumber, pair.Link != null, new TFPos(-1, position.LogPosition), new TFPos(-1, pair.Event.LogPosition), pair.Event.EventId, pair.Event.EventType, (pair.Event.Flags & PrepareFlags.IsJson) != 0, pair.Event.Data, pair.Event.Metadata, pair.Link == null ? null : pair.Link.Metadata, null, pair.Event.TimeStamp), null, -1, source: this.GetType()); _publisher.Publish( EventReaderSubscriptionMessage.CommittedEventReceived.FromCommittedEventDistributed( committedEvent, positionTag, null, _projectionCorrelationId, prerecordedEventMessageSequenceNumber)); } protected void RequestRestart(string reason) { _stopped = true; // ignore messages _publisher.Publish(new CoreProjectionProcessingMessage.RestartRequested(_projectionCorrelationId, reason)); } private void Failed(string reason) { _stopped = true; // ignore messages _publisher.Publish(new CoreProjectionProcessingMessage.Failed(_projectionCorrelationId, reason)); } protected void CheckpointWritten(CheckpointTag lastCompletedCheckpointPosition) { Contract.Requires(_closingCheckpoint != null); _lastCompletedCheckpointPosition = lastCompletedCheckpointPosition; _closingCheckpoint.Dispose(); _closingCheckpoint = null; if (!_stopping) // ignore any writes pending in the current checkpoint (this is not the best, but they will never hit the storage, so it is safe) _currentCheckpoint.Start(); _inCheckpoint = false; //NOTE: the next checkpoint will start by completing checkpoint work item _publisher.Publish( new CoreProjectionProcessingMessage.CheckpointCompleted( _projectionCorrelationId, _lastCompletedCheckpointPosition)); } public virtual void BeginLoadPrerecordedEvents(CheckpointTag checkpointTag) { PrerecordedEventsLoaded(checkpointTag); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace System.Data.SqlClient.SNI { /// <summary> /// SNI Asynchronous callback /// </summary> /// <param name="packet">SNI packet</param> /// <param name="sniErrorCode">SNI error code</param> internal delegate void SNIAsyncCallback(SNIPacket packet, uint sniErrorCode); /// <summary> /// SNI provider identifiers /// </summary> internal enum SNIProviders { HTTP_PROV, // HTTP Provider NP_PROV, // Named Pipes Provider SESSION_PROV, // Session Provider SIGN_PROV, // Sign Provider SM_PROV, // Shared Memory Provider SMUX_PROV, // SMUX Provider SSL_PROV, // SSL Provider TCP_PROV, // TCP Provider MAX_PROVS, // Number of providers INVALID_PROV // SQL Network Interfaces } /// <summary> /// SMUX packet header /// </summary> internal sealed class SNISMUXHeader { public const int HEADER_LENGTH = 16; public byte SMID; public byte flags; public ushort sessionId; public uint length; public uint sequenceNumber; public uint highwater; public void Read(byte[] bytes) { SMID = bytes[0]; flags = bytes[1]; sessionId = BitConverter.ToUInt16(bytes, 2); length = BitConverter.ToUInt32(bytes, 4) - SNISMUXHeader.HEADER_LENGTH; sequenceNumber = BitConverter.ToUInt32(bytes, 8); highwater = BitConverter.ToUInt32(bytes, 12); } public void Write(Span<byte> bytes) { uint value = highwater; // access the highest element first to cause the largest range check in the jit, then fill in the rest of the value and carry on as normal bytes[15] = (byte)((value >> 24) & 0xff); bytes[12] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); bytes[13] = (byte)((value >> 8) & 0xff); bytes[14] = (byte)((value >> 16) & 0xff); bytes[0] = SMID; // BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); bytes[1] = flags; // BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); value = sessionId; bytes[2] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); bytes[3] = (byte)((value >> 8) & 0xff); value = length; bytes[4] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); bytes[5] = (byte)((value >> 8) & 0xff); bytes[6] = (byte)((value >> 16) & 0xff); bytes[7] = (byte)((value >> 24) & 0xff); value = sequenceNumber; bytes[8] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); bytes[9] = (byte)((value >> 8) & 0xff); bytes[10] = (byte)((value >> 16) & 0xff); bytes[11] = (byte)((value >> 24) & 0xff); } } /// <summary> /// SMUX packet flags /// </summary> [Flags] internal enum SNISMUXFlags { SMUX_SYN = 1, // Begin SMUX connection SMUX_ACK = 2, // Acknowledge SMUX packets SMUX_FIN = 4, // End SMUX connection SMUX_DATA = 8 // SMUX data packet } internal class SNICommon { // Each error number maps to SNI_ERROR_* in String.resx internal const int ConnTerminatedError = 2; internal const int InvalidParameterError = 5; internal const int ProtocolNotSupportedError = 8; internal const int ConnTimeoutError = 11; internal const int ConnNotUsableError = 19; internal const int InvalidConnStringError = 25; internal const int HandshakeFailureError = 31; internal const int InternalExceptionError = 35; internal const int ConnOpenFailedError = 40; internal const int ErrorSpnLookup = 44; internal const int LocalDBErrorCode = 50; internal const int MultiSubnetFailoverWithMoreThan64IPs = 47; internal const int MultiSubnetFailoverWithInstanceSpecified = 48; internal const int MultiSubnetFailoverWithNonTcpProtocol = 49; internal const int MaxErrorValue = 50157; internal const int LocalDBNoInstanceName = 51; internal const int LocalDBNoInstallation = 52; internal const int LocalDBInvalidConfig = 53; internal const int LocalDBNoSqlUserInstanceDllPath = 54; internal const int LocalDBInvalidSqlUserInstanceDllPath = 55; internal const int LocalDBFailedToLoadDll = 56; internal const int LocalDBBadRuntime = 57; /// <summary> /// Validate server certificate callback for SSL /// </summary> /// <param name="targetServerName">Server that client is expecting to connect to</param> /// <param name="sender">Sender object</param> /// <param name="cert">X.509 certificate</param> /// <param name="chain">X.509 chain</param> /// <param name="policyErrors">Policy errors</param> /// <returns>True if certificate is valid</returns> internal static bool ValidateSslServerCertificate(string targetServerName, object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { if (policyErrors == SslPolicyErrors.None) { return true; } if ((policyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { string certServerName = cert.Subject.Substring(cert.Subject.IndexOf('=') + 1); // Verify that target server name matches subject in the certificate if (targetServerName.Length > certServerName.Length) { return false; } else if (targetServerName.Length == certServerName.Length) { // Both strings have the same length, so targetServerName must be a FQDN if (!targetServerName.Equals(certServerName, StringComparison.OrdinalIgnoreCase)) { return false; } } else { if (string.Compare(targetServerName, 0, certServerName, 0, targetServerName.Length, StringComparison.OrdinalIgnoreCase) != 0) { return false; } // Server name matches cert name for its whole length, so ensure that the // character following the server name is a '.'. This will avoid // having server name "ab" match "abc.corp.company.com" // (Names have different lengths, so the target server can't be a FQDN.) if (certServerName[targetServerName.Length] != '.') { return false; } } } else { // Fail all other SslPolicy cases besides RemoteCertificateNameMismatch return false; } return true; } /// <summary> /// Sets last error encountered for SNI /// </summary> /// <param name="provider">SNI provider</param> /// <param name="nativeError">Native error code</param> /// <param name="sniError">SNI error code</param> /// <param name="errorMessage">Error message</param> /// <returns></returns> internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uint sniError, string errorMessage) { return ReportSNIError(new SNIError(provider, nativeError, sniError, errorMessage)); } /// <summary> /// Sets last error encountered for SNI /// </summary> /// <param name="provider">SNI provider</param> /// <param name="sniError">SNI error code</param> /// <param name="sniException">SNI Exception</param> /// <returns></returns> internal static uint ReportSNIError(SNIProviders provider, uint sniError, Exception sniException) { return ReportSNIError(new SNIError(provider, sniError, sniException)); } /// <summary> /// Sets last error encountered for SNI /// </summary> /// <param name="error">SNI error</param> /// <returns></returns> internal static uint ReportSNIError(SNIError error) { SNILoadHandle.SingletonInstance.LastError = error; return TdsEnums.SNI_ERROR; } } }
using System; using System.IO; namespace ICSharpCode.SharpZipLib.Tar { /// <summary> /// The TarBuffer class implements the tar archive concept /// of a buffered input stream. This concept goes back to the /// days of blocked tape drives and special io devices. In the /// C# universe, the only real function that this class /// performs is to ensure that files have the correct "record" /// size, or other tars will complain. /// <p> /// You should never have a need to access this class directly. /// TarBuffers are created by Tar IO Streams. /// </p> /// </summary> public class TarBuffer { /* A quote from GNU tar man file on blocking and records A `tar' archive file contains a series of blocks. Each block contains `BLOCKSIZE' bytes. Although this format may be thought of as being on magnetic tape, other media are often used. Each file archived is represented by a header block which describes the file, followed by zero or more blocks which give the contents of the file. At the end of the archive file there may be a block filled with binary zeros as an end-of-file marker. A reasonable system should write a block of zeros at the end, but must not assume that such a block exists when reading an archive. The blocks may be "blocked" for physical I/O operations. Each record of N blocks is written with a single 'write ()' operation. On magnetic tapes, the result of such a write is a single record. When writing an archive, the last record of blocks should be written at the full size, with blocks after the zero block containing all zeros. When reading an archive, a reasonable system should properly handle an archive whose last record is shorter than the rest, or which contains garbage records after a zero block. */ #region Constants /// <summary> /// The size of a block in a tar archive in bytes. /// </summary> /// <remarks>This is 512 bytes.</remarks> public const int BlockSize = 512; /// <summary> /// The number of blocks in a default record. /// </summary> /// <remarks> /// The default value is 20 blocks per record. /// </remarks> public const int DefaultBlockFactor = 20; /// <summary> /// The size in bytes of a default record. /// </summary> /// <remarks> /// The default size is 10KB. /// </remarks> public const int DefaultRecordSize = BlockSize * DefaultBlockFactor; #endregion /// <summary> /// Get the record size for this buffer /// </summary> /// <value>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></value> public int RecordSize { get { return recordSize; } } /// <summary> /// Get the TAR Buffer's record size. /// </summary> /// <returns>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return recordSize; } /// <summary> /// Get the Blocking factor for the buffer /// </summary> /// <value>This is the number of blocks in each record.</value> public int BlockFactor { get { return blockFactor; } } /// <summary> /// Get the TAR Buffer's block factor /// </summary> /// <returns>The block factor; the number of blocks per record.</returns> [Obsolete("Use BlockFactor property instead")] public int GetBlockFactor() { return blockFactor; } /// <summary> /// Construct a default TarBuffer /// </summary> protected TarBuffer() { } /// <summary> /// Create TarBuffer for reading with default BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } return CreateInputTarBuffer(inputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for reading inputStream setting BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor) { if (inputStream == null) { throw new ArgumentNullException(nameof(inputStream)); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative"); } var tarBuffer = new TarBuffer(); tarBuffer.inputStream = inputStream; tarBuffer.outputStream = null; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Construct TarBuffer for writing with default BlockFactor /// </summary> /// <param name="outputStream">output stream for buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } return CreateOutputTarBuffer(outputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for writing Tar output to streams. /// </summary> /// <param name="outputStream">Output stream to write to.</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException(nameof(outputStream)); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException(nameof(blockFactor), "Factor cannot be negative"); } var tarBuffer = new TarBuffer(); tarBuffer.inputStream = null; tarBuffer.outputStream = outputStream; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Initialization common to all constructors. /// </summary> void Initialize(int archiveBlockFactor) { blockFactor = archiveBlockFactor; recordSize = archiveBlockFactor * BlockSize; recordBuffer = new byte[RecordSize]; if (inputStream != null) { currentRecordIndex = -1; currentBlockIndex = BlockFactor; } else { currentRecordIndex = 0; currentBlockIndex = 0; } } /// <summary> /// Determine if an archive block indicates End of Archive. End of /// archive is indicated by a block that consists entirely of null bytes. /// All remaining blocks for the record should also be null's /// However some older tars only do a couple of null blocks (Old GNU tar for one) /// and also partial records /// </summary> /// <param name = "block">The data block to check.</param> /// <returns>Returns true if the block is an EOF block; false otherwise.</returns> [Obsolete("Use IsEndOfArchiveBlock instead")] public bool IsEOFBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (block.Length != BlockSize) { throw new ArgumentException("block length is invalid"); } for (int i = 0; i < BlockSize; ++i) { if (block[i] != 0) { return false; } } return true; } /// <summary> /// Determine if an archive block indicates the End of an Archive has been reached. /// End of archive is indicated by a block that consists entirely of null bytes. /// All remaining blocks for the record should also be null's /// However some older tars only do a couple of null blocks (Old GNU tar for one) /// and also partial records /// </summary> /// <param name = "block">The data block to check.</param> /// <returns>Returns true if the block is an EOF block; false otherwise.</returns> public static bool IsEndOfArchiveBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (block.Length != BlockSize) { throw new ArgumentException("block length is invalid"); } for (int i = 0; i < BlockSize; ++i) { if (block[i] != 0) { return false; } } return true; } /// <summary> /// Skip over a block on the input stream. /// </summary> public void SkipBlock() { if (inputStream == null) { throw new TarException("no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } currentBlockIndex++; } /// <summary> /// Read a block from the input stream. /// </summary> /// <returns> /// The block of data read. /// </returns> public byte[] ReadBlock() { if (inputStream == null) { throw new TarException("TarBuffer.ReadBlock - no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } byte[] result = new byte[BlockSize]; Array.Copy(recordBuffer, (currentBlockIndex * BlockSize), result, 0, BlockSize); currentBlockIndex++; return result; } /// <summary> /// Read a record from data stream. /// </summary> /// <returns> /// false if End-Of-File, else true. /// </returns> bool ReadRecord() { if (inputStream == null) { throw new TarException("no input stream stream defined"); } currentBlockIndex = 0; int offset = 0; int bytesNeeded = RecordSize; while (bytesNeeded > 0) { long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); // // NOTE // We have found EOF, and the record is not full! // // This is a broken archive. It does not follow the standard // blocking algorithm. However, because we are generous, and // it requires little effort, we will simply ignore the error // and continue as if the entire record were read. This does // not appear to break anything upstream. We used to return // false in this case. // // Thanks to 'Yohann.Roussel@alcatel.fr' for this fix. // if (numBytes <= 0) { break; } offset += (int)numBytes; bytesNeeded -= (int)numBytes; } currentRecordIndex++; return true; } /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> /// <remarks>Block numbers are zero based values</remarks> /// <seealso cref="RecordSize"/> public int CurrentBlock { get { return currentBlockIndex; } } /// <summary> /// Get/set flag indicating ownership of the underlying stream. /// When the flag is true <see cref="Close"></see> will close the underlying stream also. /// </summary> public bool IsStreamOwner { get { return isStreamOwner_; } set { isStreamOwner_ = value; } } /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> /// <returns> /// The current zero based block number. /// </returns> /// <remarks> /// The absolute block number = (<see cref="GetCurrentRecordNum">record number</see> * <see cref="BlockFactor">block factor</see>) + <see cref="GetCurrentBlockNum">block number</see>. /// </remarks> [Obsolete("Use CurrentBlock property instead")] public int GetCurrentBlockNum() { return currentBlockIndex; } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> public int CurrentRecord { get { return currentRecordIndex; } } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> [Obsolete("Use CurrentRecord property instead")] public int GetCurrentRecordNum() { return currentRecordIndex; } /// <summary> /// Write a block of data to the archive. /// </summary> /// <param name="block"> /// The data to write to the archive. /// </param> public void WriteBlock(byte[] block) { if (block == null) { throw new ArgumentNullException(nameof(block)); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream defined"); } if (block.Length != BlockSize) { string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", block.Length, BlockSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write an archive record to the archive, where the record may be /// inside of a larger array buffer. The buffer must be "offset plus /// record size" long. /// </summary> /// <param name="buffer"> /// The buffer containing the record data to write. /// </param> /// <param name="offset"> /// The offset of the record data within buffer. /// </param> public void WriteBlock(byte[] buffer, int offset) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); } if ((offset < 0) || (offset >= buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if ((offset + BlockSize) > buffer.Length) { string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", buffer.Length, offset, recordSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write a TarBuffer record to the archive. /// </summary> void WriteRecord() { if (outputStream == null) { throw new TarException("TarBuffer.WriteRecord no output stream defined"); } outputStream.Write(recordBuffer, 0, RecordSize); outputStream.Flush(); currentBlockIndex = 0; currentRecordIndex++; } /// <summary> /// WriteFinalRecord writes the current record buffer to output any unwritten data is present. /// </summary> /// <remarks>Any trailing bytes are set to zero which is by definition correct behaviour /// for the end of a tar stream.</remarks> void WriteFinalRecord() { if (outputStream == null) { throw new TarException("TarBuffer.WriteFinalRecord no output stream defined"); } if (currentBlockIndex > 0) { int dataBytes = currentBlockIndex * BlockSize; Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); WriteRecord(); } outputStream.Flush(); } /// <summary> /// Close the TarBuffer. If this is an output buffer, also flush the /// current block before closing. /// </summary> public void Close() { if (outputStream != null) { WriteFinalRecord(); if (isStreamOwner_) { outputStream.Close(); } outputStream = null; } else if (inputStream != null) { if (isStreamOwner_) { inputStream.Close(); } inputStream = null; } } #region Instance Fields Stream inputStream; Stream outputStream; byte[] recordBuffer; int currentBlockIndex; int currentRecordIndex; int recordSize = DefaultRecordSize; int blockFactor = DefaultBlockFactor; bool isStreamOwner_ = true; #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsSubscriptionIdApiVersion { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// GroupOperations operations. /// </summary> internal partial class GroupOperations : IServiceOperations<MicrosoftAzureTestUrl>, IGroupOperations { /// <summary> /// Initializes a new instance of the GroupOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal GroupOperations(MicrosoftAzureTestUrl client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the MicrosoftAzureTestUrl /// </summary> public MicrosoftAzureTestUrl Client { get; private set; } /// <summary> /// Provides a resouce group with name 'testgroup101' and location 'West US'. /// </summary> /// <param name='resourceGroupName'> /// Resource Group name 'testgroup101'. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SampleResourceGroup>> GetSampleResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetSampleResourceGroup", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SampleResourceGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SampleResourceGroup>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Google.Maps.Examples.Shared { /// <summary> /// Class for showing an in-scene, <see cref="Camera.main"/> aligned Label. /// </summary> [RequireComponent(typeof(CanvasGroup))] public class Label : MonoBehaviour { [Tooltip("Text element to show this Label's text in.")] public Text Text; [Tooltip( "Should this Label keep its starting x-rotation (i.e. should it stay at its current " + "up/down tilt amount, and just turn in y-axis to face Camera)?")] public bool TurnOnly; [Tooltip( "Should the Label which is the most closely aligned to the Camera be the most visible? " + "This helps reduce visual clutter by allowing all Labels not been directly looked at to " + "be faded out.")] public bool FadeWithView; [Tooltip("Total time this Label should take to fade in or out?")] public float FadeTime = 1f; [Tooltip("Should this Label start hidden?")] public bool StartFadedOut; [Tooltip("Should this Label automatically start fading in as soon as SetText is called?")] public bool AutoFadeIn; /// <summary> /// Is this <see cref="Label"/> currently tracking <see cref="Camera.main"/>, i.e. is this /// <see cref="Label"/> continually making sure it is aligned to <see cref="Camera.main"/>? /// </summary> /// <remarks> /// This flag is used to ensure that the coroutine for <see cref="Camera.main"/>-tracking is not /// redundantly started when it is already running. /// </remarks> private bool IsTrackingCamera; /// <summary>Is this <see cref="Label"/> currently fading in or out?</summary> /// <remarks> /// This flag is used to ensure that the fading-facing coroutine is not redundantly started when /// when it is already running. /// </remarks> private bool IsFading; /// <summary>Has a <see cref="Text"/> component been defined?</summary> /// <remarks> /// This is set to null before this check is performed, allowing this check to only be performed /// once, with the result being stored for future re-use. /// </remarks> private bool? HasText; /// <summary>Is this <see cref="Label"/> currently fading in (true) or out (false)?</summary> private bool FadingIn; /// <summary>Time into current fade.</summary> private float FadeTimer; /// <summary> /// Value to multiply alpha by to achieve desired alpha level? This is used when alpha is /// controlled by view angle, to allow manual changes in alpha or fading animations to be /// combined with this view-dependant alpha logic. /// </summary> /// <remarks> /// This value starts at 1f to ensure no change in alpha until a new value is set. /// </remarks> private float AlphaMultiplier = 1f; /// <summary> /// Required <see cref="CanvasGroup"/>, used for optionally fading all parts of this /// <see cref="Label"/> in or out as <see cref="Camera.main"/> looks towards or away from it. /// </summary> /// <remarks> /// This variable is auto-found on first access, allowing this <see cref="CanvasGroup"/> to be /// accessed at any time without having to check if it is null. /// </remarks> private CanvasGroup CanvasGroup { get { if (_CanvasGroup == null) { _CanvasGroup = GetComponent<CanvasGroup>(); } return _CanvasGroup; } } /// <summary> /// Actual stored <see cref="CanvasGroup"/>. This is stored in this way to allow /// <see cref="Label.CanvasGroup"/> to be used at any time without having to check if it is /// null. /// </summary> private CanvasGroup _CanvasGroup; /// <summary>Has this <see cref="Label"/> been setup yet?</summary> /// <remarks>Allows setup to be intelligently called when needed?</remarks> private bool IsSetup; /// <summary> /// All <see cref="Label"/>s in the current scene. Used to perform group actions, like starting /// all <see cref="Label"/>s fading in or out together, or hiding the <see cref="Text"/> part of /// all <see cref="Label"/>s. /// </summary> private static readonly List<Label> AllLabels = new List<Label>(); /// <summary> /// Setup this <see cref="Label"/> if (and only if) have not already done so. /// </summary> private void Start() { TrySetup(); } /// <summary> /// Setup this <see cref="Label"/> if (and only if) have not already done so. /// </summary> protected void TrySetup() { // Skip if have already setup this Label. if (IsSetup) { return; } // Add to list of all Labels, so can fade all Labels in/out together. AllLabels.Add(this); // If this Label is meant to start faded out, make invisible now. if (StartFadedOut) { AlphaMultiplier = 0f; CanvasGroup.alpha = 0f; } // Flag this label as now set up. IsSetup = true; } /// <summary>Set the specific text to display on this <see cref="Label"/>.</summary> /// <param name="text">Text to show on this <see cref="Label"/>.</param> internal void SetText(string text) { // Make sure this label is setup. TrySetup(); // Print an error if no Text element has been given. if (!CanFindText()) { // Note: 'name' and 'GetType()' just give the name of the GameObject this script is on, and // the name of this script respectively. Debug.LogErrorFormat( "No Text element set for {0}.{1}, which requires a UI.Text element to " + "show given text \"{2}\".", name, GetType(), text); return; } // Name this GameObject based on given text (to make debugging easier) and display the text. gameObject.name = string.Concat("Label: ", text); Text.text = text; // Start this Label tracking the Camera (unless already doing so). if (!IsTrackingCamera) { StartCoroutine(TrackCamera()); } // Optionally start fading in. if (AutoFadeIn) { StartFadingIn(); } } /// <summary>Set a new alpha value for this <see cref="Label"/>.</summary> /// <param name="newAlpha"> /// New alpha value to set, assumed to be a valid value (within the range of 0f to 1f). /// </param> internal void SetAlpha(float newAlpha) { // Make sure this label is setup. TrySetup(); // Print an error if no Text element has been given. if (!CanFindText()) { Debug.LogErrorFormat( "No Text element set for {0}.{1}, which requires a UI.Text element to " + "apply new alpha value of {2:N2} to.", name, GetType(), newAlpha); return; } // Set desired alpha level. ApplyAlpha(newAlpha); // Start this Label tracking the Camera (unless already doing so). if (!IsTrackingCamera) { StartCoroutine(TrackCamera()); } } /// <summary>Start this <see cref="Label"/> fading in smoothly over time.</summary> internal void StartFadingIn() { StartFading(true); } /// <summary>Start this <see cref="Label"/> fading in smoothly over time.</summary> internal void StartFadingOut() { StartFading(false); } /// <summary>Start all <see cref="Label"/>s fading in smoothly over time.</summary> internal static void StartFadingAllIn() { StartFadingAll(true); } /// <summary>Start all <see cref="Label"/>s fading in smoothly over time.</summary> internal static void StartFadingAllOut() { StartFadingAll(false); } /// <summary>Shrink/grow all <see cref="Label"/>s by a given multiplier.</summary> /// <remarks> /// This is a class member. Calling <see cref="Label.ScaleAll"/> iterates over all in-scene /// <see cref="Label"/>s, scaling each. /// </remarks> /// <param name="multiplier"> /// Value to multiply current scale by for all <see cref="Label"/>s. /// </param> internal static void ScaleAll(float multiplier) { foreach (Label label in AllLabels) { label.Scale(multiplier); } } /// <summary>Hide all <see cref="Label"/>s.</summary> /// <remarks> /// This is a class member. Calling <see cref="Label.HideAll"/> iterates over all in-scene /// <see cref="Label"/>s, hiding each. /// </remarks> /// <param name="hide">Optionally set to true to hide, false to show.</param> internal static void HideAll(bool hide = true) { HideOrShowAll(hide); } /// <summary>Hide all <see cref="Label"/>s.</summary> /// <remarks> /// This is a class member. Calling the static method <see cref="Label.ShowAll"/> iterates over /// all in-scene <see cref="Label"/>s, showing each. /// </remarks> /// <param name="show">Optionally set to true to show, false to hide.</param> internal static void ShowAll(bool show = true) { HideOrShowAll(!show); } /// <summary>Hide the <see cref="Text"/> part of all <see cref="Label"/>s.</summary> /// <remarks> /// This is a class member. Calling the static method <see cref="Label.HideAllText"/> iterates /// over all in-scene <see cref="Label"/>s, hiding the <see cref="Text"/> part of each. /// </remarks> /// <param name="hide">Optionally set to true to hide, false to show.</param> internal static void HideAllText(bool hide = true) { HideOrShowAllText(hide); } /// <summary>Hide the <see cref="Text"/> part of all <see cref="Label"/>s.</summary> /// <remarks> /// This is a class member. Calling the static method <see cref="Label.ShowAllText"/> iterates /// over all in-scene <see cref="Label"/>s, showing the <see cref="Text"/> part of each. /// </remarks> /// <param name="show">Optionally set to true to hide, false to show.</param> internal static void ShowAllText(bool show = true) { HideOrShowAllText(!show); } /// <summary>Turn to face the <see cref="Camera.main"/> every frame.</summary> /// <remarks> /// If <see cref="FadeWithView"/> is enabled, this <see cref="Label"/> will also fade in or out /// as <see cref="Camera.main"/> looks towards or away from it. /// </remarks> private IEnumerator TrackCamera() { // Flag that this coroutine has started (so it will not be redundantly restarted later). IsTrackingCamera = true; // Start facing Camera. while (true) { // Get the current rotation of the Camera. If Labels are meant to turn only (y-rotation // only, ignoring x-rotation) then remove the x-component of this rotation. Quaternion cameraRotation; if (TurnOnly) { Vector3 cameraEuler = Camera.main.transform.eulerAngles; cameraRotation = Quaternion.Euler(0f, cameraEuler.y, 0f); } else { cameraRotation = Camera.main.transform.rotation; } // Match Label's rotation to that of the Camera. This is so all Labels will be parallel to // each other, yet all be readable to the Camera. Also note that, for any other kind of // GameObject, the inverse of the Camera's rotation should be used, so that this Label is // facing the opposite direction of the Camera (i.e. towards the Camera). But Unity creates // all UI elements and quads with their textured side facing backwards. So to make any UI // element look at the Camera, we have to make it face the same direction as the Camera. transform.rotation = cameraRotation; // Optionally fade in/out based on view angle, so that the Label closest to the view center // is the clearest, and all other Labels are semi-transparent. if (FadeWithView) { FadeWithViewAngle(); } // Wait for next frame. yield return null; } } /// <summary>Fade this <see cref="Label"/> in or out over time.</summary> private IEnumerator Fade() { // Flag that this coroutine has started (so it will not be redundantly restarted later). IsFading = true; // Start fading in/out. while (true) { // Count up until end of fading animation. FadeTimer += Time.smoothDeltaTime; // If have reached end, apply final alpha value (fully faded in or out). if (FadeTimer >= FadeTime) { ApplyAlpha(FadingIn ? 1f : 0f); IsFading = false; break; } // If still fading, determine current fade value. float fadePercent = FadeTimer / FadeTime; // Convert to alpha based on whether fading in or out, smoothing result towards 1f so will // smoothly approach/leave fully opaque and apply. float alpha = FadingIn ? fadePercent : 1f - fadePercent; alpha = Smooth(alpha); ApplyAlpha(alpha); // Wait for next frame. yield return null; } } /// <summary>Start this <see cref="Label"/> fading in or out smoothly over time.</summary> /// <params name="fadeIn">True to start fading in, false to start fading out.</params> private void StartFading(bool fadeIn) { // Make sure this label is setup. TrySetup(); // Print an error if no Text element has been given. if (!CanFindText()) { Debug.LogErrorFormat( "No Text element set for {0}.{1}, which requires a UI.Text element to " + "start fading {2}.", name, GetType(), fadeIn ? "in" : "out"); return; } // Setup start of fade. AlphaMultiplier = 0f; FadeTimer = 0f; FadingIn = fadeIn; // Start this Label fading (unless already fading). Note that if already fading, then the // change in variables above will set up the new fade with the existing coroutine. if (!IsFading) { StartCoroutine(Fade()); } // Make this Label always face the Camera (unless already facing the Camera). if (!IsTrackingCamera) { StartCoroutine(TrackCamera()); } } /// <summary>Start all <see cref="Label"/>s fading in or out smoothly over time.</summary> /// <remarks> /// This is a class member. Calling the static method <see cref="Label.StartFadingAll"/> /// iterates over all in-scene <see cref="Label"/>s, calling <see cref="StartFading"/> on each. /// </remarks> /// <params name="fadeIn">True to start fading in, false to start fading out.</params> private static void StartFadingAll(bool fadeIn) { // Print an error if there are no Labels to start fading. if (AllLabels.Count == 0) { Debug.LogErrorFormat( "No {0} found in the current scene, so cannot start fading them all " + "{1}.", typeof(Label), fadeIn ? "in" : "out"); return; } // Traverse list of all Labels in the scene, starting fading them all in.out. Labels are // traversed in reverse order so that any null/deleted Labels can be removed without affecting // future list-indices. for (int i = AllLabels.Count - 1; i >= 0; i--) { if (AllLabels[i] == null) { AllLabels.RemoveAt(i); } else { AllLabels[i].StartFading(fadeIn); } } } ///< summary> /// Set desired alpha level. If alpha is controlled by view angle, apply alpha through the use /// of a multiplier, otherwise apply alpha directly to <see cref="CanvasGroup"/> now. /// </summary> private void ApplyAlpha(float newAlpha) { if (FadeWithView) { AlphaMultiplier = newAlpha; } else { CanvasGroup.alpha = newAlpha; } } /// <summary> /// Fade all parts of this <see cref="Label"/> in or out as <see cref="Camera.main"/> faces /// towards or away from this <see cref="Label"/>. /// </summary> /// <remarks> /// This is to avoid the screen becoming too visually cluttered with fully-opaque /// <see cref="Label"/>s, naturally highlighting the <see cref="Label"/>s /// <see cref="Camera.main"/> is looking at and fading out the rest. /// </remarks> private void FadeWithViewAngle() { // Determine how close the Camera is to directly looking at this Label. Vector3 direction = (Text.transform.position - Camera.main.transform.position).normalized; float dotProduct = Vector3.Dot(Camera.main.transform.forward, direction); float angle = Mathf.Acos(dotProduct) * Mathf.Rad2Deg; // Convert angle to an alpha value of 1f when looking directly at this Label, and nearly // transparent (0.1f) when looking 45 degrees or more away from this Label. float alpha; if (angle > 45f) { alpha = 0.1f; } else { alpha = (1f - angle / 45f) * 0.9f + 0.1f; // Smooth alpha towards 1f, so Label will stay at nearly 100% alpha for longer when looking // roughly near Label. alpha = Smooth(alpha); } // Apply alpha to Canvas Group to fade Label in/out. Multiply by alpha multiplier to allow // alpha to be influenced by manual changes or by fading in/out. CanvasGroup.alpha = alpha * AlphaMultiplier; } /// <summary>Shrink/grow this <see cref="Label"/> by a given multiplier.</summary> /// <param name="multiplier">Value to multiply current scale by.</param> private void Scale(float multiplier) { // Make sure this label is setup before adjusting its scale TrySetup(); gameObject.transform.localScale *= multiplier; } /// <summary>Hide/show all <see cref="Label"/>s.</summary> /// This is a class member. Calling the static method <see cref="Label.HideOrShowAll"/> iterates /// over all in-scene <see cref="Label"/>s, calling <see cref="HideOrShow"/> on each. /// <param name="hide">True to hide, false to show if hidden.</param> private static void HideOrShowAll(bool hide) { foreach (Label label in AllLabels) { label.HideOrShow(hide); } } /// <summary>Hide/show this <see cref="Label"/>.</summary> /// <param name="hide">True to hide, false to show if hidden.</param> private void HideOrShow(bool hide) { // Make sure this label is setup, then activate/deactivate it's GameObject to show/hide it. TrySetup(); gameObject.SetActive(!hide); } /// <summary>Hide/show the <see cref="Text"/> part of all <see cref="Label"/>s.</summary> /// <remarks> /// This is a class member. Calling the static method <see cref="Label.HideOrShowAllText"/> /// iterates over all in-scene <see cref="Label"/>s, calling <see cref="HideOrShowText"/> on /// each. /// </remarks> /// <param name="hide">True to hide text, false to show if hidden.</param> private static void HideOrShowAllText(bool hide) { foreach (Label label in AllLabels) { label.HideOrShowText(hide); } } /// <summary>Hide/show the <see cref="Text"/> part of this <see cref="Label"/>.</summary> /// <param name="hide">True to hide text, false to show if hidden.</param> private void HideOrShowText(bool hide) { // Make sure this label is setup, then if a text element can be found, hide/show it. TrySetup(); if (CanFindText()) { Text.gameObject.SetActive(!hide); } } /// <summary>See if a <see cref="Text"/> element has been given.</summary> private bool CanFindText() { // If have not already done so, check for Text element, storing result for later re-use if // required. if (!HasText.HasValue) { HasText = Text != null; } return HasText.Value; } /// <summary>Return a given value smoothed towards 1f.</summary> private static float Smooth(float value) { return Mathf.Sin(value * Mathf.PI / 2f); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; namespace System { internal class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid { #region QCalls [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser); #endregion public SafeTypeNameParserHandle() : base(true) { } protected override bool ReleaseHandle() { _ReleaseTypeNameParser(handle); handle = IntPtr.Zero; return true; } } internal sealed class TypeNameParser : IDisposable { #region QCalls [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString); #endregion #region Static Members internal static Type? GetType( string typeName, Func<AssemblyName, Assembly?>? assemblyResolver, Func<Assembly?, string, bool, Type?>? typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { if (typeName == null) throw new ArgumentNullException(nameof(typeName)); if (typeName.Length > 0 && typeName[0] == '\0') throw new ArgumentException(SR.Format_StringZeroLength); Type? ret = null; SafeTypeNameParserHandle? handle = CreateTypeNameParser(typeName, throwOnError); if (handle != null) { // If we get here the typeName must have been successfully parsed. // Let's construct the Type object. using (TypeNameParser parser = new TypeNameParser(handle)) { ret = parser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } } return ret; } #endregion #region Private Data Members private readonly SafeTypeNameParserHandle m_NativeParser; private static readonly char[] SPECIAL_CHARS = { ',', '[', ']', '&', '*', '+', '\\' }; /* see typeparse.h */ #endregion #region Constructor and Disposer private TypeNameParser(SafeTypeNameParserHandle handle) { m_NativeParser = handle; } public void Dispose() { m_NativeParser.Dispose(); } #endregion #region private Members private unsafe Type? ConstructType( Func<AssemblyName, Assembly?>? assemblyResolver, Func<Assembly?, string, bool, Type?>? typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { // assembly name Assembly? assembly = null; string asmName = GetAssemblyName(); // GetAssemblyName never returns null Debug.Assert(asmName != null); if (asmName.Length > 0) { assembly = ResolveAssembly(asmName, assemblyResolver, throwOnError, ref stackMark); if (assembly == null) { // Cannot resolve the assembly. If throwOnError is true we should have already thrown. return null; } } string[]? names = GetNames(); if (names == null) { // This can only happen if the type name is an empty string or if the first char is '\0' if (throwOnError) throw new TypeLoadException(SR.Arg_TypeLoadNullStr); return null; } Type? baseType = ResolveType(assembly, names, typeResolver, throwOnError, ignoreCase, ref stackMark); if (baseType == null) { // Cannot resolve the type. If throwOnError is true we should have already thrown. Debug.Assert(!throwOnError); return null; } SafeTypeNameParserHandle[]? typeArguments = GetTypeArguments(); Type?[]? types = null; if (typeArguments != null) { types = new Type[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { Debug.Assert(typeArguments[i] != null); using (TypeNameParser argParser = new TypeNameParser(typeArguments[i])) { types[i] = argParser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } if (types[i] == null) { // If throwOnError is true argParser.ConstructType should have already thrown. Debug.Assert(!throwOnError); return null; } } } int[]? modifiers = GetModifiers(); fixed (int* ptr = modifiers) { IntPtr intPtr = new IntPtr(ptr); return RuntimeTypeHandle.GetTypeHelper(baseType, types!, intPtr, modifiers == null ? 0 : modifiers.Length); } } private static Assembly? ResolveAssembly(string asmName, Func<AssemblyName, Assembly?>? assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark) { Debug.Assert(!string.IsNullOrEmpty(asmName)); Assembly? assembly = null; if (assemblyResolver == null) { if (throwOnError) { assembly = RuntimeAssembly.InternalLoad(asmName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } else { // When throwOnError is false we should only catch FileNotFoundException. // Other exceptions like BadImangeFormatException should still fly. try { assembly = RuntimeAssembly.InternalLoad(asmName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } catch (FileNotFoundException) { return null; } } } else { assembly = assemblyResolver(new AssemblyName(asmName)); if (assembly == null && throwOnError) { throw new FileNotFoundException(SR.Format(SR.FileNotFound_ResolveAssembly, asmName)); } } return assembly; } private static Type? ResolveType(Assembly? assembly, string[] names, Func<Assembly?, string, bool, Type?>? typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { Debug.Assert(names != null && names.Length > 0); Type? type = null; // both the customer provided and the default type resolvers accept escaped type names string OuterMostTypeName = EscapeTypeName(names[0]); // Resolve the top level type. if (typeResolver != null) { type = typeResolver(assembly, OuterMostTypeName, ignoreCase); if (type == null && throwOnError) { string errorString = assembly == null ? SR.Format(SR.TypeLoad_ResolveType, OuterMostTypeName) : SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, OuterMostTypeName, assembly.FullName); throw new TypeLoadException(errorString); } } else { if (assembly == null) { type = RuntimeType.GetType(OuterMostTypeName, throwOnError, ignoreCase, ref stackMark); } else { type = assembly.GetType(OuterMostTypeName, throwOnError, ignoreCase); } } // Resolve nested types. if (type != null) { BindingFlags bindingFlags = BindingFlags.NonPublic | BindingFlags.Public; if (ignoreCase) bindingFlags |= BindingFlags.IgnoreCase; for (int i = 1; i < names.Length; i++) { type = type.GetNestedType(names[i], bindingFlags); if (type == null) { if (throwOnError) throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1])); else break; } } } return type; } private static string EscapeTypeName(string name) { if (name.IndexOfAny(SPECIAL_CHARS) < 0) return name; StringBuilder sb = StringBuilderCache.Acquire(); foreach (char c in name) { if (Array.IndexOf<char>(SPECIAL_CHARS, c) >= 0) sb.Append('\\'); sb.Append(c); } return StringBuilderCache.GetStringAndRelease(sb); } private static SafeTypeNameParserHandle? CreateTypeNameParser(string typeName, bool throwOnError) { SafeTypeNameParserHandle? retHandle = null; _CreateTypeNameParser(typeName, JitHelpers.GetObjectHandleOnStack(ref retHandle), throwOnError); return retHandle; } private string[]? GetNames() { string[]? names = null; _GetNames(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref names)); return names; } private SafeTypeNameParserHandle[]? GetTypeArguments() { SafeTypeNameParserHandle[]? arguments = null; _GetTypeArguments(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref arguments)); return arguments; } private int[]? GetModifiers() { int[]? modifiers = null; _GetModifiers(m_NativeParser, JitHelpers.GetObjectHandleOnStack(ref modifiers)); return modifiers; } private string GetAssemblyName() { string? assemblyName = null; _GetAssemblyName(m_NativeParser, JitHelpers.GetStringHandleOnStack(ref assemblyName)); return assemblyName!; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinSByte() { var test = new SimpleBinaryOpTest__MinSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinSByte testClass) { var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinSByte testClass) { fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public SimpleBinaryOpTest__MinSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.Min( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Min( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Min( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Min), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<SByte>* pClsVar1 = &_clsVar1) fixed (Vector256<SByte>* pClsVar2 = &_clsVar2) { var result = Avx2.Min( Avx.LoadVector256((SByte*)(pClsVar1)), Avx.LoadVector256((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinSByte(); var result = Avx2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MinSByte(); fixed (Vector256<SByte>* pFld1 = &test._fld1) fixed (Vector256<SByte>* pFld2 = &test._fld2) { var result = Avx2.Min( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<SByte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.Min( Avx.LoadVector256((SByte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.Min( Avx.LoadVector256((SByte*)(&test._fld1)), Avx.LoadVector256((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<SByte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Min(left[0], right[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Min(left[i], right[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Min)}<SByte>(Vector256<SByte>, Vector256<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using UnityEngine; using System.Collections.Generic; using DPek.Raconteur.RenPy.Display; using DPek.Raconteur.RenPy.Parser; using DPek.Raconteur.RenPy.Script; using DPek.Raconteur.RenPy.State; using System.Collections; namespace DPek.Raconteur.RenPy { public class RenPyViewBasic : MonoBehaviour { public bool m_autoStart; public RenPyController m_controller; void Start() { if (m_autoStart) { m_controller.StartDialog(); } } void Update() { if (!m_controller.Running) { m_controller.StopDialog(); return; } if (m_controller.GetCurrentStatement() == null) { m_controller.NextStatement(); } RenPyStatementType mode = m_controller.GetCurrentStatement().Type; switch (mode) { case RenPyStatementType.SAY: // Check for input to go to next line if (Input.GetMouseButtonDown(0)) { m_controller.NextStatement(); } break; case RenPyStatementType.PAUSE: // Check for input to go to next line var pause = m_controller.GetCurrentStatement() as RenPyPause; if (pause.WaitForInput && Input.GetMouseButtonDown(0)) { m_controller.NextStatement(); } // Or wait until we can go to the next line else { StartCoroutine(WaitNextStatement(pause.WaitTime)); } break; case RenPyStatementType.MENU: // Do nothing break; default: // Show nothing for this line, proceed to the next one. m_controller.NextStatement(); Update(); // Update immediately to prevent delay break; } } void OnGUI() { if (!m_controller.Running || m_controller.GetCurrentStatement() == null) { return; } Rect rect; GUIStyle style = new GUIStyle(); style.alignment = TextAnchor.MiddleCenter; style.normal.textColor = Color.white; style.fontSize = 15; style.wordWrap = true; // Draw background var bg = m_controller.GetBackgroundImage(); if (bg != null) { var pos = new Rect(0, 0, Screen.width, Screen.height); GUI.DrawTexture(pos, bg.Texture, ScaleMode.ScaleAndCrop); } // Draw images var images = m_controller.GetImages(); foreach (RenPyImageData image in images) { float screenWidth = Screen.width; float screenHeight = Screen.height; float texWidth = image.Texture.width; float texHeight = image.Texture.height; var pos = new Rect(0, 0, texWidth, texHeight); switch(image.Alignment) { case Util.RenPyAlignment.BottomCenter: pos.x = screenWidth / 2 - texWidth / 2; pos.y = screenHeight - texHeight; break; case Util.RenPyAlignment.BottomLeft: pos.x = 0; pos.y = screenHeight - texHeight; break; case Util.RenPyAlignment.BottomRight: pos.x = screenWidth - texWidth; pos.y = screenHeight - texHeight; break; case Util.RenPyAlignment.Center: pos.x = screenWidth / 2 - texWidth / 2; pos.y = screenHeight / 2 - texHeight / 2; break; case Util.RenPyAlignment.LeftCenter: pos.x = 0; pos.y = screenHeight / 2 - texHeight / 2; break; case Util.RenPyAlignment.RightCenter: pos.x = screenHeight - texWidth; pos.y = screenHeight / 2 - texHeight / 2; break; case Util.RenPyAlignment.TopCenter: pos.x = screenWidth / 2 - texWidth / 2; pos.y = 0; break; case Util.RenPyAlignment.TopLeft: pos.x = 0; pos.y = 0; break; case Util.RenPyAlignment.TopRight: pos.x = screenHeight - texWidth; pos.y = 0; break; } GUI.DrawTexture(pos, image.Texture, ScaleMode.ScaleToFit); } // Draw the window if needed if (m_controller.ShouldDrawWindow()) { DrawBox(50, Screen.height - 200, Screen.width - 100, 200); } // Draw text switch (m_controller.GetCurrentStatement().Type) { case RenPyStatementType.SAY: var speech = m_controller.GetCurrentStatement() as RenPySay; // Render the speaker int y = Screen.height - 200; int width = Screen.width - 100; rect = new Rect(50, y, width, 200); style.alignment = TextAnchor.UpperLeft; RenPyCharacterData speaker = m_controller.GetSpeaker(speech); var oldColor = style.normal.textColor; style.normal.textColor = speaker.Color; GUI.Label(rect, speaker.Name, style); style.normal.textColor = oldColor; // Render the speech style.alignment = TextAnchor.MiddleCenter; rect = new Rect(50, y + 50, width, 100); GUI.Label(rect, speech.Text, style); break; case RenPyStatementType.MENU: var menu = m_controller.GetCurrentStatement() as RenPyMenu; // Display the choices int height = 30; int numChoices = menu.GetChoices().Count; int yPos = Mathf.Max(0, Screen.height/2 - numChoices*height); rect = new Rect(100, yPos, Screen.width-200, height); foreach (var choice in menu.GetChoices()) { // Check if a choice was selected DrawBox(100, rect.y + 5, rect.width, rect.height - 10); if (GUI.Button(rect, choice, style)) { m_controller.PickChoice(menu, choice); m_controller.NextStatement(); } rect.y += height; } break; } } bool waiting = false; private IEnumerator WaitNextStatement(float time) { if (!waiting) { waiting = true; yield return new WaitForSeconds(time); m_controller.NextStatement(); waiting = false; } } private void DrawBox(float x, float y, float width, float height) { Rect rect = new Rect(x, y, width, height); Texture2D texture = new Texture2D(1, 1); texture.SetPixel(0, 0, new Color(0, 0, 0, 0.6f)); texture.Apply(); GUI.skin.box.normal.background = texture; GUI.Box(rect, GUIContent.none); } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ //#define USE_ACTIVE_CONTACT_SET using System.Diagnostics; using FarseerPhysics.Collision; using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Contacts { /// <summary> /// A contact edge is used to connect bodies and contacts together /// in a contact graph where each body is a node and each contact /// is an edge. A contact edge belongs to a doubly linked list /// maintained in each attached body. Each contact has two contact /// nodes, one for each attached body. /// </summary> public sealed class ContactEdge { /// <summary> /// The contact /// </summary> public Contact Contact; /// <summary> /// The next contact edge in the body's contact list /// </summary> public ContactEdge Next; /// <summary> /// Provides quick access to the other body attached. /// </summary> public Body Other; /// <summary> /// The previous contact edge in the body's contact list /// </summary> public ContactEdge Prev; } /// <summary> /// The class manages contact between two shapes. A contact exists for each overlapping /// AABB in the broad-phase (except if filtered). Therefore a contact object may exist /// that has no contact points. /// </summary> public class Contact { #region Properties/Fields public Fixture FixtureA; public Fixture FixtureB; public float Friction; public float Restitution; /// <summary> /// Get the contact manifold. Do not modify the manifold unless you understand the internals of Box2D. /// </summary> public Manifold Manifold; /// Get or set the desired tangent speed for a conveyor belt behavior. In meters per second. public float TangentSpeed; /// <summary> /// Enable/disable this contact. This can be used inside the pre-solve contact listener. The contact is only disabled for the current /// time step (or sub-step in continuous collisions). /// NOTE: If you are setting Enabled to a constant true or false, use the explicit Enable() or Disable() functions instead to /// save the CPU from doing a branch operation. /// </summary> public bool Enabled; /// <summary> /// Get the child primitive index for fixture A. /// </summary> /// <value>The child index A.</value> public int ChildIndexA { get; internal set; } /// <summary> /// Get the child primitive index for fixture B. /// </summary> /// <value>The child index B.</value> public int ChildIndexB { get; internal set; } /// <summary> /// Determines whether this contact is touching. /// </summary> /// <returns> /// <c>true</c> if this instance is touching; otherwise, <c>false</c>. /// </returns> public bool IsTouching { get; set; } internal bool islandFlag; internal bool toiFlag; internal bool filterFlag; ContactType _type; static EdgeShape _edge = new EdgeShape(); static ContactType[,] _contactRegisters = new[,] { { ContactType.Circle, ContactType.EdgeAndCircle, ContactType.PolygonAndCircle, ContactType.ChainAndCircle, }, { ContactType.EdgeAndCircle, ContactType.NotSupported, // 1,1 is invalid (no ContactType.Edge) ContactType.EdgeAndPolygon, ContactType.NotSupported, // 1,3 is invalid (no ContactType.EdgeAndLoop) }, { ContactType.PolygonAndCircle, ContactType.EdgeAndPolygon, ContactType.Polygon, ContactType.ChainAndPolygon, }, { ContactType.ChainAndCircle, ContactType.NotSupported, // 3,1 is invalid (no ContactType.EdgeAndLoop) ContactType.ChainAndPolygon, ContactType.NotSupported, // 3,3 is invalid (no ContactType.Loop) }, }; // Nodes for connecting bodies. internal ContactEdge _nodeA = new ContactEdge(); internal ContactEdge _nodeB = new ContactEdge(); internal int _toiCount; internal float _toi; #endregion Contact(Fixture fA, int indexA, Fixture fB, int indexB) { Reset(fA, indexA, fB, indexB); } public void ResetRestitution() { Restitution = Settings.MixRestitution(FixtureA.Restitution, FixtureB.Restitution); } public void ResetFriction() { Friction = Settings.MixFriction(FixtureA.Friction, FixtureB.Friction); } /// <summary> /// Gets the world manifold. /// </summary> public void GetWorldManifold(out Vector2 normal, out FixedArray2<Vector2> points) { var bodyA = FixtureA.Body; var bodyB = FixtureB.Body; var shapeA = FixtureA.Shape; var shapeB = FixtureB.Shape; ContactSolver.WorldManifold.Initialize(ref Manifold, ref bodyA._xf, shapeA.Radius, ref bodyB._xf, shapeB.Radius, out normal, out points); } void Reset(Fixture fA, int indexA, Fixture fB, int indexB) { Enabled = true; IsTouching = false; islandFlag = false; filterFlag = false; toiFlag = false; FixtureA = fA; FixtureB = fB; ChildIndexA = indexA; ChildIndexB = indexB; Manifold.PointCount = 0; _nodeA.Contact = null; _nodeA.Prev = null; _nodeA.Next = null; _nodeA.Other = null; _nodeB.Contact = null; _nodeB.Prev = null; _nodeB.Next = null; _nodeB.Other = null; _toiCount = 0; //FPE: We only set the friction and restitution if we are not destroying the contact if (FixtureA != null && FixtureB != null) { Friction = Settings.MixFriction(FixtureA.Friction, FixtureB.Friction); Restitution = Settings.MixRestitution(FixtureA.Restitution, FixtureB.Restitution); } TangentSpeed = 0; } /// <summary> /// Update the contact manifold and touching status. /// Note: do not assume the fixture AABBs are overlapping or are valid. /// </summary> /// <param name="contactManager">The contact manager.</param> internal void Update(ContactManager contactManager) { var bodyA = FixtureA.Body; var bodyB = FixtureB.Body; if (FixtureA == null || FixtureB == null) return; var oldManifold = Manifold; // Re-enable this contact. Enabled = true; bool touching; var wasTouching = IsTouching; var sensor = FixtureA.IsSensor || FixtureB.IsSensor; // Is this contact a sensor? if (sensor) { var shapeA = FixtureA.Shape; var shapeB = FixtureB.Shape; touching = Collision.Collision.TestOverlap(shapeA, ChildIndexA, shapeB, ChildIndexB, ref bodyA._xf, ref bodyB._xf); // Sensors don't generate manifolds. Manifold.PointCount = 0; } else { Evaluate(ref Manifold, ref bodyA._xf, ref bodyB._xf); touching = Manifold.PointCount > 0; // Match old contact ids to new contact ids and copy the // stored impulses to warm start the solver. for (int i = 0; i < Manifold.PointCount; ++i) { var mp2 = Manifold.Points[i]; mp2.NormalImpulse = 0.0f; mp2.TangentImpulse = 0.0f; var id2 = mp2.Id; for (int j = 0; j < oldManifold.PointCount; ++j) { var mp1 = oldManifold.Points[j]; if (mp1.Id.Key == id2.Key) { mp2.NormalImpulse = mp1.NormalImpulse; mp2.TangentImpulse = mp1.TangentImpulse; break; } } Manifold.Points[i] = mp2; } if (touching != wasTouching) { bodyA.IsAwake = true; bodyB.IsAwake = true; } } IsTouching = touching; if (wasTouching == false) { if (touching) { if (Settings.AllCollisionCallbacksAgree) { bool enabledA = true, enabledB = true; // Report the collision to both participants. Track which ones returned true so we can // later call OnSeparation if the contact is disabled for a different reason. if (FixtureA.OnCollision != null) foreach (OnCollisionEventHandler handler in FixtureA.OnCollision.GetInvocationList()) enabledA = handler(FixtureA, FixtureB, this) && enabledA; // Reverse the order of the reported fixtures. The first fixture is always the one that the // user subscribed to. if (FixtureB.OnCollision != null) foreach (OnCollisionEventHandler handler in FixtureB.OnCollision.GetInvocationList()) enabledB = handler(FixtureB, FixtureA, this) && enabledB; Enabled = enabledA && enabledB; // BeginContact can also return false and disable the contact if (enabledA && enabledB && contactManager.OnBeginContact != null) Enabled = contactManager.OnBeginContact(this); } else { // Report the collision to both participants: if (FixtureA.OnCollision != null) foreach (OnCollisionEventHandler handler in FixtureA.OnCollision.GetInvocationList()) Enabled = handler(FixtureA, FixtureB, this); //Reverse the order of the reported fixtures. The first fixture is always the one that the //user subscribed to. if (FixtureB.OnCollision != null) foreach (OnCollisionEventHandler handler in FixtureB.OnCollision.GetInvocationList()) Enabled = handler(FixtureB, FixtureA, this); //BeginContact can also return false and disable the contact if (contactManager.OnBeginContact != null) Enabled = contactManager.OnBeginContact(this); } // If the user disabled the contact (needed to exclude it in TOI solver) at any point by // any of the callbacks, we need to mark it as not touching and call any separation // callbacks for fixtures that didn't explicitly disable the collision. if (!Enabled) IsTouching = false; } } else { if (touching == false) { // Report the separation to both participants: if (FixtureA != null && FixtureA.OnSeparation != null) FixtureA.OnSeparation(FixtureA, FixtureB); //Reverse the order of the reported fixtures. The first fixture is always the one that the //user subscribed to. if (FixtureB != null && FixtureB.OnSeparation != null) FixtureB.OnSeparation(FixtureB, FixtureA); if (contactManager.OnEndContact != null) contactManager.OnEndContact(this); } } if (sensor) return; if (contactManager.OnPreSolve != null) contactManager.OnPreSolve(this, ref oldManifold); } /// <summary> /// Evaluate this contact with your own manifold and transforms. /// </summary> /// <param name="manifold">The manifold.</param> /// <param name="transformA">The first transform.</param> /// <param name="transformB">The second transform.</param> void Evaluate(ref Manifold manifold, ref Transform transformA, ref Transform transformB) { switch (_type) { case ContactType.Polygon: Collision.Collision.CollidePolygons(ref manifold, (PolygonShape) FixtureA.Shape, ref transformA, (PolygonShape) FixtureB.Shape, ref transformB); break; case ContactType.PolygonAndCircle: Collision.Collision.CollidePolygonAndCircle(ref manifold, (PolygonShape) FixtureA.Shape, ref transformA, (CircleShape) FixtureB.Shape, ref transformB); break; case ContactType.EdgeAndCircle: Collision.Collision.CollideEdgeAndCircle(ref manifold, (EdgeShape) FixtureA.Shape, ref transformA, (CircleShape) FixtureB.Shape, ref transformB); break; case ContactType.EdgeAndPolygon: Collision.Collision.CollideEdgeAndPolygon(ref manifold, (EdgeShape) FixtureA.Shape, ref transformA, (PolygonShape) FixtureB.Shape, ref transformB); break; case ContactType.ChainAndCircle: var chain = (ChainShape) FixtureA.Shape; chain.GetChildEdge(_edge, ChildIndexA); Collision.Collision.CollideEdgeAndCircle(ref manifold, _edge, ref transformA, (CircleShape) FixtureB.Shape, ref transformB); break; case ContactType.ChainAndPolygon: var loop2 = (ChainShape) FixtureA.Shape; loop2.GetChildEdge(_edge, ChildIndexA); Collision.Collision.CollideEdgeAndPolygon(ref manifold, _edge, ref transformA, (PolygonShape) FixtureB.Shape, ref transformB); break; case ContactType.Circle: Collision.Collision.CollideCircles(ref manifold, (CircleShape) FixtureA.Shape, ref transformA, (CircleShape) FixtureB.Shape, ref transformB); break; } } internal static Contact Create(Fixture fixtureA, int indexA, Fixture fixtureB, int indexB) { var type1 = fixtureA.Shape.ShapeType; var type2 = fixtureB.Shape.ShapeType; Debug.Assert(ShapeType.Unknown < type1 && type1 < ShapeType.TypeCount); Debug.Assert(ShapeType.Unknown < type2 && type2 < ShapeType.TypeCount); Contact c; var pool = fixtureA.Body._world._contactPool; if (pool.Count > 0) { c = pool.Dequeue(); if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon)) && !(type2 == ShapeType.Edge && type1 == ShapeType.Polygon)) c.Reset(fixtureA, indexA, fixtureB, indexB); else c.Reset(fixtureB, indexB, fixtureA, indexA); } else { // Edge+Polygon is non-symetrical due to the way Erin handles collision type registration. if ((type1 >= type2 || (type1 == ShapeType.Edge && type2 == ShapeType.Polygon)) && !(type2 == ShapeType.Edge && type1 == ShapeType.Polygon)) c = new Contact(fixtureA, indexA, fixtureB, indexB); else c = new Contact(fixtureB, indexB, fixtureA, indexA); } c._type = _contactRegisters[(int) type1, (int) type2]; return c; } internal void Destroy() { #if USE_ACTIVE_CONTACT_SET FixtureA.Body.World.ContactManager.RemoveActiveContact(this); #endif FixtureA.Body._world._contactPool.Enqueue(this); if (Manifold.PointCount > 0 && FixtureA.IsSensor == false && FixtureB.IsSensor == false) { FixtureA.Body.IsAwake = true; FixtureB.Body.IsAwake = true; } Reset(null, 0, null, 0); } #region Nested type: ContactType public enum ContactType { NotSupported, Polygon, PolygonAndCircle, Circle, EdgeAndPolygon, EdgeAndCircle, ChainAndPolygon, ChainAndCircle, } #endregion } }
using Lucene.Net.Support; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Lucene.Net.Util { /* * 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> /// Implements a combination of <seealso cref="java.util.WeakHashMap"/> and /// <seealso cref="java.util.IdentityHashMap"/>. /// Useful for caches that need to key off of a {@code ==} comparison /// instead of a {@code .equals}. /// /// <p>this class is not a general-purpose <seealso cref="java.util.Map"/> /// implementation! It intentionally violates /// Map's general contract, which mandates the use of the equals method /// when comparing objects. this class is designed for use only in the /// rare cases wherein reference-equality semantics are required. /// /// <p>this implementation was forked from <a href="http://cxf.apache.org/">Apache CXF</a> /// but modified to <b>not</b> implement the <seealso cref="java.util.Map"/> interface and /// without any set views on it, as those are error-prone and inefficient, /// if not implemented carefully. The map only contains <seealso cref="Iterator"/> implementations /// on the values and not-GCed keys. Lucene's implementation also supports {@code null} /// keys, but those are never weak! /// /// <p><a name="reapInfo" />The map supports two modes of operation: /// <ul> /// <li>{@code reapOnRead = true}: this behaves identical to a <seealso cref="java.util.WeakHashMap"/> /// where it also cleans up the reference queue on every read operation (<seealso cref="#get(Object)"/>, /// <seealso cref="#containsKey(Object)"/>, <seealso cref="#size()"/>, <seealso cref="#valueIterator()"/>), freeing map entries /// of already GCed keys.</li> /// <li>{@code reapOnRead = false}: this mode does not call <seealso cref="#reap()"/> on every read /// operation. In this case, the reference queue is only cleaned up on write operations /// (like <seealso cref="#put(Object, Object)"/>). this is ideal for maps with few entries where /// the keys are unlikely be garbage collected, but there are lots of <seealso cref="#get(Object)"/> /// operations. The code can still call <seealso cref="#reap()"/> to manually clean up the queue without /// doing a write operation.</li> /// </ul> /// /// @lucene.internal /// </summary> public sealed class WeakIdentityMap<K, V> where K : class { // LUCENENET TODO Make this class internal as it isn't required anywhere; need to have it exposed to tests though //private readonly ReferenceQueue<object> queue = new ReferenceQueue<object>(); private readonly IDictionary<IdentityWeakReference, V> BackingStore; private readonly bool ReapOnRead; /// <summary> /// Creates a new {@code WeakIdentityMap} based on a non-synchronized <seealso cref="HashMap"/>. /// The map <a href="#reapInfo">cleans up the reference queue on every read operation</a>. /// </summary> public static WeakIdentityMap<K, V> newHashMap() { return NewHashMap(false); } /// <summary> /// Creates a new {@code WeakIdentityMap} based on a non-synchronized <seealso cref="HashMap"/>. </summary> /// <param name="reapOnRead"> controls if the map <a href="#reapInfo">cleans up the reference queue on every read operation</a>. </param> public static WeakIdentityMap<K, V> NewHashMap(bool reapOnRead) { return new WeakIdentityMap<K, V>(new HashMap<IdentityWeakReference, V>(), reapOnRead); } /// <summary> /// Creates a new {@code WeakIdentityMap} based on a <seealso cref="ConcurrentHashMap"/>. /// The map <a href="#reapInfo">cleans up the reference queue on every read operation</a>. /// </summary> public static WeakIdentityMap<K, V> NewConcurrentHashMap() { return NewConcurrentHashMap(true); } /// <summary> /// Creates a new {@code WeakIdentityMap} based on a <seealso cref="ConcurrentHashMap"/>. </summary> /// <param name="reapOnRead"> controls if the map <a href="#reapInfo">cleans up the reference queue on every read operation</a>. </param> public static WeakIdentityMap<K, V> NewConcurrentHashMap(bool reapOnRead) { return new WeakIdentityMap<K, V>(new ConcurrentDictionary<IdentityWeakReference, V>(), reapOnRead); } /// <summary> /// Private only constructor, to create use the static factory methods. </summary> private WeakIdentityMap(IDictionary<IdentityWeakReference, V> backingStore, bool reapOnRead) { this.BackingStore = backingStore; this.ReapOnRead = reapOnRead; } /// <summary> /// Removes all of the mappings from this map. </summary> public void Clear() { BackingStore.Clear(); Reap(); } /// <summary> /// Returns {@code true} if this map contains a mapping for the specified key. </summary> public bool ContainsKey(object key) { if (ReapOnRead) { Reap(); } return BackingStore.ContainsKey(new IdentityWeakReference(key)); } /// <summary> /// Returns the value to which the specified key is mapped. </summary> public V Get(object key) { if (ReapOnRead) { Reap(); } V val; if (BackingStore.TryGetValue(new IdentityWeakReference(key), out val)) { return val; } else { return default(V); } } /// <summary> /// Associates the specified value with the specified key in this map. /// If the map previously contained a mapping for this key, the old value /// is replaced. /// </summary> public V Put(K key, V value) { Reap(); return BackingStore[new IdentityWeakReference(key)] = value; } public IEnumerable<K> Keys { // .NET port: using this method which mimics IDictionary instead of KeyIterator() get { foreach (var key in BackingStore.Keys) { var target = key.Target; if (target == null) continue; else if (target == NULL) yield return null; else yield return (K)target; } } } public IEnumerable<V> Values { get { if (ReapOnRead) Reap(); return BackingStore.Values; } } /// <summary> /// Returns {@code true} if this map contains no key-value mappings. </summary> public bool Empty { get { return Size() == 0; } } /// <summary> /// Removes the mapping for a key from this weak hash map if it is present. /// Returns the value to which this map previously associated the key, /// or {@code null} if the map contained no mapping for the key. /// A return value of {@code null} does not necessarily indicate that /// the map contained. /// </summary> public bool Remove(object key) { Reap(); return BackingStore.Remove(new IdentityWeakReference(key)); } /// <summary> /// Returns the number of key-value mappings in this map. this result is a snapshot, /// and may not reflect unprocessed entries that will be removed before next /// attempted access because they are no longer referenced. /// </summary> public int Size() { if (BackingStore.Count == 0) { return 0; } if (ReapOnRead) { Reap(); } return BackingStore.Count; } /*LUCENE TO-DO I don't think necessary /// <summary> /// Returns an iterator over all weak keys of this map. /// Keys already garbage collected will not be returned. /// this Iterator does not support removals. /// </summary> public IEnumerator<K> KeyIterator() { Reap(); IEnumerator<IdentityWeakReference> iterator = BackingStore.Keys.GetEnumerator(); // IMPORTANT: Don't use oal.util.FilterIterator here: // We need *strong* reference to current key after setNext()!!! return new IteratorAnonymousInnerClassHelper(this, iterator); } private class IteratorAnonymousInnerClassHelper : Iterator<K> { private readonly WeakIdentityMap<K,V> OuterInstance; private IEnumerator<IdentityWeakReference> Iterator; public IteratorAnonymousInnerClassHelper(WeakIdentityMap<K,V> outerInstance, IEnumerator<IdentityWeakReference> iterator) { this.OuterInstance = outerInstance; this.Iterator = iterator; next = null; nextIsSet = false; } // holds strong reference to next element in backing iterator: private object next; // the backing iterator was already consumed: private bool nextIsSet; / public virtual bool HasNext() { return nextIsSet || SetNext(); } public virtual K Next() { if (!HasNext()) { throw new Exception(); } Debug.Assert(nextIsSet); try { return (K) next; } finally { // release strong reference and invalidate current value: nextIsSet = false; next = null; } } public virtual void Remove() { throw new System.NotSupportedException(); } private bool SetNext() { Debug.Assert(!nextIsSet); while (Iterator.MoveNext()) { next = Iterator.Current; if (next == null) { // the key was already GCed, we can remove it from backing map: Iterator.remove(); } else { // unfold "null" special value: if (next == NULL) { next = null; } return nextIsSet = true; } } return false; } }*/ /// <summary> /// Returns an iterator over all values of this map. /// this iterator may return values whose key is already /// garbage collected while iterator is consumed, /// especially if {@code reapOnRead} is {@code false}. /// </summary> public IEnumerator<V> ValueIterator() { if (ReapOnRead) { Reap(); } return BackingStore.Values.GetEnumerator(); } /// <summary> /// this method manually cleans up the reference queue to remove all garbage /// collected key/value pairs from the map. Calling this method is not needed /// if {@code reapOnRead = true}. Otherwise it might be a good idea /// to call this method when there is spare time (e.g. from a background thread). </summary> /// <seealso cref= <a href="#reapInfo">Information about the <code>reapOnRead</code> setting</a> </seealso> public void Reap() { List<IdentityWeakReference> keysToRemove = new List<IdentityWeakReference>(); foreach (IdentityWeakReference zombie in BackingStore.Keys) { if (!zombie.IsAlive) { keysToRemove.Add(zombie); } } foreach (var key in keysToRemove) { BackingStore.Remove(key); } } // we keep a hard reference to our NULL key, so map supports null keys that never get GCed: internal static readonly object NULL = new object(); private sealed class IdentityWeakReference : WeakReference { internal readonly int Hash; internal IdentityWeakReference(object obj/*, ReferenceQueue<object> queue*/) : base(obj == null ? NULL : obj/*, queue*/) { Hash = RuntimeHelpers.GetHashCode(obj); } public override int GetHashCode() { return Hash; } public override bool Equals(object o) { if (this == o) { return true; } if (o is IdentityWeakReference) { IdentityWeakReference @ref = (IdentityWeakReference)o; if (this.Target == @ref.Target) { return true; } } return false; } } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Administration { internal static class AdministrationStrings { internal const string AcknowledgementInterval = "AcknowledgementInterval"; internal const string Action = "Action"; internal const string Address = "Address"; internal const string AddressFilterMode = "AddressFilterMode"; internal const string AddressHeaders = "AddressHeaders"; internal const string AllowAnonymous = "AllowAnonymous"; internal const string AllowCookies = "AllowCookies"; internal const string AllowedImpersonationLevel = "AllowedImpersonationLevel"; internal const string AllowInsecureTransport = "AllowInsecureTransport"; internal const string AllowNtlm = "AllowNtlm"; internal const string AppDomainId = "AppDomainId"; internal const string AppDomainInfo = "AppDomainInfo"; internal const string AsyncPattern = "AsyncPattern"; internal const string AuditLogLocation = "AuditLogLocation"; internal const string AuthenticationMode = "AuthenticationMode"; internal const string AuthenticationScheme = "AuthenticationScheme"; internal const string AutoDisposeParameters = "AutoDisposeParameters"; internal const string AutomaticSessionShutdown = "AutomaticSessionShutdown"; internal const string BaseAddresses = "BaseAddresses"; internal const string Behaviors = "Behaviors"; internal const string Binding = "Binding"; internal const string BindingElements = "BindingElements"; internal const string BypassProxyOnLocal = "BypassProxyOnLocal"; internal const string CacheIssuedTokens = "CacheIssuedTokens"; internal const string CallbackContract = "CallbackContract"; internal const string Channel = "Channel"; internal const string ChannelInitializationTimeout = "ChannelInitializationTimeout"; internal const string ChannelPoolSettings = "ChannelPoolSettings"; internal const string Channels = "OutgoingChannels"; internal const string ClientBaseAddress = "ClientBaseAddress"; internal const string ClientCertificate = "ClientCertificate"; internal const string CloseTimeout = "CloseTimeout"; internal const string CompressionFormat = "CompressionFormat"; internal const string ConcurrencyMode = "ConcurrencyMode"; internal const string ConfigurationName = "ConfigurationName"; internal const string ConnectionBufferSize = "ConnectionBufferSize"; internal const string ConnectionPoolSettings = "ConnectionPoolSettings"; internal const string ContextMode = "ContextMode"; internal const string Contract = "Contract"; internal const string ContractName = "ContractName"; internal const string CounterInstanceName = "CounterInstanceName"; internal const string CustomChannelBinding = "CustomChannelBinding"; internal const string CustomDeadLetterQueue = "CustomDeadLetterQueue"; internal const string CustomServiceNames = "CustomServiceNames"; internal const string Custom = "Custom"; internal const string DeadLetterQueue = "DeadLetterQueue"; internal const string DecompressionEnabled = "DecompressionEnabled"; internal const string DefaultAlgorithmSuite = "DefaultAlgorithmSuite"; internal const string Description = "Description"; internal const string DetectReplays = "DetectReplays"; internal const string DistinguishedName = "DistinguishedName"; internal const string Durable = "Durable"; internal const string GenerateRequestSignatureConfirmation = "GenerateRequestSignatureConfirmation"; internal const string EnableKeyDerivation = "EnableKeyDerivation"; internal const string EnableUnsecuredResponse = "EnableUnsecuredResponse"; internal const string Endpoint = "Endpoint"; internal const string EndpointRefs = "EndpointRefs"; internal const string Endpoints = "Endpoints"; internal const string Encoding = "Encoding"; internal const string EnsureOrderedDispatch = "EnsureOrderedDispatch"; internal const string ExactlyOnce = "ExactlyOnce"; internal const string ExtendedProtectionPolicy = "ExtendedProtectionPolicy"; internal const string Extensions = "Extensions"; internal const string ExternalMetadataLocation = "ExternalMetadataLocation"; internal const string FlowControlEnabled = "FlowControlEnabled"; internal const string FullName = "FullName"; internal const string GetOperationCounterInstanceName = "GetOperationCounterInstanceName"; internal const string GetSupportedAttributes = "GetSupportedAttributes"; internal const string GroupName = "GroupName"; internal const string HostNameComparisonMode = "HostNameComparisonMode"; internal const string HttpDigest = "HttpDigest"; internal const string HttpGetEnabled = "HttpGetEnabled"; internal const string HttpGetUrl = "HttpGetUrl"; internal const string HttpHelpPageUrl = "HttpHelpPageUrl"; internal const string HttpHelpPageEnabled = "HttpHelpPageEnabled"; internal const string HttpsGetEnabled = "HttpsGetEnabled"; internal const string HttpsGetUrl = "HttpsGetUrl"; internal const string HttpsHelpPageUrl = "HttpsHelpPageUrl"; internal const string HttpsHelpPageEnabled = "HttpsHelpPageEnabled"; internal const string Identity = "AddressIdentity"; internal const string IdleTimeout = "IdleTimeout"; internal const string IgnoreExtensionDataObject = "IgnoreExtensionDataObject"; internal const string ImpersonateCallerForAllOperations = "ImpersonateCallerForAllOperations"; internal const string ImpersonateOnSerializingReply = "ImpersonateOnSerializingReply"; internal const string Impersonation = "Impersonation"; internal const string InactivityTimeout = "InactivityTimeout"; internal const string IncludeTimestamp = "IncludeTimestamp"; internal const string IncludeExceptionDetailInFaults = "IncludeExceptionDetailInFaults"; internal const string SupportFaults = "SupportFaults"; internal const string IndigoAppName = "ServiceModel"; internal const string IndigoNamespace = "root\\ServiceModel"; internal const string InitializeData = "initializeData"; internal const string InstanceContextMode = "InstanceContextMode"; internal const string IsCallback = "IsCallback"; internal const string IsDefault = "IsDefault"; internal const string IsInitiating = "IsInitiating"; internal const string IsOneWay = "IsOneWay"; internal const string IssuedCookieLifetime = "IssuedCookieLifetime"; internal const string IssuedTokenAuthentication = "IssuedTokenAuthentication"; internal const string IssuedToken = "IssuedToken"; internal const string IssuedTokenParameters = "IssuedTokenParameters"; internal const string IssuedTransitionTokenLifetime = "IssuedTransitionTokenLifetime"; internal const string IsTerminating = "IsTerminating"; internal const string KeepAliveEnabled = "KeepAliveEnabled"; internal const string KeyEntropyMode = "KeyEntropyMode"; internal const string LeaseTimeout = "LeaseTimeout"; internal const string ListenBacklog = "ListenBacklog"; internal const string ListenIPAddress = "ListenIPAddress"; internal const string ListenUri = "ListenUri"; internal const string LocalAddress = "LocalAddress"; internal const string Localhost = "localhost"; internal const string LocalServiceSecuritySettings = "LocalServiceSecuritySettings"; internal const string LogMalformedMessages = "LogMalformedMessages"; internal const string LogMessagesAtServiceLevel = "LogMessagesAtServiceLevel"; internal const string LogMessagesAtTransportLevel = "LogMessagesAtTransportLevel"; internal const string ManualAddressing = "ManualAddressing"; internal const string MaxArrayLength = "MaxArrayLength"; internal const string MaxBatchSize = "MaxBatchSize"; internal const string MaxBufferPoolSize = "MaxBufferPoolSize"; internal const string MaxBufferSize = "MaxBufferSize"; internal const string MaxBytesPerRead = "MaxBytesPerRead"; internal const string MaxCachedCookies = "MaxCachedCookies"; internal const string MaxClockSkew = "MaxClockSkew"; internal const string MaxConcurrentCalls = "MaxConcurrentCalls"; internal const string MaxConcurrentInstances = "MaxConcurrentInstances"; internal const string MaxConcurrentSessions = "MaxConcurrentSessions"; internal const string MaxPendingConnections = "MaxPendingConnections"; internal const string MaxDepth = "MaxDepth"; internal const string MaxPendingSessions = "MaxPendingSessions"; internal const string MaxAcceptedChannels = "MaxAcceptedChannels"; internal const string MaxItemsInObjectGraph = "MaxItemsInObjectGraph"; internal const string MaxReceivedMessageSize = "MaxReceivedMessageSize"; internal const string MaxNameTableCharCount = "MaxNameTableCharCount"; internal const string MaxOutboundChannelsPerEndpoint = "MaxOutboundChannelsPerEndpoint"; internal const string MaxOutboundConnectionsPerEndpoint = "MaxOutboundConnectionsPerEndpoint"; internal const string MaxOutputDelay = "MaxOutputDelay"; internal const string MaxPendingAccepts = "MaxPendingAccepts"; internal const string MaxPendingChannels = "MaxPendingChannels"; internal const string MaxReadPoolSize = "MaxReadPoolSize"; internal const string MaxPoolSize = "MaxPoolSize"; internal const string MaxRetryCount = "MaxRetryCount"; internal const string MaxRetryCycles = "MaxRetryCycles"; internal const string MaxSessionSize = "MaxSessionSize"; internal const string MaxStringContentLength = "MaxStringContentLength"; internal const string MaxStatefulNegotiations = "MaxStatefulNegotiations"; internal const string MaxTransferWindowSize = "MaxTransferWindowSize"; internal const string MaxWritePoolSize = "MaxWritePoolSize"; internal const string MessageAuthenticationAuditLevel = "MessageAuthenticationAuditLevel"; internal const string MessageLoggingTraceListeners = "MessageLoggingTraceListeners"; internal const string MessageProtectionOrder = "MessageProtectionOrder"; internal const string MessageSecurityVersion = "MessageSecurityVersion"; internal const string MessageVersion = "MessageVersion"; internal const string Metadata = "Metadata"; internal const string MetadataExporter = "MetadataExporter"; internal const string MetadataExportInfo = "MetadataExportInfo"; internal const string MethodSignature = "MethodSignature"; internal const string MsmqAuthenticationMode = "MsmqAuthenticationMode"; internal const string Name = "Name"; internal const string NamedPipeConnectionPoolSettings = "NamedPipeConnectionPoolSettings"; internal const string Namespace = "Namespace"; internal const string NegotiationTimeout = "NegotiationTimeout"; internal const string Opened = "Opened"; internal const string OpenTimeout = "OpenTimeout"; internal const string Operation = "Operation"; internal const string Operations = "Operations"; internal const string Ordered = "Ordered"; internal const string PacketRoutable = "PacketRoutable"; internal const string ParameterTypes = "ParameterTypes"; internal const string Password = "Password"; internal const string Peer = "Peer"; internal const string PeerSecurityMode = "Mode"; internal const string PeerSecuritySettings = "PeerSecuritySettings"; internal const string PeerTransportCredentialType = "CredentialType"; internal const string PeerTransportSecuritySettings = "PeerTransportSecuritySettings"; internal const string PeerResolver = "Resolver"; internal const string PerformanceCounters = "PerformanceCounters"; internal const string PolicyEnforcement = "PolicyEnforcement"; internal const string PolicyVersion = "PolicyVersion"; internal const string Port = "Port"; internal const string PortSharingEnabled = "PortSharingEnabled"; internal const string PrincipalPermissionMode = "PrincipalPermissionMode"; internal const string PrivacyNoticeVersion = "PrivacyNoticeVersion"; internal const string ProcessId = "ProcessId"; internal const string ProtectionLevel = "ProtectionLevel"; internal const string ProtectionScenario = "ProtectionScenario"; internal const string ProxyAddress = "ProxyAddress"; internal const string ProxyAuthenticationScheme = "ProxyAuthenticationScheme"; internal const string QueuedDeliveryRequirements = "QueuedDeliveryRequirements"; internal const string QueueTransferProtocol = "QueueTransferProtocol"; internal const string ReaderQuotas = "ReaderQuotas"; internal const string Realm = "Realm"; internal const string ReceiveContextEnabled = "ReceiveContextEnabled"; internal const string ReceiveErrorHandling = "ReceiveErrorHandling"; internal const string ReceiveRetryCount = "ReceiveRetryCount"; internal const string ReceiveTimeout = "ReceiveTimeout"; internal const string ReconnectTransportOnFailure = "ReconnectTransportOnFailure"; internal const string ReferralPolicy = "ReferralPolicy"; internal const string ReleaseInstanceMode = "ReleaseInstanceMode"; internal const string ReleaseServiceInstanceOnTransactionComplete = "ReleaseServiceInstanceOnTransactionComplete"; internal const string ReliableMessagingVersion = "ReliableMessagingVersion"; internal const string RemoteAddress = "RemoteAddress"; internal const string RemoteEndpoint = "RemoteEndpoint"; internal const string ReplayCacheSize = "ReplayCacheSize"; internal const string ReplayWindow = "ReplayWindow"; internal const string ReplyAction = "ReplyAction"; internal const string RequireClientCertificate = "RequireClientCertificate"; internal const string RequireOrderedDelivery = "RequireOrderedDelivery"; internal const string RequireSignatureConfirmation = "RequireSignatureConfirmation"; internal const string RequirementsMode = "RequirementsMode"; internal const string ResolverMode = "Mode"; internal const string RetryCycleDelay = "RetryCycleDelay"; internal const string ReturnType = "ReturnType"; internal const string RoleProvider = "RoleProvider"; internal const string Scheme = "Scheme"; internal const string SecureConversationAuthentication = "SecureConversationAuthentication"; internal const string SecurityHeaderLayout = "SecurityHeaderLayout"; internal const string Security = "Security"; internal const string SecurityMode = "SecurityMode"; internal const string SecurityStateEncoder = "SecurityStateEncoder"; internal const string SendTimeout = "SendTimeout"; internal const string SerializationFormat = "SerializationFormat"; internal const string Service = "Service"; internal const string ServiceAdmin = "ServiceAdmin"; internal const string ServiceAppDomain = "ServiceAppDomain"; internal const string ServiceAuthorizationAuditLevel = "ServiceAuthorizationAuditLevel"; internal const string ServiceAuthorizationManager = "ServiceAuthorizationManager"; internal const string ServiceCertificate = "ServiceCertificate"; internal const string ServiceConfigPath = "ServiceConfigPath"; internal const string ServiceModelTraceListeners = "ServiceModelTraceListeners"; internal const string ServiceToEndpointAssociation = "ServiceToEndpointAssociation"; internal const string ServiceType = "ServiceType"; internal const string SessionMode = "SessionMode"; internal const string SessionId = "SessionId"; internal const string SessionKeyRenewalInterval = "SessionKeyRenewalInterval"; internal const string SessionKeyRolloverInterval = "SessionKeyRolloverInterval"; internal const string Style = "Style"; internal const string SupportInteractive = "SupportInteractive"; internal const string SuppressAuditFailure = "SuppressAuditFailure"; internal const string TargetContract = "TargetContract"; internal const string TcpConnectionPoolSettings = "TcpConnectionPoolSettings"; internal const string TeredoEnabled = "TeredoEnabled"; internal const string TimestampValidityDuration = "TimestampValidityDuration"; internal const string TimeToLive = "TimeToLive"; internal const string TraceLevel = "TraceLevel"; internal const string TraceListener = "TraceListener"; internal const string TraceListenerArgument = "TraceListenerArgument"; internal const string TraceListenerArguments = "TraceListenerArguments"; internal const string Transport = "Transport"; internal const string TransactionAutoComplete = "TransactionAutoComplete"; internal const string TransactionAutoCompleteOnSessionClose = "TransactionAutoCompleteOnSessionClose"; internal const string TransactionFlowOption = "TransactionFlowOption"; internal const string TransactionIsolationLevel = "TransactionIsolationLevel"; internal const string TransactionProtocol = "TransactionProtocol"; internal const string TransactionFlow = "TransactionFlow"; internal const string AllowWildcardAction = "AllowWildcardAction"; internal const string TransactionScopeRequired = "TransactionScopeRequired"; internal const string TransactionTimeout = "TransactionTimeout"; internal const string TransferMode = "TransferMode"; internal const string Type = "Type"; internal const string UnsafeConnectionNtlmAuthentication = "UnsafeConnectionNtlmAuthentication"; internal const string Url = "Url"; internal const string Uri = "Uri"; internal const string Use = "Use"; internal const string UseActiveDirectory = "UseActiveDirectory"; internal const string UseDefaultWebProxy = "UseDefaultWebProxy"; internal const string UseMsmqTracing = "UseMsmqTracing"; internal const string UserName = "UserName"; internal const string UserNameAuthentication = "UserNameAuthentication"; internal const string UseSourceJournal = "UseSourceJournal"; internal const string UseSynchronizationContext = "UseSynchronizationContext"; internal const string ValidateMustUnderstand = "ValidateMustUnderstand"; internal const string ValidationMode = "ValidationMode"; internal const string ValidityDuration = "ValidityDuration"; internal const string Value = "Value"; internal const string VirtualPath = "VirtualPath"; internal const string WindowsAuthentication = "WindowsAuthentication"; internal const string Windows = "Windows"; internal const string XmlDictionaryReaderQuotas = "XmlDictionaryReaderQuotas"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing.Imaging { using System.Runtime.InteropServices; /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix"]/*' /> /// <devdoc> /// Defines a 5 x 5 matrix that that /// contains the homogenous coordinates for the RGBA space. /// </devdoc> [StructLayout(LayoutKind.Sequential)] public sealed class ColorMatrix { private float _matrix00; private float _matrix01; private float _matrix02; private float _matrix03; private float _matrix04; private float _matrix10; private float _matrix11; private float _matrix12; private float _matrix13; private float _matrix14; private float _matrix20; private float _matrix21; private float _matrix22; private float _matrix23; private float _matrix24; private float _matrix30; private float _matrix31; private float _matrix32; private float _matrix33; private float _matrix34; private float _matrix40; private float _matrix41; private float _matrix42; private float _matrix43; private float _matrix44; /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.ColorMatrix"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Imaging.ColorMatrix'/> class. /// </para> /// </devdoc> public ColorMatrix() { /* * Setup identity matrix by default */ _matrix00 = 1.0f; //matrix01 = 0.0f; //matrix02 = 0.0f; //matrix03 = 0.0f; //matrix04 = 0.0f; //matrix10 = 0.0f; _matrix11 = 1.0f; //matrix12 = 0.0f; //matrix13 = 0.0f; //matrix14 = 0.0f; //matrix20 = 0.0f; //matrix21 = 0.0f; _matrix22 = 1.0f; // matrix23 = 0.0f; // matrix24 = 0.0f; // matrix30 = 0.0f; //matrix31 = 0.0f; // matrix32 = 0.0f; _matrix33 = 1.0f; // matrix34 = 0.0f; // matrix40 = 0.0f; // matrix41 = 0.0f; // matrix42 = 0.0f; // matrix43 = 0.0f; _matrix44 = 1.0f; } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix00"]/*' /> /// <devdoc> /// <para> /// Represents the element at the /// 0th row and 0th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix00 { get { return _matrix00; } set { _matrix00 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix01"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 0th row and 1st column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix01 { get { return _matrix01; } set { _matrix01 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix02"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 0th row and 2nd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix02 { get { return _matrix02; } set { _matrix02 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix03"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 0th row and 3rd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix03 { get { return _matrix03; } set { _matrix03 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix04"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 0th row and 4th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix04 { get { return _matrix04; } set { _matrix04 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix10"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 1st row and 0th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix10 { get { return _matrix10; } set { _matrix10 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix11"]/*' /> /// <devdoc> /// Represents the element at the 1st row and /// 1st column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </devdoc> public float Matrix11 { get { return _matrix11; } set { _matrix11 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix12"]/*' /> /// <devdoc> /// Represents the element at the 1st row /// and 2nd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </devdoc> public float Matrix12 { get { return _matrix12; } set { _matrix12 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix13"]/*' /> /// <devdoc> /// Represents the element at the 1st row /// and 3rd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </devdoc> public float Matrix13 { get { return _matrix13; } set { _matrix13 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix14"]/*' /> /// <devdoc> /// Represents the element at the 1st row /// and 4th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </devdoc> public float Matrix14 { get { return _matrix14; } set { _matrix14 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix20"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 2nd row and /// 0th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix20 { get { return _matrix20; } set { _matrix20 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix21"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 2nd row and 1st column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix21 { get { return _matrix21; } set { _matrix21 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix22"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 2nd row and 2nd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix22 { get { return _matrix22; } set { _matrix22 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix23"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 2nd row and 3rd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix23 { get { return _matrix23; } set { _matrix23 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix24"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 2nd row and 4th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix24 { get { return _matrix24; } set { _matrix24 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix30"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 3rd row and 0th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix30 { get { return _matrix30; } set { _matrix30 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix31"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 3rd row and 1st column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix31 { get { return _matrix31; } set { _matrix31 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix32"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 3rd row and 2nd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix32 { get { return _matrix32; } set { _matrix32 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix33"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 3rd row and 3rd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix33 { get { return _matrix33; } set { _matrix33 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix34"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 3rd row and 4th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix34 { get { return _matrix34; } set { _matrix34 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix40"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 4th row and 0th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix40 { get { return _matrix40; } set { _matrix40 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix41"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 4th row and 1st column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix41 { get { return _matrix41; } set { _matrix41 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix42"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 4th row and 2nd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix42 { get { return _matrix42; } set { _matrix42 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix43"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 4th row and 3rd column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix43 { get { return _matrix43; } set { _matrix43 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.Matrix44"]/*' /> /// <devdoc> /// <para> /// Represents the element at the 4th row and 4th column of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float Matrix44 { get { return _matrix44; } set { _matrix44 = value; } } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.ColorMatrix1"]/*' /> /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Imaging.ColorMatrix'/> class with the /// elements in the specified matrix. /// </para> /// </devdoc> [CLSCompliant(false)] public ColorMatrix(float[][] newColorMatrix) { SetMatrix(newColorMatrix); } internal void SetMatrix(float[][] newColorMatrix) { _matrix00 = newColorMatrix[0][0]; _matrix01 = newColorMatrix[0][1]; _matrix02 = newColorMatrix[0][2]; _matrix03 = newColorMatrix[0][3]; _matrix04 = newColorMatrix[0][4]; _matrix10 = newColorMatrix[1][0]; _matrix11 = newColorMatrix[1][1]; _matrix12 = newColorMatrix[1][2]; _matrix13 = newColorMatrix[1][3]; _matrix14 = newColorMatrix[1][4]; _matrix20 = newColorMatrix[2][0]; _matrix21 = newColorMatrix[2][1]; _matrix22 = newColorMatrix[2][2]; _matrix23 = newColorMatrix[2][3]; _matrix24 = newColorMatrix[2][4]; _matrix30 = newColorMatrix[3][0]; _matrix31 = newColorMatrix[3][1]; _matrix32 = newColorMatrix[3][2]; _matrix33 = newColorMatrix[3][3]; _matrix34 = newColorMatrix[3][4]; _matrix40 = newColorMatrix[4][0]; _matrix41 = newColorMatrix[4][1]; _matrix42 = newColorMatrix[4][2]; _matrix43 = newColorMatrix[4][3]; _matrix44 = newColorMatrix[4][4]; } internal float[][] GetMatrix() { float[][] returnMatrix = new float[5][]; for (int i = 0; i < 5; i++) returnMatrix[i] = new float[5]; returnMatrix[0][0] = _matrix00; returnMatrix[0][1] = _matrix01; returnMatrix[0][2] = _matrix02; returnMatrix[0][3] = _matrix03; returnMatrix[0][4] = _matrix04; returnMatrix[1][0] = _matrix10; returnMatrix[1][1] = _matrix11; returnMatrix[1][2] = _matrix12; returnMatrix[1][3] = _matrix13; returnMatrix[1][4] = _matrix14; returnMatrix[2][0] = _matrix20; returnMatrix[2][1] = _matrix21; returnMatrix[2][2] = _matrix22; returnMatrix[2][3] = _matrix23; returnMatrix[2][4] = _matrix24; returnMatrix[3][0] = _matrix30; returnMatrix[3][1] = _matrix31; returnMatrix[3][2] = _matrix32; returnMatrix[3][3] = _matrix33; returnMatrix[3][4] = _matrix34; returnMatrix[4][0] = _matrix40; returnMatrix[4][1] = _matrix41; returnMatrix[4][2] = _matrix42; returnMatrix[4][3] = _matrix43; returnMatrix[4][4] = _matrix44; return returnMatrix; } /// <include file='doc\ColorMatrix.uex' path='docs/doc[@for="ColorMatrix.this"]/*' /> /// <devdoc> /// <para> /// Gets or sets the value of the specified element of this <see cref='System.Drawing.Imaging.ColorMatrix'/>. /// </para> /// </devdoc> public float this[int row, int column] { get { return GetMatrix()[row][column]; } set { float[][] tempMatrix = GetMatrix(); tempMatrix[row][column] = value; SetMatrix(tempMatrix); } } } }
using DirtyMagic.Breakpoints; using DirtyMagic.Processes; using DirtyMagic.WinAPI; using DirtyMagic.WinAPI.Structures; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using DirtyMagic.Exceptions; namespace DirtyMagic { public class ProcessDebugger : MemoryHandler { private Thread _debugThread = null; public bool IsDebugging { get; private set; } public bool IsDetached { get; private set; } public bool HasExited => !Process.IsValid; public List<HardwareBreakPoint> Breakpoints { get; private set; } = new List<HardwareBreakPoint>(); public ProcessDebugger(int processId) : base(processId) { } public ProcessDebugger(RemoteProcess process) : base(process) { } private void Attach() { var res = false; if (!Kernel32.CheckRemoteDebuggerPresent(Process.Handle, ref res)) throw new DebuggerException("Failed to check if remote process is already being debugged"); if (res) throw new DebuggerException("Process is already being debugged by another debugger"); if (!Kernel32.DebugActiveProcess(Process.Id)) throw new DebuggerException("Failed to start debugging"); if (!Kernel32.DebugSetProcessKillOnExit(false)) throw new DebuggerException("Failed to set kill on exit"); ClearUsedBreakpointSlots(); IsDebugging = true; } public void ClearUsedBreakpointSlots() { RefreshMemory(); foreach (var th in Process.Threads) { var hThread = Kernel32.OpenThread(ThreadAccess.THREAD_ALL_ACCESS, false, th.Id); if (hThread == IntPtr.Zero) throw new BreakPointException("Can't open thread for access"); HardwareBreakPoint.UnsetSlotsFromThread(hThread, SlotFlags.All); if (!Kernel32.CloseHandle(hThread)) throw new BreakPointException("Failed to close thread handle"); } } public void AddBreakPoint(HardwareBreakPoint breakpoint) { if (Breakpoints.Count >= Kernel32.MaxHardwareBreakpointsCount) throw new DebuggerException("Can't set any more breakpoints"); try { using (var suspender = MakeSuspender()) { breakpoint.Set(this); Breakpoints.Add(breakpoint); } } catch (BreakPointException e) { throw new DebuggerException(e.Message); } } public void RemoveBreakPoints() { try { using (var suspender = MakeSuspender()) { foreach (var bp in Breakpoints) bp.UnSet(this); } Breakpoints.Clear(); } catch (BreakPointException e) { throw new DebuggerException(e.Message); } } public void StopDebugging() => IsDebugging = false; public void Join() { _debugThread?.Join(); } protected void Detach() { if (IsDetached) return; IsDetached = true; RefreshMemory(); if (HasExited) return; RemoveBreakPoints(); if (!Kernel32.DebugActiveProcessStop(Process.Id)) throw new DebuggerException("Failed to stop process debugging"); } private void StartListener(uint waitInterval = 200) { var debugEvent = new DEBUG_EVENT(); for (; IsDebugging;) { if (!Kernel32.WaitForDebugEvent(ref debugEvent, waitInterval)) { if (!IsDebugging) break; continue; } //Console.WriteLine("Debug Event Code: {0} ", DebugEvent.dwDebugEventCode); var okEvent = false; switch (debugEvent.dwDebugEventCode) { case DebugEventType.RIP_EVENT: case DebugEventType.EXIT_PROCESS_DEBUG_EVENT: { //Console.WriteLine("Process has exited"); IsDebugging = false; IsDetached = true; if (!Kernel32.ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, okEvent ? (uint) DebugContinueStatus.DBG_CONTINUE : (uint) DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) throw new DebuggerException("Failed to continue debug event"); if (!Kernel32.DebugActiveProcessStop(Process.Id)) throw new DebuggerException("Failed to stop process debugging"); return; } case DebugEventType.EXCEPTION_DEBUG_EVENT: { //Console.WriteLine("Exception Code: {0:X}", DebugEvent.Exception.ExceptionRecord.ExceptionCode); if (debugEvent.Exception.ExceptionRecord.ExceptionCode == (uint) ExceptonStatus.STATUS_SINGLE_STEP) { okEvent = true; /*if (DebugEvent.dwThreadId != threadId) { Console.WriteLine("Debug event thread id does not match breakpoint thread"); break; }*/ var hThread = Kernel32.OpenThread(ThreadAccess.THREAD_ALL_ACCESS, false, debugEvent.dwThreadId); if (hThread == IntPtr.Zero) throw new DebuggerException("Failed to open thread"); var Context = new CONTEXT(); Context.ContextFlags = CONTEXT_FLAGS.CONTEXT_FULL; if (!Kernel32.GetThreadContext(hThread, Context)) throw new DebuggerException("Failed to get thread context"); if (!Breakpoints.Any(e => e != null && e.IsSet && e.Address.ToUInt32() == Context.Eip)) break; var bp = Breakpoints.First(e => e != null && e.IsSet && e.Address.ToUInt32() == Context.Eip); var ContextWrapper = new ContextWrapper(this, Context); if (bp.HandleException(ContextWrapper)) { if (!Kernel32.SetThreadContext(hThread, ContextWrapper.Context)) throw new DebuggerException("Failed to set thread context"); } } break; } case DebugEventType.CREATE_THREAD_DEBUG_EVENT: { foreach (var bp in Breakpoints) bp.SetToThread(debugEvent.CreateThread.hThread, debugEvent.dwThreadId); break; } case DebugEventType.EXIT_THREAD_DEBUG_EVENT: { foreach (var bp in Breakpoints) bp.UnregisterThread(debugEvent.dwThreadId); break; } } if (!IsDebugging) { IsDetached = true; RemoveBreakPoints(); if (!Kernel32.ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, okEvent ? (uint)DebugContinueStatus.DBG_CONTINUE : (uint)DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) throw new DebuggerException("Failed to continue debug event"); if (!Kernel32.DebugActiveProcessStop(Process.Id)) throw new DebuggerException("Failed to stop process debugging"); return; } if (!Kernel32.ContinueDebugEvent(debugEvent.dwProcessId, debugEvent.dwThreadId, okEvent ? (uint)DebugContinueStatus.DBG_CONTINUE : (uint)DebugContinueStatus.DBG_EXCEPTION_NOT_HANDLED)) throw new DebuggerException("Failed to continue debug event"); } Detach(); } public void Run() { _debugThread = new Thread(() => { try { Attach(); StartListener(); } catch (DebuggerException e) { Console.WriteLine("Debugger exception occured: {0}", e.Message); } catch (Exception e) { Console.WriteLine("Exception occured: {0}", e.Message); } try { Detach(); } catch (DebuggerException e) { Console.WriteLine("Debugger exception occured: {0}", e.Message); } catch (Exception e) { Console.WriteLine("Exception occured: {0}", e.Message); } }); _debugThread.Start(); } public bool WaitForComeUp(int waitTime) { if (IsDebugging) return true; Thread.Sleep(waitTime); return IsDebugging; } public bool WaitForComeUp(int waitTime, int repeatCount) { for (int i = 0; i < repeatCount; ++i) { if (WaitForComeUp(waitTime)) return true; } return IsDebugging; } private bool _catchSigInt; public bool CatchSigInt { get => _catchSigInt; set { _catchSigInt = value; if (_catchSigInt) SigIntHandler.AddInstance(this); else SigIntHandler.RemoveInstance(this); } } } public static class SigIntHandler { private static readonly List<ProcessDebugger> AffectedInstances = new List<ProcessDebugger>(); static SigIntHandler() { Console.CancelKeyPress += (sender, e) => { if (AffectedInstances.Count > 0) { e.Cancel = true; foreach (var Debugger in AffectedInstances) Debugger.StopDebugging(); } }; } public static void AddInstance(ProcessDebugger debugger) => AffectedInstances.Add(debugger); public static void RemoveInstance(ProcessDebugger debugger) => AffectedInstances.Remove(debugger); } }
// 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.Collections.ObjectModel; using System.ComponentModel.Composition.Primitives; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { public abstract partial class ExportProvider { /// <summary> /// Returns the export with the contract name derived from the specified type parameter, /// throwing an exception if there is not exactly one matching export. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T}"/> object to return. The contract name is also /// derived from this type parameter. /// </typeparam> /// <returns> /// The <see cref="Lazy{T}"/> object with the contract name derived from /// <typeparamref name="T"/>. /// </returns> /// <remarks> /// <para> /// The returned <see cref="Lazy{T}"/> object is an instance of /// <see cref="Lazy{T, TMetadataView}"/> underneath, where /// <c>TMetadataView</c> /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c> /// is <see cref="string"/> and <c>TValue</c> is <see cref="object"/>. /// </para> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero <see cref="Lazy{T}"/> objects with the contract name derived /// from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one <see cref="Lazy{T}"/> objects with the contract name /// derived from <typeparamref name="T"/> in the <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> public Lazy<T> GetExport<T>() { return GetExport<T>((string)null); } /// <summary> /// Returns the export with the specified contract name, throwing an exception if there /// is not exactly one matching export. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T}"/> object to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the <see cref="Lazy{T}"/> /// object to return; or <see langword="null"/> or an empty string ("") to use the /// default contract name. /// </param> /// <returns> /// The <see cref="Lazy{T}"/> object with the specified contract name. /// </returns> /// <remarks> /// <para> /// The returned <see cref="Lazy{T}"/> object is an instance of /// <see cref="Lazy{T, TMetadataView}"/> underneath, where /// <c>TMetadataView</c> /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c> /// is <see cref="string"/> and <c>TValue</c> is <see cref="object"/>. /// </para> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The default contract name is compared using a case-sensitive, non-linguistic /// comparison using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero <see cref="Lazy{T}"/> objects with the specified contract name /// in the <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one <see cref="Lazy{T}"/> objects with the specified contract /// name in the <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> public Lazy<T> GetExport<T>(string contractName) { return GetExportCore<T>(contractName); } /// <summary> /// Returns the export with the contract name derived from the specified type parameter, /// throwing an exception if there is not exactly one matching export. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return. The /// contract name is also derived from this type parameter. /// </typeparam> /// <typeparam name="TMetadataView"> /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object /// to return. /// </typeparam> /// <returns> /// The <see cref="Lazy{T, TMetadataView}"/> object with the contract name derived /// from <typeparamref name="T"/>. /// </returns> /// <remarks> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the contract /// name derived from <typeparamref name="T"/> in the /// <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the /// contract name derived from <typeparamref name="T"/> in the /// <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="InvalidOperationException"> /// <typeparamref name="TMetadataView"/> is not a valid metadata view type. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> public Lazy<T, TMetadataView> GetExport<T, TMetadataView>() { return GetExport<T, TMetadataView>((string)null); } /// <summary> /// Returns the export with the specified contract name, throwing an exception if there /// is not exactly one matching export. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T, TMetadataView}"/> object to return. /// </typeparam> /// <typeparam name="TMetadataView"> /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> object /// to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the /// <see cref="Lazy{T, TMetadataView}"/> object to return; or <see langword="null"/> /// or an empty string ("") to use the default contract name. /// </param> /// <returns> /// The <see cref="Lazy{T, TMetadataView}"/> object with the specified contract name. /// </returns> /// <remarks> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero <see cref="Lazy{T, TMetadataView}"/> objects with the /// specified contract name in the <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one <see cref="Lazy{T, TMetadataView}"/> objects with the /// specified contract name in the <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="InvalidOperationException"> /// <typeparamref name="TMetadataView"/> is not a valid metadata view type. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> public Lazy<T, TMetadataView> GetExport<T, TMetadataView>(string contractName) { return GetExportCore<T, TMetadataView>(contractName); } /// <summary> /// Returns the exports with the specified contract name. /// </summary> /// <param name="type"> /// The <see cref="Type"/> of the <see cref="Export"/> objects to return. /// </param> /// <param name="metadataViewType"> /// The <see cref="Type"/> of the metadata view of the <see cref="Export"/> objects to /// return. /// </param> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the /// <see cref="Export"/> object to return; or <see langword="null"/> /// or an empty string ("") to use the default contract name. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{Object, Object}"/> objects /// with the specified contract name, if found; otherwise, an empty /// <see cref="IEnumerable{T}"/>. /// </returns> /// <remarks> /// <para> /// The returned <see cref="Export"/> objects are instances of /// <see cref="Lazy{T, TMetadataView}"/> underneath, where <c>T</c> /// is <paramref name="type"/> and <c>TMetadataView</c> is /// <paramref name="metadataViewType"/>. /// </para> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <paramref name="type"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="type"/> is <see langword="null"/>. /// </exception> /// <exception cref="InvalidOperationException"> /// <paramref name="metadataViewType"/> is not a valid metadata view type. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable<Lazy<object, object>> GetExports(Type type, Type metadataViewType, string contractName) { IEnumerable<Export> exports = GetExportsCore(type, metadataViewType, contractName, ImportCardinality.ZeroOrMore); Collection<Lazy<object, object>> result = new Collection<Lazy<object, object>>(); Func<Export, Lazy<object, object>> typedExportFactory = ExportServices.CreateSemiStronglyTypedLazyFactory(type, metadataViewType); foreach (Export export in exports) { result.Add(typedExportFactory.Invoke(export)); } return result; } /// <summary> /// Returns the exports with the contract name derived from the specified type parameter. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T}"/> objects to return. The contract name is also /// derived from this type parameter. /// </typeparam> /// <returns> /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects /// with the contract name derived from <typeparamref name="T"/>, if found; otherwise, /// an empty <see cref="IEnumerable{T}"/>. /// </returns> /// <remarks> /// <para> /// The returned <see cref="Lazy{T}"/> objects are instances of /// <see cref="Lazy{T, TMetadataView}"/> underneath, where /// <c>TMetadataView</c> /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c> /// is <see cref="string"/> and <c>TValue</c> is <see cref="object"/>. /// </para> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable<Lazy<T>> GetExports<T>() { return GetExports<T>((string)null); } /// <summary> /// Returns the exports with the specified contract name. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T}"/> objects to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the <see cref="Lazy{T}"/> /// objects to return; or <see langword="null"/> or an empty string ("") to use the /// default contract name. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> containing the <see cref="Lazy{T}"/> objects /// with the specified contract name, if found; otherwise, an empty /// <see cref="IEnumerable{T}"/>. /// </returns> /// <remarks> /// <para> /// The returned <see cref="Lazy{T}"/> objects are instances of /// <see cref="Lazy{T, TMetadataView}"/> underneath, where /// <c>TMetadataView</c> /// is <see cref="IDictionary{TKey, TValue}"/> and where <c>TKey</c> /// is <see cref="string"/> and <c>TValue</c> is <see cref="object"/>. /// </para> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable<Lazy<T>> GetExports<T>(string contractName) { return GetExportsCore<T>(contractName); } /// <summary> /// Returns the exports with the contract name derived from the specified type parameter. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The /// contract name is also derived from this type parameter. /// </typeparam> /// <typeparam name="TMetadataView"> /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects /// to return. /// </typeparam> /// <returns> /// An <see cref="IEnumerable{T}"/> containing the /// <see cref="Lazy{T, TMetadataView}"/> objects with the contract name derived from /// <typeparamref name="T"/>, if found; otherwise, an empty /// <see cref="IEnumerable{T}"/>. /// </returns> /// <remarks> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// <typeparamref name="TMetadataView"/> is not a valid metadata view type. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>() { return GetExports<T, TMetadataView>((string)null); } /// <summary> /// Returns the exports with the specified contract name. /// </summary> /// <typeparam name="T"> /// The type of the <see cref="Lazy{T, TMetadataView}"/> objects to return. The /// contract name is also derived from this type parameter. /// </typeparam> /// <typeparam name="TMetadataView"> /// The type of the metadata view of the <see cref="Lazy{T, TMetadataView}"/> objects /// to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the /// <see cref="Lazy{T, TMetadataView}"/> objects to return; or <see langword="null"/> /// or an empty string ("") to use the default contract name. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> containing the /// <see cref="Lazy{T, TMetadataView}"/> objects with the specified contract name if /// found; otherwise, an empty <see cref="IEnumerable{T}"/>. /// </returns> /// <remarks> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="InvalidOperationException"> /// <typeparamref name="TMetadataView"/> is not a valid metadata view type. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006")] public IEnumerable<Lazy<T, TMetadataView>> GetExports<T, TMetadataView>(string contractName) { return GetExportsCore<T, TMetadataView>(contractName); } /// <summary> /// Returns the exported value with the contract name derived from the specified type /// parameter, throwing an exception if there is not exactly one matching exported value. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. The contract name is also /// derived from this type parameter. /// </typeparam> /// <returns> /// The exported <see cref="object"/> with the contract name derived from /// <typeparamref name="T"/>. /// </returns> /// <remarks> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// The underlying exported value cannot be cast to <typeparamref name="T"/>. /// </exception> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero exported values with the contract name derived from /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one exported values with the contract name derived from /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public T GetExportedValue<T>() { return GetExportedValue<T>((string)null); } /// <summary> /// Returns the exported value with the specified contract name, throwing an exception /// if there is not exactly one matching exported value. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the exported value to return, /// or <see langword="null"/> or an empty string ("") to use the default contract name. /// </param> /// <returns> /// The exported <see cref="object"/> with the specified contract name. /// </returns> /// <remarks> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// The underlying exported value cannot be cast to <typeparamref name="T"/>. /// </exception> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are zero exported values with the specified contract name in the /// <see cref="CompositionContainer"/>. /// </para> /// -or- /// <para> /// There are more than one exported values with the specified contract name in the /// <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public T GetExportedValue<T>(string contractName) { return GetExportedValueCore<T>(contractName, ImportCardinality.ExactlyOne); } /// <summary> /// Returns the exported value with the contract name derived from the specified type /// parameter, throwing an exception if there is more than one matching exported value. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. The contract name is also /// derived from this type parameter. /// </typeparam> /// <returns> /// The exported <see cref="object"/> with the contract name derived from /// <typeparamref name="T"/>, if found; otherwise, the default value for /// <typeparamref name="T"/>. /// </returns> /// <remarks> /// <para> /// If the exported value is not found, then this method returns the appropriate /// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer /// types, <see langword="false"/> for Boolean types, and <see langword="null"/> /// for reference types. /// </para> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// The underlying exported value cannot be cast to <typeparamref name="T"/>. /// </exception> /// <exception cref="ImportCardinalityMismatchException"> /// <para> /// There are more than one exported values with the contract name derived from /// <typeparamref name="T"/> in the <see cref="CompositionContainer"/>. /// </para> /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public T GetExportedValueOrDefault<T>() { return GetExportedValueOrDefault<T>((string)null); } /// <summary> /// Returns the exported value with the specified contract name, throwing an exception /// if there is more than one matching exported value. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the exported value to return, /// or <see langword="null"/> or an empty string ("") to use the default contract name. /// </param> /// <returns> /// The exported <see cref="object"/> with the specified contract name, if found; /// otherwise, the default value for <typeparamref name="T"/>. /// </returns> /// <remarks> /// <para> /// If the exported value is not found, then this method returns the appropriate /// default value for <typeparamref name="T"/>; for example, 0 (zero) for integer /// types, <see langword="false"/> for Boolean types, and <see langword="null"/> /// for reference types. /// </para> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// The underlying exported value cannot be cast to <typeparamref name="T"/>. /// </exception> /// <exception cref="ImportCardinalityMismatchException"> /// There are more than one exported values with the specified contract name in the /// <see cref="CompositionContainer"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public T GetExportedValueOrDefault<T>(string contractName) { return GetExportedValueCore<T>(contractName, ImportCardinality.ZeroOrOne); } /// <summary> /// Returns the exported values with the contract name derived from the specified type /// parameter. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. The contract name is also /// derived from this type parameter. /// </typeparam> /// <returns> /// An <see cref="Collection{T}"/> containing the exported values with the contract name /// derived from the specified type parameter, if found; otherwise, an empty /// <see cref="Collection{T}"/>. /// </returns> /// <remarks> /// <para> /// The contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// One or more of the underlying exported values cannot be cast to /// <typeparamref name="T"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public IEnumerable<T> GetExportedValues<T>() { return GetExportedValues<T>((string)null); } /// <summary> /// Returns the exported values with the specified contract name. /// </summary> /// <typeparam name="T"> /// The type of the exported value to return. /// </typeparam> /// <param name="contractName"> /// A <see cref="string"/> containing the contract name of the exported values to /// return; or <see langword="null"/> or an empty string ("") to use the default /// contract name. /// </param> /// <returns> /// An <see cref="Collection{T}"/> containing the exported values with the specified /// contract name, if found; otherwise, an empty <see cref="Collection{T}"/>. /// </returns> /// <remarks> /// <para> /// The default contract name is the result of calling /// <see cref="AttributedModelServices.GetContractName(Type)"/> on <typeparamref name="T"/>. /// </para> /// <para> /// The contract name is compared using a case-sensitive, non-linguistic comparison /// using <see cref="StringComparer.Ordinal"/>. /// </para> /// </remarks> /// <exception cref="CompositionContractMismatchException"> /// One or more of the underlying exported values cannot be cast to /// <typeparamref name="T"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="CompositionContainer"/> has been disposed of. /// </exception> /// <exception cref="CompositionException"> /// An error occurred during composition. <see cref="CompositionException.Errors"/> will /// contain a collection of errors that occurred. /// </exception> public IEnumerable<T> GetExportedValues<T>(string contractName) { return GetExportedValuesCore<T>(contractName); } private IEnumerable<T> GetExportedValuesCore<T>(string contractName) { IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore); Collection<T> result = new Collection<T>(); foreach (Export export in exports) { result.Add(ExportServices.GetCastedExportedValue<T>(export)); } return result; } private T GetExportedValueCore<T>(string contractName, ImportCardinality cardinality) { if (!cardinality.IsAtMostOne()) { throw new Exception(SR.Diagnostic_InternalExceptionMessage); } Export export = GetExportsCore(typeof(T), (Type)null, contractName, cardinality).SingleOrDefault(); return (export != null) ? ExportServices.GetCastedExportedValue<T>(export) : default(T); } private IEnumerable<Lazy<T>> GetExportsCore<T>(string contractName) { IEnumerable<Export> exports = GetExportsCore(typeof(T), (Type)null, contractName, ImportCardinality.ZeroOrMore); Collection<Lazy<T>> result = new Collection<Lazy<T>>(); foreach (Export export in exports) { result.Add(ExportServices.CreateStronglyTypedLazyOfT<T>(export)); } return result; } private IEnumerable<Lazy<T, TMetadataView>> GetExportsCore<T, TMetadataView>(string contractName) { IEnumerable<Export> exports = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ZeroOrMore); Collection<Lazy<T, TMetadataView>> result = new Collection<Lazy<T, TMetadataView>>(); foreach (Export export in exports) { result.Add(ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export)); } return result; } private Lazy<T, TMetadataView> GetExportCore<T, TMetadataView>(string contractName) { Export export = GetExportsCore(typeof(T), typeof(TMetadataView), contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); return (export != null) ? ExportServices.CreateStronglyTypedLazyOfTM<T, TMetadataView>(export) : null; } private Lazy<T> GetExportCore<T>(string contractName) { Export export = GetExportsCore(typeof(T), null, contractName, ImportCardinality.ExactlyOne).SingleOrDefault(); return (export != null) ? ExportServices.CreateStronglyTypedLazyOfT<T>(export) : null; } private IEnumerable<Export> GetExportsCore(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality) { // Only 'type' cannot be null - the other parameters have sensible defaults. Requires.NotNull(type, nameof(type)); if (string.IsNullOrEmpty(contractName)) { contractName = AttributedModelServices.GetContractName(type); } if (metadataViewType == null) { metadataViewType = ExportServices.DefaultMetadataViewType; } if (!MetadataViewProvider.IsViewTypeValid(metadataViewType)) { throw new InvalidOperationException(SR.Format(SR.InvalidMetadataView, metadataViewType.Name)); } ImportDefinition importDefinition = BuildImportDefinition(type, metadataViewType, contractName, cardinality); return GetExports(importDefinition, null); } private static ImportDefinition BuildImportDefinition(Type type, Type metadataViewType, string contractName, ImportCardinality cardinality) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (metadataViewType == null) { throw new ArgumentNullException(nameof(metadataViewType)); } if (contractName == null) { throw new ArgumentNullException(nameof(contractName)); } IEnumerable<KeyValuePair<string, Type>> requiredMetadata = CompositionServices.GetRequiredMetadata(metadataViewType); IDictionary<string, object> metadata = CompositionServices.GetImportMetadata(type, null); string requiredTypeIdentity = null; if (type != typeof(object)) { requiredTypeIdentity = AttributedModelServices.GetTypeIdentity(type); } return new ContractBasedImportDefinition(contractName, requiredTypeIdentity, requiredMetadata, cardinality, false, true, CreationPolicy.Any, metadata); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace LinqToDB.Common.Internal.Cache { internal class CacheEntry : ICacheEntry { private bool _added = false; private static readonly Action<object> ExpirationCallback = ExpirationTokensExpired; private readonly Action<CacheEntry> _notifyCacheOfExpiration; private readonly Action<CacheEntry> _notifyCacheEntryDisposed; private IList<IDisposable>? _expirationTokenRegistrations; private IList<PostEvictionCallbackRegistration>? _postEvictionCallbacks; private bool _isExpired; internal IList<IChangeToken>? _expirationTokens; internal DateTimeOffset? _absoluteExpiration; internal TimeSpan? _absoluteExpirationRelativeToNow; private TimeSpan? _slidingExpiration; private long? _size; private IDisposable _scope; internal readonly object _lock = new object(); internal CacheEntry( object key, Action<CacheEntry> notifyCacheEntryDisposed, Action<CacheEntry> notifyCacheOfExpiration) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (notifyCacheEntryDisposed == null) { throw new ArgumentNullException(nameof(notifyCacheEntryDisposed)); } if (notifyCacheOfExpiration == null) { throw new ArgumentNullException(nameof(notifyCacheOfExpiration)); } Key = key; _notifyCacheEntryDisposed = notifyCacheEntryDisposed; _notifyCacheOfExpiration = notifyCacheOfExpiration; _scope = CacheEntryHelper.EnterScope(this); } /// <summary> /// Gets or sets an absolute expiration date for the cache entry. /// </summary> public DateTimeOffset? AbsoluteExpiration { get { return _absoluteExpiration; } set { _absoluteExpiration = value; } } /// <summary> /// Gets or sets an absolute expiration time, relative to now. /// </summary> public TimeSpan? AbsoluteExpirationRelativeToNow { get { return _absoluteExpirationRelativeToNow; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException( nameof(AbsoluteExpirationRelativeToNow), value, "The relative expiration value must be positive."); } _absoluteExpirationRelativeToNow = value; } } /// <summary> /// Gets or sets how long a cache entry can be inactive (e.g. not accessed) before it will be removed. /// This will not extend the entry lifetime beyond the absolute expiration (if set). /// </summary> public TimeSpan? SlidingExpiration { get { return _slidingExpiration; } set { if (value <= TimeSpan.Zero) { throw new ArgumentOutOfRangeException( nameof(SlidingExpiration), value, "The sliding expiration value must be positive."); } _slidingExpiration = value; } } /// <summary> /// Gets the <see cref="IChangeToken"/> instances which cause the cache entry to expire. /// </summary> public IList<IChangeToken> ExpirationTokens { get { if (_expirationTokens == null) { _expirationTokens = new List<IChangeToken>(); } return _expirationTokens; } } /// <summary> /// Gets or sets the callbacks will be fired after the cache entry is evicted from the cache. /// </summary> public IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get { if (_postEvictionCallbacks == null) { _postEvictionCallbacks = new List<PostEvictionCallbackRegistration>(); } return _postEvictionCallbacks; } } /// <summary> /// Gets or sets the priority for keeping the cache entry in the cache during a /// memory pressure triggered cleanup. The default is <see cref="CacheItemPriority.Normal"/>. /// </summary> public CacheItemPriority Priority { get; set; } = CacheItemPriority.Normal; /// <summary> /// Gets or sets the size of the cache entry value. /// </summary> public long? Size { get => _size; set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), value, $"{nameof(value)} must be non-negative."); } _size = value; } } public object Key { get; private set; } public object? Value { get; set; } internal DateTimeOffset LastAccessed { get; set; } internal EvictionReason EvictionReason { get; private set; } public void Dispose() { if (!_added) { _added = true; _scope.Dispose(); _notifyCacheEntryDisposed(this); PropagateOptions(CacheEntryHelper.Current); } } internal bool CheckExpired(DateTimeOffset now) { return _isExpired || CheckForExpiredTime(now) || CheckForExpiredTokens(); } internal void SetExpired(EvictionReason reason) { if (EvictionReason == EvictionReason.None) { EvictionReason = reason; } _isExpired = true; DetachTokens(); } private bool CheckForExpiredTime(DateTimeOffset now) { if (_absoluteExpiration.HasValue && _absoluteExpiration.Value <= now) { SetExpired(EvictionReason.Expired); return true; } if (_slidingExpiration.HasValue && (now - LastAccessed) >= _slidingExpiration) { SetExpired(EvictionReason.Expired); return true; } return false; } internal bool CheckForExpiredTokens() { if (_expirationTokens != null) { for (int i = 0; i < _expirationTokens.Count; i++) { var expiredToken = _expirationTokens[i]; if (expiredToken.HasChanged) { SetExpired(EvictionReason.TokenExpired); return true; } } } return false; } internal void AttachTokens() { if (_expirationTokens != null) { lock (_lock) { for (int i = 0; i < _expirationTokens.Count; i++) { var expirationToken = _expirationTokens[i]; if (expirationToken.ActiveChangeCallbacks) { if (_expirationTokenRegistrations == null) { _expirationTokenRegistrations = new List<IDisposable>(1); } var registration = expirationToken.RegisterChangeCallback(ExpirationCallback, this); _expirationTokenRegistrations.Add(registration); } } } } } private static void ExpirationTokensExpired(object obj) { // start a new thread to avoid issues with callbacks called from RegisterChangeCallback Task.Factory.StartNew(state => { var entry = (CacheEntry)state!; entry.SetExpired(EvictionReason.TokenExpired); entry._notifyCacheOfExpiration(entry); }, obj, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } private void DetachTokens() { lock(_lock) { var registrations = _expirationTokenRegistrations; if (registrations != null) { _expirationTokenRegistrations = null; for (int i = 0; i < registrations.Count; i++) { var registration = registrations[i]; registration.Dispose(); } } } } internal void InvokeEvictionCallbacks() { if (_postEvictionCallbacks != null) { Task.Factory.StartNew(state => InvokeCallbacks((CacheEntry)state!), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } } private static void InvokeCallbacks(CacheEntry entry) { var callbackRegistrations = Interlocked.Exchange(ref entry._postEvictionCallbacks, null); if (callbackRegistrations == null) { return; } for (int i = 0; i < callbackRegistrations.Count; i++) { var registration = callbackRegistrations[i]; try { registration.EvictionCallback?.Invoke(entry.Key, entry.Value, entry.EvictionReason, registration.State); } catch (Exception) { // This will be invoked on a background thread, don't let it throw. // TODO: LOG } } } internal void PropagateOptions(CacheEntry? parent) { if (parent == null) { return; } // Copy expiration tokens and AbsoluteExpiration to the cache entries hierarchy. // We do this regardless of it gets cached because the tokens are associated with the value we'll return. if (_expirationTokens != null) { lock (_lock) { lock (parent._lock) { foreach (var expirationToken in _expirationTokens) { parent.AddExpirationToken(expirationToken); } } } } if (_absoluteExpiration.HasValue) { if (!parent._absoluteExpiration.HasValue || _absoluteExpiration < parent._absoluteExpiration) { parent._absoluteExpiration = _absoluteExpiration; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Connections; using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Http.Connections.Client; using Microsoft.AspNetCore.SignalR.Protocol; using Microsoft.AspNetCore.SignalR.Tests; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Testing; using Microsoft.Extensions.Options; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.AspNetCore.SignalR.Client.FunctionalTests { public class HubProtocolVersionTestsCollection : ICollectionFixture<InProcessTestServer<VersionStartup>> { public const string Name = nameof(HubProtocolVersionTestsCollection); } [Collection(HubProtocolVersionTestsCollection.Name)] public class HubProtocolVersionTests : FunctionalTestBase { [Theory] [MemberData(nameof(TransportTypes))] public async Task ClientUsingOldCallWithOriginalProtocol(HttpTransportType transportType) { await using (var server = await StartServer<VersionStartup>()) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); var connection = connectionBuilder.Build(); try { await connection.StartAsync().DefaultTimeout(); var result = await connection.InvokeAsync<string>(nameof(VersionHub.Echo), "Hello World!").DefaultTimeout(); Assert.Equal("Hello World!", result); } catch (Exception ex) { LoggerFactory.CreateLogger<HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } } [Theory] [MemberData(nameof(TransportTypes))] public async Task ClientUsingOldCallWithNewProtocol(HttpTransportType transportType) { await using (var server = await StartServer<VersionStartup>()) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton<IHubProtocol>(new VersionedJsonHubProtocol(1000)); var connection = connectionBuilder.Build(); try { await connection.StartAsync().DefaultTimeout(); var result = await connection.InvokeAsync<string>(nameof(VersionHub.Echo), "Hello World!").DefaultTimeout(); Assert.Equal("Hello World!", result); } catch (Exception ex) { LoggerFactory.CreateLogger<HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } } [Theory] [MemberData(nameof(TransportTypes))] public async Task ClientUsingNewCallWithNewProtocol(HttpTransportType transportType) { await using (var server = await StartServer<VersionStartup>()) { var httpConnectionFactory = new HttpConnectionFactory( Options.Create(new HttpConnectionOptions { Transports = transportType, DefaultTransferFormat = TransferFormat.Text }), LoggerFactory); var tcs = new TaskCompletionSource(); var proxyConnectionFactory = new ProxyConnectionFactory(httpConnectionFactory); var connectionBuilder = new HubConnectionBuilder() .WithUrl(new Uri(server.Url + "/version")) .WithLoggerFactory(LoggerFactory); connectionBuilder.Services.AddSingleton<IHubProtocol>(new VersionedJsonHubProtocol(1000)); connectionBuilder.Services.AddSingleton<IConnectionFactory>(proxyConnectionFactory); var connection = connectionBuilder.Build(); connection.On("NewProtocolMethodClient", () => { tcs.SetResult(); }); try { await connection.StartAsync().DefaultTimeout(); // Task should already have been awaited in StartAsync var connectionContext = await proxyConnectionFactory.ConnectTask.DefaultTimeout(); // Simulate a new call from the client var messageToken = new JObject { ["type"] = int.MaxValue }; connectionContext.Transport.Output.Write(Encoding.UTF8.GetBytes(messageToken.ToString())); connectionContext.Transport.Output.Write(new[] { (byte)0x1e }); await connectionContext.Transport.Output.FlushAsync().DefaultTimeout(); await tcs.Task.DefaultTimeout(); } catch (Exception ex) { LoggerFactory.CreateLogger<HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } } [Theory] [MemberData(nameof(TransportTypes))] [LogLevel(LogLevel.Trace)] public async Task ClientWithUnsupportedProtocolVersionDoesNotConnect(HttpTransportType transportType) { bool ExpectedErrors(WriteContext writeContext) { return writeContext.LoggerName == typeof(HubConnection).FullName; } await using (var server = await StartServer<VersionStartup>(ExpectedErrors)) { var connectionBuilder = new HubConnectionBuilder() .WithLoggerFactory(LoggerFactory) .WithUrl(server.Url + "/version", transportType); connectionBuilder.Services.AddSingleton<IHubProtocol>(new VersionedJsonHubProtocol(int.MaxValue)); var connection = connectionBuilder.Build(); try { await ExceptionAssert.ThrowsAsync<HubException>( () => connection.StartAsync(), "Unable to complete handshake with the server due to an error: The server does not support version 2147483647 of the 'json' protocol.").DefaultTimeout(); } catch (Exception ex) { LoggerFactory.CreateLogger<HubConnectionTests>().LogError(ex, "{ExceptionType} from test", ex.GetType().FullName); throw; } finally { await connection.DisposeAsync().DefaultTimeout(); } } } private class ProxyConnectionFactory : IConnectionFactory { private readonly IConnectionFactory _innerFactory; public ValueTask<ConnectionContext> ConnectTask { get; private set; } public ProxyConnectionFactory(IConnectionFactory innerFactory) { _innerFactory = innerFactory; } public ValueTask<ConnectionContext> ConnectAsync(EndPoint endPoint, CancellationToken cancellationToken = default) { ConnectTask = _innerFactory.ConnectAsync(endPoint, cancellationToken); return ConnectTask; } } public static IEnumerable<object[]> TransportTypes() { if (TestHelpers.IsWebSocketsSupported()) { yield return new object[] { HttpTransportType.WebSockets }; } yield return new object[] { HttpTransportType.ServerSentEvents }; yield return new object[] { HttpTransportType.LongPolling }; } } }
//------------------------------------------------------------------------------ // <copyright file="PeerNameResolver.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.PeerToPeer { using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.Threading; using System.Security.Permissions; using System.Runtime.InteropServices; using System.Net; using System.Net.Sockets; using System.Diagnostics; /// <summary> /// This is the event args class we give back each time when /// we have incremental resolution results /// </summary> public class ResolveProgressChangedEventArgs : ProgressChangedEventArgs { private PeerNameRecord m_PeerNameRecord; /// <summary> /// We use progress percentage of **0** all times sice /// we will not no upfront how many records we are going to get /// </summary> /// <param name="peerNameRecord"></param> /// <param name="userToken"></param> public ResolveProgressChangedEventArgs(PeerNameRecord peerNameRecord, object userToken) : base(0, userToken) { m_PeerNameRecord = peerNameRecord; } public PeerNameRecord PeerNameRecord { get { return m_PeerNameRecord; } } } /// <summary> /// When the resolution completes, we invoke the callback with this event args instance /// </summary> public class ResolveCompletedEventArgs : AsyncCompletedEventArgs { private PeerNameRecordCollection m_PeerNameRecordCollection; public ResolveCompletedEventArgs( PeerNameRecordCollection peerNameRecordCollection, Exception error, bool canceled, object userToken) : base(error, canceled, userToken) { m_PeerNameRecordCollection = peerNameRecordCollection; } public PeerNameRecordCollection PeerNameRecordCollection { get { return m_PeerNameRecordCollection; } } } internal class PeerNameResolverHelper : IDisposable { private const UInt32 FACILITY_P2P = 99; private const UInt32 NO_MORE_RECORDS = 0x4003; private const int PEER_E_NO_MORE = (int)(((int)1 << 31) | ((int)FACILITY_P2P << 16) | NO_MORE_RECORDS); //------------------------------------------ //userState the user has supplied //------------------------------------------ internal object m_userState; //------------------------------------------ //Handle to the resolution process //------------------------------------------ internal SafePeerNameEndResolve m_SafePeerNameEndResolve; //------------------------------------------ //Event that the native API sets to indicate that //information is available and that we should call //the PeerPnrpGetEndPoint() to get the end point //------------------------------------------ internal AutoResetEvent m_EndPointInfoAvailableEvent = new AutoResetEvent(false); //------------------------------------------ //The WaitHandle that hooks up a callback to the //event //------------------------------------------ internal RegisteredWaitHandle m_RegisteredWaitHandle; //------------------------------------------ //PeerName that is being resolved //------------------------------------------ internal PeerName m_PeerName; //------------------------------------------ //Cloud in which the resolution must occur //------------------------------------------ internal Cloud m_Cloud; //------------------------------------------ //Max number of records to resolve //------------------------------------------ internal int m_MaxRecords; //------------------------------------------ //Disposed or not //------------------------------------------ internal bool m_Disposed; //----------------------------------------- //Flag to indicate completed or an exception //happened. If you set this flag you own //calling the callback //----------------------------------------- internal bool m_CompletedOrException; //----------------------------------------- //Flag to indicate that the call is canceled //If you set this flag you own calling the callback //----------------------------------------- internal bool m_Cancelled; //------------------------------------------ //A place to save the incremental results //so that we can invoke the completed //handler with all the results at once //------------------------------------------ PeerNameRecordCollection m_PeerNameRecordCollection = new PeerNameRecordCollection(); //------------------------------------------ //Async operation to ensure synchornization //context //------------------------------------------ AsyncOperation m_AsyncOp; //------------------------------------------ //A link to the resolver to avoid //circular dependencies and enable GC //------------------------------------------ WeakReference m_PeerNameResolverWeakReference; //------------------------------------------ //Lock to make sure things don't mess up stuff //------------------------------------------ object m_Lock = new Object(); //------------------------------------------ //EventID or Just a trackig id //------------------------------------------ int m_TraceEventId; internal PeerNameResolverHelper(PeerName peerName, Cloud cloud, int MaxRecords, object userState, PeerNameResolver parent, int NewTraceEventId) { m_userState = userState; m_PeerName = peerName; m_Cloud = cloud; m_MaxRecords = MaxRecords; m_PeerNameResolverWeakReference = new WeakReference(parent); m_TraceEventId = NewTraceEventId; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "New PeerNameResolverHelper created with TraceEventID {0}", m_TraceEventId); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "\tPeerName: {0}, Cloud: {1}, MaxRecords: {2}, userState {3}, ParentReference {4}", m_PeerName, m_Cloud, m_MaxRecords, userState.GetHashCode(), m_PeerNameResolverWeakReference.Target.GetHashCode() ); } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsClosed():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <CallsSuppressUnmanagedCode Name="UnsafeP2PNativeMethods.PeerPnrpStartResolve(System.String,System.String,System.UInt32,Microsoft.Win32.SafeHandles.SafeWaitHandle,System.Net.PeerToPeer.SafePeerNameEndResolve&):System.Int32" /> // <ReferencesCritical Name="Method: EndPointInfoAvailableCallback(Object, Boolean):Void" Ring="1" /> // <ReferencesCritical Name="Field: m_SafePeerNameEndResolve" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal void StartAsyncResolve() { //------------------------------------------ //Check for disposal //------------------------------------------ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); //------------------------------------------ //First wire up a callback //------------------------------------------ m_RegisteredWaitHandle = ThreadPool.RegisterWaitForSingleObject(m_EndPointInfoAvailableEvent, //Event that triggers the callback new WaitOrTimerCallback(EndPointInfoAvailableCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers not for events false //call us everytime the event is set not just one time ); //------------------------------------------ //Now call the native API to start the resolution //process save the handle for later //------------------------------------------ Int32 result = UnsafeP2PNativeMethods.PeerPnrpStartResolve(m_PeerName.ToString(), m_Cloud.InternalName, (UInt32)m_MaxRecords, m_EndPointInfoAvailableEvent.SafeWaitHandle, out m_SafePeerNameEndResolve); if (result != 0) { if (!m_SafePeerNameEndResolve.IsInvalid && !m_SafePeerNameEndResolve.IsClosed) { m_SafePeerNameEndResolve.Dispose(); } m_RegisteredWaitHandle.Unregister(null); m_RegisteredWaitHandle = null; PeerToPeerException ex = PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_CouldNotStartNameResolution), result); Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, m_TraceEventId, "Exception occurred while starting async resolve"); throw ex; } //------------------------------------------ //Create an async operation with the given //user state //------------------------------------------ m_AsyncOp = AsyncOperationManager.CreateOperation(m_userState); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Successfully started the async resolve. The native handle is {0}", m_SafePeerNameEndResolve.DangerousGetHandle()); } // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local pEndPointInfo of type: PEER_PNRP_ENDPOINT_INFO*" /> // <UsesUnsafeCode Name="Method: IntPtr.op_Explicit(System.IntPtr):System.Void*" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStringUni(System.IntPtr):System.String" /> // <SatisfiesLinkDemand Name="Marshal.Copy(System.IntPtr,System.Byte[],System.Int32,System.Int32):System.Void" /> // <SatisfiesLinkDemand Name="Marshal.ReadIntPtr(System.IntPtr):System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.SizeOf(System.Type):System.Int32" /> // <CallsSuppressUnmanagedCode Name="UnsafeP2PNativeMethods.PeerPnrpGetEndpoint(System.IntPtr,System.Net.PeerToPeer.SafePeerData&):System.Int32" /> // <ReferencesCritical Name="Local shEndPointInfo of type: SafePeerData" Ring="1" /> // <ReferencesCritical Name="Field: m_SafePeerNameEndResolve" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public void EndPointInfoAvailableCallback(object state, bool timedOut) { //------------------------------------------ //This callback is called whenever there is an endpoint info //available or the resultion is completed //------------------------------------------ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "EndPointInfoAvailableCallback called"); PeerNameRecord record = null; SafePeerData shEndPointInfo; Int32 result = 0; PeerNameResolver parent = null; if (m_Cancelled) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Detected that the async operation is already canceled - before entering the lock"); return; } lock (m_Lock) { if (m_Cancelled) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Detected that the async operation is already canceled - after entering the lock"); return; } result = UnsafeP2PNativeMethods.PeerPnrpGetEndpoint(m_SafePeerNameEndResolve.DangerousGetHandle(), out shEndPointInfo); if (result != 0) { if (result == PEER_E_NO_MORE) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Native API returned that there are no more records - resolve completed successfully"); } m_CompletedOrException = true; m_SafePeerNameEndResolve.Dispose(); } else { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Proceeding to retrieve the endpoint information from incremental resolve"); try { unsafe { PEER_PNRP_ENDPOINT_INFO* pEndPointInfo = (PEER_PNRP_ENDPOINT_INFO*)shEndPointInfo.DangerousGetHandle(); record = new PeerNameRecord(); record.PeerName = new PeerName(Marshal.PtrToStringUni(pEndPointInfo->pwszPeerName)); string comment = Marshal.PtrToStringUni(pEndPointInfo->pwszComment); if (comment != null && comment.Length > 0) { record.Comment = comment; } if (pEndPointInfo->payLoad.cbPayload != 0) { record.Data = new byte[pEndPointInfo->payLoad.cbPayload]; Marshal.Copy(pEndPointInfo->payLoad.pbPayload, record.Data, 0, (int)pEndPointInfo->payLoad.cbPayload); } //record.EndPointList = new IPEndPoint[pEndPointInfo->cAddresses]; IntPtr ppSOCKADDRs = pEndPointInfo->ArrayOfSOCKADDRIN6Pointers; for (UInt32 j = 0; j < pEndPointInfo->cAddresses; j++) { IntPtr pSOCKADDR = Marshal.ReadIntPtr(ppSOCKADDRs); byte[] AddressFamilyBuffer = new byte[2]; Marshal.Copy(pSOCKADDR, AddressFamilyBuffer, 0, 2); int addressFamily = 0; #if BIGENDIAN addressFamily = AddressFamilyBuffer[1] + ((int)AddressFamilyBuffer[0] << 8); #else addressFamily = AddressFamilyBuffer[0] + ((int)AddressFamilyBuffer[1] << 8); #endif byte[] buffer = new byte[((AddressFamily)addressFamily == AddressFamily.InterNetwork) ? SystemNetHelpers.IPv4AddressSize : SystemNetHelpers.IPv6AddressSize]; Marshal.Copy(pSOCKADDR, buffer, 0, buffer.Length); IPEndPoint ipe = SystemNetHelpers.IPEndPointFromSOCKADDRBuffer(buffer); record.EndPointCollection.Add(ipe); ppSOCKADDRs = (IntPtr)((long)ppSOCKADDRs + Marshal.SizeOf(typeof(IntPtr))); } } } finally { shEndPointInfo.Dispose(); } record.TracePeerNameRecord(); m_PeerNameRecordCollection.Add(record); ResolveProgressChangedEventArgs resolveProgressChangedEventArgs = new ResolveProgressChangedEventArgs( record, m_AsyncOp.UserSuppliedState); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Proceeding to call progress changed event callback"); parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver; if (parent != null) { parent.PrepareToRaiseProgressChangedEvent(m_AsyncOp, resolveProgressChangedEventArgs); } return; } } ResolveCompletedEventArgs resolveCompletedEventArgs; if (result == PEER_E_NO_MORE) { resolveCompletedEventArgs = new ResolveCompletedEventArgs(m_PeerNameRecordCollection, null, false, m_AsyncOp.UserSuppliedState); } else { PeerToPeerException ex = PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_ExceptionWhileResolvingAPeerName), result); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Exception occurred when the native API is called to harvest an incremental resolve notification"); resolveCompletedEventArgs = new ResolveCompletedEventArgs(null, ex, false, m_AsyncOp.UserSuppliedState); } parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver; if (parent != null) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "Proceeding to call the ResolveCompleted callback"); parent.PrepareToRaiseCompletedEvent(m_AsyncOp, resolveCompletedEventArgs); } return; } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Field: m_SafePeerNameEndResolve" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public void ContineCancelCallback(object state) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "ContineCancelCallback called"); try { if (m_CompletedOrException) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "ContinueCancelCallback detected (before acquiring lock) that another thread has already called completed event - so returning without calling cancel"); return; } lock (m_Lock) { if (m_Cancelled) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "ContinueCancelCallback detected (after acquiring lock) that cancel has already been called"); return; } if (m_CompletedOrException) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "ContinueCancelCallback detected (after acquiring lock) that another thread has already called completed event - so returning without calling cancel"); return; } else { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, m_TraceEventId, "ContinueCancelCallback is proceeding to close the handle and call the Completed callback with Cancelled = true"); } m_Cancelled = true; m_SafePeerNameEndResolve.Dispose(); } PeerNameResolver parent = m_PeerNameResolverWeakReference.Target as PeerNameResolver; if (parent != null) { ResolveCompletedEventArgs e = new ResolveCompletedEventArgs(null, null, true, m_AsyncOp.UserSuppliedState); parent.PrepareToRaiseCompletedEvent(m_AsyncOp, e); } } catch { Logging.P2PTraceSource.TraceEvent(TraceEventType.Critical, m_TraceEventId, "Exception while cancelling the call "); throw; } } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: ContineCancelCallback(Object):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public void CancelAsync() { //Defer the work to a callback ThreadPool.QueueUserWorkItem(new WaitCallback(ContineCancelCallback)); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: Dispose(Boolean):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Field: m_SafePeerNameEndResolve" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public void Dispose(bool disposing) { if (!m_Disposed) { if (!m_SafePeerNameEndResolve.IsInvalid) { m_SafePeerNameEndResolve.Dispose(); } if (m_RegisteredWaitHandle != null) m_RegisteredWaitHandle.Unregister(null); m_RegisteredWaitHandle = null; m_EndPointInfoAvailableEvent.Close(); } m_Disposed = true; } internal int TraceEventId { get { return m_TraceEventId; } } } /// <summary> /// PeerNameResolver does [....] and async resolves. /// PeerNameResolver supports multiple outstanding async calls /// </summary> public class PeerNameResolver { static PeerNameResolver() { //------------------------------------------------- //Check for the availability of the simpler PNRP APIs //------------------------------------------------- if (!PeerToPeerOSHelper.SupportsP2P) { throw new PlatformNotSupportedException(SR.GetString(SR.P2P_NotAvailable)); } } private event EventHandler<ResolveProgressChangedEventArgs> m_ResolveProgressChanged; /// <summary> /// When an event handler is hooked up or removed, we demand the permissions. /// In partial trust cases, this will avoid the security risk of just hooking up an existing instance /// of the PeerNameResolver and then receiving all notification of /// in resolution that is happening /// </summary> public event EventHandler<ResolveProgressChangedEventArgs> ResolveProgressChanged { add { PnrpPermission.UnrestrictedPnrpPermission.Demand(); m_ResolveProgressChanged += value; } remove { PnrpPermission.UnrestrictedPnrpPermission.Demand(); m_ResolveProgressChanged -= value; } } private event EventHandler<ResolveCompletedEventArgs> m_ResolveCompleted; /// <summary> /// When an event handler is hooked up or removed, we demand the permissions. /// In partial trust cases, this will avoid the security risk of just hooking up an existing instance /// of the PeerNameResolver and then receiving all notification of /// in resolution that is happening /// </summary> public event EventHandler<ResolveCompletedEventArgs> ResolveCompleted { add { PnrpPermission.UnrestrictedPnrpPermission.Demand(); m_ResolveCompleted += value; } remove { PnrpPermission.UnrestrictedPnrpPermission.Demand(); m_ResolveCompleted -= value; } } SendOrPostCallback OnResolveProgressChangedDelegate; SendOrPostCallback OnResolveCompletedDelegate; /// <summary> /// The following lock and the Sorted Dictionary served /// the purpose of keeping an account of the multiple outstanding async /// resolutions. Each outstanding async operation is /// keyed based on the userState parameter passed in /// </summary> private object m_PeerNameResolverHelperListLock = new object(); private Dictionary<object, PeerNameResolverHelper> m_PeerNameResolverHelperList = new Dictionary<object, PeerNameResolverHelper>(); public PeerNameResolver() { OnResolveProgressChangedDelegate = new SendOrPostCallback(ResolveProgressChangedWaitCallback); OnResolveCompletedDelegate = new SendOrPostCallback(ResolveCompletedWaitCallback); } public PeerNameRecordCollection Resolve(PeerName peerName) { return Resolve(peerName, Cloud.Available, int.MaxValue); } public PeerNameRecordCollection Resolve(PeerName peerName, Cloud cloud) { return Resolve(peerName, cloud, int.MaxValue); } public PeerNameRecordCollection Resolve(PeerName peerName, int maxRecords) { return Resolve(peerName, Cloud.Available, maxRecords); } /// <summary> /// Implements [....] resolve of the PeerName in the cloud given /// </summary> /// <param name="peerName"></param> /// <param name="cloud"></param> /// <param name="MaxRecords"></param> /// <returns></returns> // <SecurityKernel Critical="True" Ring="0"> // <UsesUnsafeCode Name="Local pEndPoints of type: PEER_PNRP_ENDPOINT_INFO*" /> // <UsesUnsafeCode Name="Local pEndPointInfo of type: PEER_PNRP_ENDPOINT_INFO*" /> // <UsesUnsafeCode Name="Method: IntPtr.op_Explicit(System.IntPtr):System.Void*" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStringUni(System.IntPtr):System.String" /> // <SatisfiesLinkDemand Name="Marshal.Copy(System.IntPtr,System.Byte[],System.Int32,System.Int32):System.Void" /> // <SatisfiesLinkDemand Name="Marshal.ReadIntPtr(System.IntPtr):System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.SizeOf(System.Type):System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <CallsSuppressUnmanagedCode Name="UnsafeP2PNativeMethods.PeerPnrpResolve(System.String,System.String,System.UInt32&,System.Net.PeerToPeer.SafePeerData&):System.Int32" /> // <ReferencesCritical Name="Local shEndPointInfoArray of type: SafePeerData" Ring="1" /> // <ReferencesCritical Name="Method: UnsafeP2PNativeMethods.PnrpStartup():System.Void" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] public PeerNameRecordCollection Resolve(PeerName peerName, Cloud cloud, int maxRecords) { //--------------------------------------------------- //Check arguments //--------------------------------------------------- if (peerName == null) { throw new ArgumentNullException(SR.GetString(SR.Pnrp_PeerNameCantBeNull), "peerName"); } if (maxRecords <= 0) { throw new ArgumentOutOfRangeException("maxRecords", SR.GetString(SR.Pnrp_MaxRecordsParameterMustBeGreaterThanZero)); } //--------------------------------------------------- //Assume all clouds if the clould passed is null? //--------------------------------------------------- if (cloud == null) { cloud = Cloud.Available; } //--------------------------------------------------- //Demand CAS permissions //--------------------------------------------------- PnrpPermission.UnrestrictedPnrpPermission.Demand(); //--------------------------------------------------------------- //No perf hit here, real native call happens only one time if it //did not already happen //--------------------------------------------------------------- UnsafeP2PNativeMethods.PnrpStartup(); //--------------------------------------------------------------- //Trace log //--------------------------------------------------------------- Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "[....] Resolve called with PeerName: {0}, Cloud: {1}, MaxRecords {2}", peerName, cloud, maxRecords); SafePeerData shEndPointInfoArray; string NativeCloudName = cloud.InternalName; UInt32 ActualCountOfEndPoints = (UInt32)maxRecords; int result = UnsafeP2PNativeMethods.PeerPnrpResolve(peerName.ToString(), NativeCloudName, ref ActualCountOfEndPoints, out shEndPointInfoArray); if (result != 0) { throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Pnrp_CouldNotStartNameResolution), result); } //--------------------------------------------------- //If there are no endpoints returned, return //an empty PeerNameRecord Collection //--------------------------------------------------- PeerNameRecordCollection PeerNameRecords = new PeerNameRecordCollection(); if (ActualCountOfEndPoints != 0) { try { unsafe { IntPtr pEndPointInfoArray = shEndPointInfoArray.DangerousGetHandle(); PEER_PNRP_ENDPOINT_INFO* pEndPoints = (PEER_PNRP_ENDPOINT_INFO*)pEndPointInfoArray; for (int i = 0; i < ActualCountOfEndPoints; i++) { PeerNameRecord record = new PeerNameRecord(); PEER_PNRP_ENDPOINT_INFO* pEndPointInfo = &pEndPoints[i]; record.PeerName = new PeerName(Marshal.PtrToStringUni(pEndPointInfo->pwszPeerName)); string comment = Marshal.PtrToStringUni(pEndPointInfo->pwszComment); if (comment != null && comment.Length > 0) { record.Comment = comment; } if (pEndPointInfo->payLoad.cbPayload != 0) { record.Data = new byte[pEndPointInfo->payLoad.cbPayload]; Marshal.Copy(pEndPointInfo->payLoad.pbPayload, record.Data, 0, (int)pEndPointInfo->payLoad.cbPayload); } //record.EndPointList = new IPEndPoint[pEndPointInfo->cAddresses]; IntPtr ppSOCKADDRs = pEndPointInfo->ArrayOfSOCKADDRIN6Pointers; for (UInt32 j = 0; j < pEndPointInfo->cAddresses; j++) { IntPtr pSOCKADDR = Marshal.ReadIntPtr(ppSOCKADDRs); byte[] AddressFamilyBuffer = new byte[2]; Marshal.Copy(pSOCKADDR, AddressFamilyBuffer, 0, 2); int addressFamily = 0; #if BIGENDIAN addressFamily = AddressFamilyBuffer[1] + ((int)AddressFamilyBuffer[0] << 8); #else addressFamily = AddressFamilyBuffer[0] + ((int)AddressFamilyBuffer[1] << 8); #endif byte[] buffer = new byte[((AddressFamily)addressFamily == AddressFamily.InterNetwork) ? SystemNetHelpers.IPv4AddressSize : SystemNetHelpers.IPv6AddressSize]; Marshal.Copy(pSOCKADDR, buffer, 0, buffer.Length); IPEndPoint ipe = SystemNetHelpers.IPEndPointFromSOCKADDRBuffer(buffer); record.EndPointCollection.Add(ipe); ppSOCKADDRs = (IntPtr)((long)ppSOCKADDRs + Marshal.SizeOf(typeof(IntPtr))); } //---------------------------------- //Dump for trace //---------------------------------- record.TracePeerNameRecord(); //---------------------------------- //Add to collection //---------------------------------- PeerNameRecords.Add(record); } } } finally { shEndPointInfoArray.Dispose(); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "[....] Resolve returnig with PeerNameRecord count :{0}", PeerNameRecords.Count); return PeerNameRecords; } [HostProtection(ExternalThreading = true)] public void ResolveAsync(PeerName peerName, object userState) { ResolveAsync(peerName, Cloud.Available, Int32.MaxValue, userState); } [HostProtection(ExternalThreading = true)] public void ResolveAsync(PeerName peerName, Cloud cloud, object userState) { ResolveAsync(peerName, cloud, Int32.MaxValue, userState); } [HostProtection(ExternalThreading = true)] public void ResolveAsync(PeerName peerName, int maxRecords, object userState) { ResolveAsync(peerName, Cloud.Available, maxRecords, userState); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: UnsafeP2PNativeMethods.PnrpStartup():System.Void" Ring="1" /> // <ReferencesCritical Name="Method: PeerNameResolverHelper.StartAsyncResolve():System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] [HostProtection(ExternalThreading = true)] public void ResolveAsync(PeerName peerName, Cloud cloud, int maxRecords, object userState) { //------------------------------------------------- //Check arguments //------------------------------------------------- if (peerName == null) { throw new ArgumentNullException(SR.GetString(SR.Pnrp_PeerNameCantBeNull), "peerName"); } if (cloud == null) { cloud = Cloud.Available; } if (maxRecords <= 0) { throw new ArgumentOutOfRangeException("maxRecords", SR.GetString(SR.Pnrp_MaxRecordsParameterMustBeGreaterThanZero)); } if (m_ResolveCompleted == null) { throw new PeerToPeerException(SR.GetString(SR.Pnrp_AtleastOneEvenHandlerNeeded)); } //--------------------------------------------------- //Demand CAS permissions //--------------------------------------------------- PnrpPermission.UnrestrictedPnrpPermission.Demand(); //--------------------------------------------------------------- //No perf hit here, real native call happens only one time if it //did not already happen //--------------------------------------------------------------- UnsafeP2PNativeMethods.PnrpStartup(); //---------------------------------------------------- //userToken can't be null //---------------------------------------------------- if (userState == null) { throw new ArgumentNullException(SR.GetString(SR.NullUserToken), "userState"); } PeerNameResolverHelper peerNameResolverHelper = null; //--------------------------------------------------- //The userToken can't be duplicate of what is in the //current list. These are the requriments for the new Async model //that supports multiple outstanding async calls //--------------------------------------------------- int newTraceEventId = NewTraceEventId; lock (m_PeerNameResolverHelperListLock) { if (m_PeerNameResolverHelperList.ContainsKey(userState)) { throw new ArgumentException(SR.GetString(SR.DuplicateUserToken)); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, newTraceEventId, "PeerNameResolverHelper is being created with TraceEventId {0}", newTraceEventId); peerNameResolverHelper = new PeerNameResolverHelper(peerName, cloud, maxRecords, userState, this, newTraceEventId); m_PeerNameResolverHelperList[userState] = peerNameResolverHelper; } try { //--------------------------------------------------- //Start resolution on that resolver //--------------------------------------------------- peerNameResolverHelper.StartAsyncResolve(); } catch { //--------------------------------------------------- //If an exception happens clear the userState from the //list so that that token can be reused //--------------------------------------------------- lock (m_PeerNameResolverHelperListLock) { m_PeerNameResolverHelperList.Remove(userState); Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, newTraceEventId, "Removing userState token from pending list {0}", userState.GetHashCode()); } throw; } } protected void OnResolveProgressChanged(ResolveProgressChangedEventArgs e) { if (m_ResolveProgressChanged != null) { m_ResolveProgressChanged(this, e); } } void ResolveProgressChangedWaitCallback(object operationState) { OnResolveProgressChanged((ResolveProgressChangedEventArgs)operationState); } internal void PrepareToRaiseProgressChangedEvent(AsyncOperation asyncOP, ResolveProgressChangedEventArgs args) { asyncOP.Post(OnResolveProgressChangedDelegate, args); } protected void OnResolveCompleted(ResolveCompletedEventArgs e) { if (m_ResolveCompleted != null) { m_ResolveCompleted(this, e); } } void ResolveCompletedWaitCallback(object operationState) { OnResolveCompleted((ResolveCompletedEventArgs)operationState); } internal void PrepareToRaiseCompletedEvent(AsyncOperation asyncOP, ResolveCompletedEventArgs args) { asyncOP.PostOperationCompleted(OnResolveCompletedDelegate, args); lock (m_PeerNameResolverHelperListLock) { PeerNameResolverHelper helper = m_PeerNameResolverHelperList[args.UserState]; if (helper == null) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Critical, 0, "userState for which we are about to call Completed event does not exist in the pending async list"); } else { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, helper.TraceEventId, "userState {0} is being removed from the pending async list", args.UserState.GetHashCode()); m_PeerNameResolverHelperList.Remove(args.UserState); } } } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: PeerNameResolverHelper.CancelAsync():System.Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] public void ResolveAsyncCancel(object userState) { PnrpPermission.UnrestrictedPnrpPermission.Demand(); if (userState == null) { return; } PeerNameResolverHelper helper; lock (m_PeerNameResolverHelperListLock) { if (!m_PeerNameResolverHelperList.TryGetValue(userState, out helper)) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Warning, 0, "ResolveAsyncCancel called with a userState token that is not in the pending async list - returning"); return; } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, helper.TraceEventId, "Proceeding to cancel the pending async"); helper.CancelAsync(); } private static int s_TraceEventId; private static int NewTraceEventId { get { Interlocked.CompareExchange(ref s_TraceEventId, 0, int.MaxValue); Interlocked.Increment(ref s_TraceEventId); return s_TraceEventId; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Reflection; using System.Text; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using CSJ2K; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public delegate void J2KDecodeDelegate(UUID assetID); [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "J2KDecoderModule")] public class J2KDecoderModule : ISharedRegionModule, IJ2KDecoder { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary>Temporarily holds deserialized layer data information in memory</summary> private readonly ExpiringCache<UUID, OpenJPEG.J2KLayerInfo[]> m_decodedCache = new ExpiringCache<UUID,OpenJPEG.J2KLayerInfo[]>(); /// <summary>List of client methods to notify of results of decode</summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); /// <summary>Cache that will store decoded JPEG2000 layer boundary data</summary> private IImprovedAssetCache m_cache; private IImprovedAssetCache Cache { get { if (m_cache == null) m_cache = m_scene.RequestModuleInterface<IImprovedAssetCache>(); return m_cache; } } /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary> private UUID m_CreatorID = UUID.Zero; private Scene m_scene; #region ISharedRegionModule private bool m_useCSJ2K = true; public string Name { get { return "J2KDecoderModule"; } } public J2KDecoderModule() { } public void Initialise(IConfigSource source) { IConfig startupConfig = source.Configs["Startup"]; if (startupConfig != null) { m_useCSJ2K = startupConfig.GetBoolean("UseCSJ2K", m_useCSJ2K); } } public void AddRegion(Scene scene) { if (m_scene == null) { m_scene = scene; m_CreatorID = scene.RegionInfo.RegionID; } scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void RemoveRegion(Scene scene) { if (m_scene == scene) m_scene = null; } public void PostInitialise() { } public void Close() { } public void RegionLoaded(Scene scene) { } public Type ReplaceableInterface { get { return null; } } #endregion Region Module interface #region IJ2KDecoder public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback) { OpenJPEG.J2KLayerInfo[] result; // If it's cached, return the cached results if (m_decodedCache.TryGetValue(assetID, out result)) { // m_log.DebugFormat( // "[J2KDecoderModule]: Returning existing cached {0} layers j2k decode for {1}", // result.Length, assetID); callback(assetID, result); } else { // Not cached, we need to decode it. // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { m_notifyList[assetID].Add(callback); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(callback); m_notifyList.Add(assetID, notifylist); decode = true; } } // Do Decode! if (decode) Util.FireAndForget(delegate { Decode(assetID, j2kData); }, null, "J2KDecoderModule.BeginDecode"); } } public bool Decode(UUID assetID, byte[] j2kData) { OpenJPEG.J2KLayerInfo[] layers; int components; return Decode(assetID, j2kData, out layers, out components); } public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { return DoJ2KDecode(assetID, j2kData, out layers, out components); } public Image DecodeToImage(byte[] j2kData) { if (m_useCSJ2K) return J2kImage.FromBytes(j2kData); else { ManagedImage mimage; Image image; if (OpenJPEG.DecodeToImage(j2kData, out mimage, out image)) { mimage = null; return image; } else return null; } } #endregion IJ2KDecoder /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="assetID">UUID of Asset</param> /// <param name="j2kData">JPEG2000 data</param> /// <param name="layers">layer data</param> /// <param name="components">number of components</param> /// <returns>true if decode was successful. false otherwise.</returns> private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers, out int components) { // m_log.DebugFormat( // "[J2KDecoderModule]: Doing J2K decoding of {0} bytes for asset {1}", j2kData.Length, assetID); bool decodedSuccessfully = true; //int DecodeTime = 0; //DecodeTime = Environment.TickCount; // We don't get this from CSJ2K. Is it relevant? components = 0; if (!TryLoadCacheForAsset(assetID, out layers)) { if (m_useCSJ2K) { try { List<int> layerStarts; using (MemoryStream ms = new MemoryStream(j2kData)) { layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms); } if (layerStarts != null && layerStarts.Count > 0) { layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; for (int i = 0; i < layerStarts.Count; i++) { OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); if (i == 0) layer.Start = 0; else layer.Start = layerStarts[i]; if (i == layerStarts.Count - 1) layer.End = j2kData.Length; else layer.End = layerStarts[i + 1] - 1; layers[i] = layer; } } } catch (Exception ex) { m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); decodedSuccessfully = false; } } else { if (!OpenJPEG.DecodeLayerBoundaries(j2kData, out layers, out components)) { m_log.Warn("[J2KDecoderModule]: OpenJPEG failed to decode texture " + assetID); decodedSuccessfully = false; } } if (layers == null || layers.Length == 0) { m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults"); // Layer decoding completely failed. Guess at sane defaults for the layer boundaries layers = CreateDefaultLayers(j2kData.Length); decodedSuccessfully = false; } // Cache Decoded layers SaveFileCacheForAsset(assetID, layers); } // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { foreach (DecodedCallback d in m_notifyList[assetID]) { if (d != null) d.DynamicInvoke(assetID, layers); } m_notifyList.Remove(assetID); } } return decodedSuccessfully; } private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength) { OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5]; for (int i = 0; i < layers.Length; i++) layers[i] = new OpenJPEG.J2KLayerInfo(); // These default layer sizes are based on a small sampling of real-world texture data // with extra padding thrown in for good measure. This is a worst case fallback plan // and may not gracefully handle all real world data layers[0].Start = 0; layers[1].Start = (int)((float)j2kLength * 0.02f); layers[2].Start = (int)((float)j2kLength * 0.05f); layers[3].Start = (int)((float)j2kLength * 0.20f); layers[4].Start = (int)((float)j2kLength * 0.50f); layers[0].End = layers[1].Start - 1; layers[1].End = layers[2].Start - 1; layers[2].End = layers[3].Start - 1; layers[3].End = layers[4].Start - 1; layers[4].End = j2kLength; return layers; } private void SaveFileCacheForAsset(UUID AssetId, OpenJPEG.J2KLayerInfo[] Layers) { m_decodedCache.AddOrUpdate(AssetId, Layers, TimeSpan.FromMinutes(10)); if (Cache != null) { string assetID = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = new AssetBase(assetID, assetID, (sbyte)AssetType.Notecard, m_CreatorID.ToString()); layerDecodeAsset.Local = true; layerDecodeAsset.Temporary = true; #region Serialize Layer Data StringBuilder stringResult = new StringBuilder(); string strEnd = "\n"; for (int i = 0; i < Layers.Length; i++) { if (i == Layers.Length - 1) strEnd = String.Empty; stringResult.AppendFormat("{0}|{1}|{2}{3}", Layers[i].Start, Layers[i].End, Layers[i].End - Layers[i].Start, strEnd); } layerDecodeAsset.Data = Util.UTF8.GetBytes(stringResult.ToString()); #endregion Serialize Layer Data Cache.Cache(layerDecodeAsset); } } bool TryLoadCacheForAsset(UUID AssetId, out OpenJPEG.J2KLayerInfo[] Layers) { if (m_decodedCache.TryGetValue(AssetId, out Layers)) { return true; } else if (Cache != null) { string assetName = "j2kCache_" + AssetId.ToString(); AssetBase layerDecodeAsset = Cache.Get(assetName); if (layerDecodeAsset != null) { #region Deserialize Layer Data string readResult = Util.UTF8.GetString(layerDecodeAsset.Data); string[] lines = readResult.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 0) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (empty) " + assetName); Cache.Expire(assetName); return false; } Layers = new OpenJPEG.J2KLayerInfo[lines.Length]; for (int i = 0; i < lines.Length; i++) { string[] elements = lines[i].Split('|'); if (elements.Length == 3) { int element1, element2; try { element1 = Convert.ToInt32(elements[0]); element2 = Convert.ToInt32(elements[1]); } catch (FormatException) { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (format) " + assetName); Cache.Expire(assetName); return false; } Layers[i] = new OpenJPEG.J2KLayerInfo(); Layers[i].Start = element1; Layers[i].End = element2; } else { m_log.Warn("[J2KDecodeCache]: Expiring corrupted layer data (layout) " + assetName); Cache.Expire(assetName); return false; } } #endregion Deserialize Layer Data return true; } } 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. /*============================================================ ** ** ** ** Purpose: Managed ACL wrapper for files & directories. ** ** ===========================================================*/ using Microsoft.Win32.SafeHandles; using Microsoft.Win32; using System.Collections; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.AccessControl; using System.Security.Principal; using System; namespace System.Security.AccessControl { // Constants from from winnt.h - search for FILE_WRITE_DATA, etc. [Flags] public enum FileSystemRights { // No None field - An ACE with the value 0 cannot grant nor deny. ReadData = 0x000001, ListDirectory = ReadData, // For directories WriteData = 0x000002, CreateFiles = WriteData, // For directories AppendData = 0x000004, CreateDirectories = AppendData, // For directories ReadExtendedAttributes = 0x000008, WriteExtendedAttributes = 0x000010, ExecuteFile = 0x000020, // For files Traverse = ExecuteFile, // For directories // DeleteSubdirectoriesAndFiles only makes sense on directories, but // the shell explicitly sets it for files in its UI. So we'll include // it in FullControl. DeleteSubdirectoriesAndFiles = 0x000040, ReadAttributes = 0x000080, WriteAttributes = 0x000100, Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, // From the Core File Services team, CreateFile always requires // SYNCHRONIZE access. Very tricksy, CreateFile is. Synchronize = 0x100000, // Can we wait on the handle? FullControl = 0x1F01FF, // These map to what Explorer sets, and are what most users want. // However, an ACL editor will also want to set the Synchronize // bit when allowing access, and exclude the synchronize bit when // denying access. Read = ReadData | ReadExtendedAttributes | ReadAttributes | ReadPermissions, ReadAndExecute = Read | ExecuteFile, Write = WriteData | AppendData | WriteExtendedAttributes | WriteAttributes, Modify = ReadAndExecute | Write | Delete, } public sealed class FileSystemAccessRule : AccessRule { #region Constructors // // Constructor for creating access rules for file objects // public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, AccessControlType type) : this( identity, AccessMaskFromRights(fileSystemRights, type), false, InheritanceFlags.None, PropagationFlags.None, type) { } public FileSystemAccessRule( string identity, FileSystemRights fileSystemRights, AccessControlType type) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights, type), false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Constructor for creating access rules for folder objects // public FileSystemAccessRule( IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( identity, AccessMaskFromRights(fileSystemRights, type), false, inheritanceFlags, propagationFlags, type) { } public FileSystemAccessRule( string identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights, type), false, inheritanceFlags, propagationFlags, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal FileSystemAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } #endregion #region Public properties public FileSystemRights FileSystemRights { get { return RightsFromAccessMask(base.AccessMask); } } #endregion #region Access mask to rights translation // ACL's on files have a SYNCHRONIZE bit, and CreateFile ALWAYS // asks for it. So for allows, let's always include this bit, // and for denies, let's never include this bit unless we're denying // full control. This is the right thing for users, even if it does // make the model look asymmetrical from a purist point of view. internal static int AccessMaskFromRights(FileSystemRights fileSystemRights, AccessControlType controlType) { if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl) throw new ArgumentOutOfRangeException(nameof(fileSystemRights), SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, nameof(AccessControl.FileSystemRights))); if (controlType == AccessControlType.Allow) { fileSystemRights |= FileSystemRights.Synchronize; } else if (controlType == AccessControlType.Deny) { if (fileSystemRights != FileSystemRights.FullControl && fileSystemRights != (FileSystemRights.FullControl & ~FileSystemRights.DeleteSubdirectoriesAndFiles)) fileSystemRights &= ~FileSystemRights.Synchronize; } return (int)fileSystemRights; } internal static FileSystemRights RightsFromAccessMask(int accessMask) { return (FileSystemRights)accessMask; } #endregion } public sealed class FileSystemAuditRule : AuditRule { #region Constructors public FileSystemAuditRule( IdentityReference identity, FileSystemRights fileSystemRights, AuditFlags flags) : this( identity, fileSystemRights, InheritanceFlags.None, PropagationFlags.None, flags) { } public FileSystemAuditRule( IdentityReference identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( identity, AccessMaskFromRights(fileSystemRights), false, inheritanceFlags, propagationFlags, flags) { } public FileSystemAuditRule( string identity, FileSystemRights fileSystemRights, AuditFlags flags) : this( new NTAccount(identity), fileSystemRights, InheritanceFlags.None, PropagationFlags.None, flags) { } public FileSystemAuditRule( string identity, FileSystemRights fileSystemRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : this( new NTAccount(identity), AccessMaskFromRights(fileSystemRights), false, inheritanceFlags, propagationFlags, flags) { } internal FileSystemAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } #endregion #region Private methods private static int AccessMaskFromRights(FileSystemRights fileSystemRights) { if (fileSystemRights < (FileSystemRights)0 || fileSystemRights > FileSystemRights.FullControl) throw new ArgumentOutOfRangeException(nameof(fileSystemRights), SR.Format(SR.Argument_InvalidEnumValue, fileSystemRights, nameof(AccessControl.FileSystemRights))); return (int)fileSystemRights; } #endregion #region Public properties public FileSystemRights FileSystemRights { get { return FileSystemAccessRule.RightsFromAccessMask(base.AccessMask); } } #endregion } public abstract class FileSystemSecurity : NativeObjectSecurity { #region Member variables private const ResourceType s_ResourceType = ResourceType.FileObject; #endregion internal FileSystemSecurity(bool isContainer) : base(isContainer, s_ResourceType, _HandleErrorCode, isContainer) { } internal FileSystemSecurity(bool isContainer, string name, AccessControlSections includeSections, bool isDirectory) : base(isContainer, s_ResourceType, name, includeSections, _HandleErrorCode, isDirectory) { } internal FileSystemSecurity(bool isContainer, SafeFileHandle handle, AccessControlSections includeSections, bool isDirectory) : base(isContainer, s_ResourceType, handle, includeSections, _HandleErrorCode, isDirectory) { } private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Interop.Errors.ERROR_INVALID_NAME: exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); break; case Interop.Errors.ERROR_INVALID_HANDLE: exception = new ArgumentException(SR.AccessControl_InvalidHandle); break; case Interop.Errors.ERROR_FILE_NOT_FOUND: if ((context != null) && (context is bool) && ((bool)context)) { // DirectorySecurity if ((name != null) && (name.Length != 0)) exception = new DirectoryNotFoundException(name); else exception = new DirectoryNotFoundException(); } else { if ((name != null) && (name.Length != 0)) exception = new FileNotFoundException(name); else exception = new FileNotFoundException(); } break; default: break; } return exception; } #region Factories public sealed override AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new FileSystemAccessRule( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public sealed override AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new FileSystemAuditRule( identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } #endregion #region Internal Methods internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } internal void Persist(string fullPath) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(fullPath, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } internal void Persist(SafeFileHandle handle, string fullPath) { WriteLock(); try { AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); base.Persist(handle, persistRules); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } #endregion #region Public Methods public void AddAccessRule(FileSystemAccessRule rule) { base.AddAccessRule(rule); //PersistIfPossible(); } public void SetAccessRule(FileSystemAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(FileSystemAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(FileSystemAccessRule rule) { if (rule == null) throw new ArgumentNullException(nameof(rule)); // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit. // This is to avoid dangling synchronize bit AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule; if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { return base.RemoveAccessRule(rule); } } // Mask off the synchronize bit (that is automatically added for Allow) // before removing the ACL. The logic here should be same as Deny and hence // fake a call to AccessMaskFromRights as though the ACL is for Deny FileSystemAccessRule ruleNew = new FileSystemAccessRule( rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType); return base.RemoveAccessRule(ruleNew); } public void RemoveAccessRuleAll(FileSystemAccessRule rule) { // We don't need to worry about the synchronize bit here // AccessMask is ignored anyways in a RemoveAll call base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(FileSystemAccessRule rule) { if (rule == null) throw new ArgumentNullException(nameof(rule)); // If the rule to be removed matches what is there currently then // remove it unaltered. That is, don't mask off the Synchronize bit // This is to avoid dangling synchronize bit AuthorizationRuleCollection rules = GetAccessRules(true, true, rule.IdentityReference.GetType()); for (int i = 0; i < rules.Count; i++) { FileSystemAccessRule fsrule = rules[i] as FileSystemAccessRule; if ((fsrule != null) && (fsrule.FileSystemRights == rule.FileSystemRights) && (fsrule.IdentityReference == rule.IdentityReference) && (fsrule.AccessControlType == rule.AccessControlType)) { base.RemoveAccessRuleSpecific(rule); return; } } // Mask off the synchronize bit (that is automatically added for Allow) // before removing the ACL. The logic here should be same as Deny and hence // fake a call to AccessMaskFromRights as though the ACL is for Deny FileSystemAccessRule ruleNew = new FileSystemAccessRule( rule.IdentityReference, FileSystemAccessRule.AccessMaskFromRights(rule.FileSystemRights, AccessControlType.Deny), rule.IsInherited, rule.InheritanceFlags, rule.PropagationFlags, rule.AccessControlType); base.RemoveAccessRuleSpecific(ruleNew); } public void AddAuditRule(FileSystemAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(FileSystemAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(FileSystemAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(FileSystemAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(FileSystemAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } #endregion #region some overrides public override Type AccessRightType { get { return typeof(System.Security.AccessControl.FileSystemRights); } } public override Type AccessRuleType { get { return typeof(System.Security.AccessControl.FileSystemAccessRule); } } public override Type AuditRuleType { get { return typeof(System.Security.AccessControl.FileSystemAuditRule); } } #endregion } public sealed class FileSecurity : FileSystemSecurity { #region Constructors public FileSecurity() : base(false) { } public FileSecurity(string fileName, AccessControlSections includeSections) : base(false, fileName, includeSections, false) { string fullPath = Path.GetFullPath(fileName); } // Warning! Be exceedingly careful with this constructor. Do not make // it public. We don't want to get into a situation where someone can // pass in the string foo.txt and a handle to bar.exe, and we do a // demand on the wrong file name. internal FileSecurity(SafeFileHandle handle, string fullPath, AccessControlSections includeSections) : base(false, handle, includeSections, false) { } #endregion } public sealed class DirectorySecurity : FileSystemSecurity { #region Constructors public DirectorySecurity() : base(true) { } public DirectorySecurity(string name, AccessControlSections includeSections) : base(true, name, includeSections, true) { string fullPath = Path.GetFullPath(name); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration.Provider; using System.Linq; using System.Web.Hosting; using Velyo.Web.Security.Models; using Velyo.Web.Security.Resources; using Velyo.Web.Security.Store; namespace Velyo.Web.Security { /// <summary> /// Custom XML implementation of <c>System.Web.Security.RoleProvider</c> /// </summary> public class XmlRoleProvider : RoleProviderBase, IDisposable { private string _file; private XmlRoleStore _store; ~XmlRoleProvider() { Dispose(false); } /// <summary> /// Gets the roles. /// </summary> /// <value>The roles.</value> protected List<Role> Roles { get { return Store.Roles; } } /// <summary> /// Gets the role store. /// </summary> /// <value>The role store.</value> protected XmlRoleStore Store { get { return _store ?? (_store = new XmlRoleStore(_file)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if(disposing) { if (_store != null) { _store.Dispose(); _store = null; } } } /// <summary> /// Adds the specified user names to the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be added to the specified roles.</param> /// <param name="roleNames">A string array of the role names to add the specified user names to.</param> public override void AddUsersToRoles(string[] usernames, string[] roleNames) { if (usernames == null) throw new ArgumentNullException(nameof(usernames)); if (roleNames == null) throw new ArgumentNullException(nameof(roleNames)); var comparer = Comparer; lock (SyncRoot) { foreach (string rolename in roleNames) { Role role = GetRole(rolename); if (role != null) { foreach (string username in usernames) { if (!role.Users.Contains(username, comparer)) role.Users.Add(username); } } } Store.Save(); } } /// <summary> /// Adds a new role to the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to create.</param> public override void CreateRole(string roleName) { if (roleName == null) throw new ArgumentNullException(nameof(roleName)); if (roleName.IndexOf(',') > 0) throw new ArgumentException(Messages.RoleCannotContainCommas); Role role = GetRole(roleName); if (role == null) { role = new Role { Name = roleName, Users = new List<string>() }; lock (SyncRoot) { Store.Roles.Add(role); Store.Save(); } } else { throw new ProviderException(string.Format(Messages.RoleExists, roleName)); } } /// <summary> /// Removes a role from the data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to delete.</param> /// <param name="throwOnPopulatedRole">If true, throw an exception if roleName has one or more members and do not delete roleName.</param> /// <returns> /// true if the role was successfully deleted; otherwise, false. /// </returns> public override bool DeleteRole(string roleName, bool throwOnPopulatedRole) { if (roleName == null) throw new ArgumentNullException(nameof(roleName)); lock (SyncRoot) { Role role = GetRole(roleName); if (role != null) { if (throwOnPopulatedRole && (role.Users.Count > 0)) throw new ProviderException(Messages.CannotDeletePopulatedRole); Store.Roles.Remove(role); Store.Save(); return true; } return false; } } /// <summary> /// Gets an array of user names in a role where the user name contains the specified user name to match. /// </summary> /// <param name="roleName">The role to search in.</param> /// <param name="usernameToMatch">The user name to search for.</param> /// <returns> /// A string array containing the names of all the users where the user name matches usernameToMatch and the user is a member of the specified role. /// </returns> public override string[] FindUsersInRole(string roleName, string usernameToMatch) { if (roleName == null) throw new ArgumentNullException(nameof(roleName)); if (usernameToMatch == null) throw new ArgumentNullException(nameof(usernameToMatch)); var comparison = Comparison; var query = from role in Roles.AsQueryable() from user in role.Users where (user.IndexOf(usernameToMatch, comparison) >= 0) && role.Name.Equals(roleName, comparison) select user; lock (SyncRoot) { return query.ToArray(); } } /// <summary> /// Gets a list of all the roles for the configured applicationName. /// </summary> /// <returns> /// A string array containing the names of all the roles stored in the data source for the configured applicationName. /// </returns> public override string[] GetAllRoles() { var query = from r in Roles select r.Name; lock (SyncRoot) { return query.ToArray(); } } /// <summary> /// Gets the role. /// </summary> /// <param name="roleName">The name.</param> /// <returns></returns> public Role GetRole(string roleName) { if (roleName == null) throw new ArgumentNullException(nameof(roleName)); var query = from r in Roles where r.Name.Equals(roleName, Comparison) select r; lock (SyncRoot) { return query.FirstOrDefault(); } } /// <summary> /// Gets a list of the roles that a specified user is in for the configured applicationName. /// </summary> /// <param name="username">The user to return a list of roles for.</param> /// <returns> /// A string array containing the names of all the roles that the specified user is in for the configured applicationName. /// </returns> public override string[] GetRolesForUser(string username) { if (username == null) throw new ArgumentNullException(nameof(username)); var query = from r in Roles where r.Users.Contains(username, Comparer) select r.Name; lock (SyncRoot) { return query.ToArray(); } } /// <summary> /// Gets a list of users in the specified role for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to get the list of users for.</param> /// <returns> /// A string array containing the names of all the users who are members of the specified role for the configured applicationName. /// </returns> public override string[] GetUsersInRole(string roleName) { Role role = GetRole(roleName); if (role != null) { lock (SyncRoot) { return role.Users.ToArray(); } } else { throw new ProviderException(string.Format(Messages.RoleNotExists, roleName)); } } /// <summary> /// Gets a value indicating whether the specified user is in the specified role for the configured applicationName. /// </summary> /// <param name="username">The user name to search for.</param> /// <param name="roleName">The role to search in.</param> /// <returns> /// true if the specified user is in the specified role for the configured applicationName; otherwise, false. /// </returns> public override bool IsUserInRole(string username, string roleName) { if (username == null) throw new ArgumentNullException(nameof(username)); Role role = GetRole(roleName); if (role != null) { lock (SyncRoot) { return role.Users.Contains(username, Comparer); } } else { throw new ProviderException(string.Format(Messages.RoleNotExists, roleName)); } } /// <summary> /// Removes the specified user names from the specified roles for the configured applicationName. /// </summary> /// <param name="usernames">A string array of user names to be removed from the specified roles.</param> /// <param name="roleNames">A string array of role names to remove the specified user names from.</param> public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames) { if (usernames == null) throw new ArgumentNullException(nameof(usernames)); if (roleNames == null) throw new ArgumentNullException(nameof(roleNames)); var comparer = Comparer; var query = from r in Roles where roleNames.Contains(r.Name, comparer) select r; lock (SyncRoot) { foreach (Role role in query) { foreach (string username in usernames) { role.Users.Remove(username); } } Store.Save(); } } /// <summary> /// Gets a value indicating whether the specified role name already exists in the role data source for the configured applicationName. /// </summary> /// <param name="roleName">The name of the role to search for in the data source.</param> /// <returns> /// true if the role name already exists in the data source for the configured applicationName; otherwise, false. /// </returns> public override bool RoleExists(string roleName) { return GetRole(roleName) != null; } #region - Initialize - /// <summary> /// Initializes the provider. /// </summary> /// <param name="name">The friendly name of the provider.</param> /// <param name="config">A collection of the name/value pairs representing the provider-specific attributes specified in the configuration for this provider.</param> /// <exception cref="T:System.ArgumentNullException">The name of the provider is null.</exception> /// <exception cref="T:System.InvalidOperationException">An attempt is made to call <see cref="M:System.Configuration.Provider.ProviderBase.Initialize(System.String,System.Collections.Specialized.NameValueCollection)"></see> on a provider after the provider has already been initialized.</exception> /// <exception cref="T:System.ArgumentException">The name of the provider has a length of zero.</exception> public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException(nameof(config)); // prerequisite if (name.IsNullOrWhiteSpace()) { name = "XmlRoleProvider"; } if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "XML Role Provider"); } // initialize the base class base.Initialize(name, config); // initialize provider fields string fileName = config.GetString("fileName", "Roles.xml"); string folder = config.GetString("folder", "~/App_Data/"); if (!folder.EndsWith("/")) folder += "/"; _file = HostingEnvironment.MapPath(string.Format("{0}{1}", folder, fileName)); } #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.Diagnostics; using System.Data.Common; using System.IO; using System.Runtime.Serialization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Runtime.CompilerServices; namespace System.Data.SqlTypes { internal enum SqlBytesCharsState { Null = 0, Buffer = 1, //IntPtr = 2, Stream = 3, } [XmlSchemaProvider("GetXsdType")] public sealed class SqlBytes : INullable, IXmlSerializable, ISerializable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlBytes has five possible states // 1) SqlBytes is Null // - m_stream must be null, m_lCuLen must be x_lNull. // 2) SqlBytes contains a valid buffer, // - m_rgbBuf must not be null,m_stream must be null // 3) SqlBytes contains a valid pointer // - m_rgbBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlBytes contains a Stream // - m_stream must not be null // - m_rgbBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlBytes contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal byte[] _rgbBuf; // Data buffer private long _lCurLen; // Current data length internal Stream _stream; private SqlBytesCharsState _state; private byte[] _rgbWorkBuf; // A 1-byte work buffer. // The max data length that we support at this time. private const long x_lMaxLen = int.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlBytes() { SetNull(); } // Create a SqlBytes with an in-memory buffer public SqlBytes(byte[] buffer) { _rgbBuf = buffer; _stream = null; if (_rgbBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = _rgbBuf.Length; } _rgbWorkBuf = null; AssertValid(); } // Create a SqlBytes from a SqlBinary public SqlBytes(SqlBinary value) : this(value.IsNull ? null : value.Value) { } public SqlBytes(Stream s) { // Create a SqlBytes from a Stream _rgbBuf = null; _lCurLen = x_lNull; _stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgbWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlBytes // Return Buffer even if SqlBytes is Null. public byte[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return _rgbBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return _stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlBytes is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (_rgbBuf == null) ? -1L : _rgbBuf.Length; } } } // Property: get a copy of the data in a new byte[] array. public byte[] Value { get { byte[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (_stream.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new byte[_stream.Length]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(buffer, 0, checked((int)_stream.Length)); break; default: buffer = new byte[_lCurLen]; Array.Copy(_rgbBuf, 0, buffer, 0, (int)_lCurLen); break; } return buffer; } } // class indexer public byte this[long offset] { get { if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (_rgbWorkBuf == null) _rgbWorkBuf = new byte[1]; Read(offset, _rgbWorkBuf, 0, 1); return _rgbWorkBuf[0]; } set { if (_rgbWorkBuf == null) _rgbWorkBuf = new byte[1]; _rgbWorkBuf[0] = value; Write(offset, _rgbWorkBuf, 0, 1); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } public Stream Stream { get { return FStream() ? _stream : new StreamOnSqlBytes(this); } set { _lCurLen = x_lNull; _stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; _stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlBytes is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); if (FStream()) { _stream.SetLength(value); } else { // If there is a buffer, even the value of SqlBytes is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == _rgbBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (value > _rgbBuf.Length) throw new ArgumentOutOfRangeException(nameof(value)); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, byte[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); // Adjust count based on data length if (count > Length - offset) count = (int)(Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: Array.Copy(_rgbBuf, offset, buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlBytes from specified offset public void Write(long offset, byte[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (_rgbBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > _rgbBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); if (count > _rgbBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); } if (count != 0) { Array.Copy(buffer, offsetInBuffer, _rgbBuf, offset, count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlBinary ToSqlBinary() { return IsNull ? SqlBinary.Null : new SqlBinary(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlBinary() public static explicit operator SqlBinary(SqlBytes value) { return value.ToSqlBinary(); } // Alternative method: constructor SqlBytes(SqlBinary) public static explicit operator SqlBytes(SqlBinary value) { return new SqlBytes(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (_rgbBuf != null && _lCurLen <= _rgbBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgbWorkBuf == null || _rgbWorkBuf.Length == 1); } // Copy the data from the Stream to the array buffer. // If the SqlBytes doesn't hold a buffer or the buffer // is not big enough, allocate new byte array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = _stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); if (_rgbBuf == null || _rgbBuf.Length < lStreamLen) _rgbBuf = new byte[lStreamLen]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(_rgbBuf, 0, (int)lStreamLen); _stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } // whether the SqlBytes contains a pointer // whether the SqlBytes contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } private void SetBuffer(byte[] buffer) { _rgbBuf = buffer; _lCurLen = (_rgbBuf == null) ? x_lNull : _rgbBuf.Length; _stream = null; _state = (_rgbBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // XML Serialization // -------------------------------------------------------------- XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { byte[] value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); SetNull(); } else { string base64 = r.ReadElementString(); if (base64 == null) { value = Array.Empty<byte>(); } else { base64 = base64.Trim(); if (base64.Length == 0) value = Array.Empty<byte>(); else value = Convert.FromBase64String(base64); } } SetBuffer(value); } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { byte[] value = Buffer; writer.WriteString(Convert.ToBase64String(value, 0, (int)(Length))); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("base64Binary", XmlSchema.Namespace); } // -------------------------------------------------------------- // Serialization using ISerializable // -------------------------------------------------------------- // State information is not saved. The current state is converted to Buffer and only the underlying // array is serialized, except for Null, in which case this state is kept. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlBytes is mutable, have to be property and create a new one each time. public static SqlBytes Null { get { return new SqlBytes((byte[])null); } } } // class SqlBytes // StreamOnSqlBytes is a stream build on top of SqlBytes, and // provides the Stream interface. The purpose is to help users // to read/write SqlBytes object. After getting the stream from // SqlBytes, users could create a BinaryReader/BinaryWriter object // to easily read and write primitive types. internal sealed class StreamOnSqlBytes : Stream { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlBytes _sb; // the SqlBytes object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal StreamOnSqlBytes(SqlBytes sb) { _sb = sb; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // Always can read/write/seek, unless sb is null, // which means the stream has been closed. public override bool CanRead { get { return _sb != null && !_sb.IsNull; } } public override bool CanSeek { get { return _sb != null; } } public override bool CanWrite { get { return _sb != null && (!_sb.IsNull || _sb._rgbBuf != null); } } public override long Length { get { CheckIfStreamClosed("get_Length"); return _sb.Length; } } public override long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sb.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public override long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sb.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sb.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sb.Length + offset; if (lPosition < 0 || lPosition > _sb.Length) throw new ArgumentOutOfRangeException(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.InvalidSeekOrigin(nameof(offset)); } return _lPosition; } // The Read/Write/ReadByte/WriteByte simply delegates to SqlBytes public override int Read(byte[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); int iBytesRead = (int)_sb.Read(_lPosition, buffer, offset, count); _lPosition += iBytesRead; return iBytesRead; } public override void Write(byte[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); _sb.Write(_lPosition, buffer, offset, count); _lPosition += count; } public override int ReadByte() { CheckIfStreamClosed(); // If at the end of stream, return -1, rather than call SqlBytes.ReadByte, // which will throw exception. This is the behavior for Stream. // if (_lPosition >= _sb.Length) return -1; int ret = _sb[_lPosition]; _lPosition++; return ret; } public override void WriteByte(byte value) { CheckIfStreamClosed(); _sb[_lPosition] = value; _lPosition++; } public override void SetLength(long value) { CheckIfStreamClosed(); _sb.SetLength(value); if (_lPosition > value) _lPosition = value; } // Flush is a no-op for stream on SqlBytes, because they are all in memory public override void Flush() { if (_sb.FStream()) _sb._stream.Flush(); } protected override void Dispose(bool disposing) { // When m_sb is null, it means the stream has been closed, and // any opearation in the future should fail. // This is the only case that m_sb is null. try { _sb = null; } finally { base.Dispose(disposing); } } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sb == null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class StreamOnSqlBytes } // namespace System.Data.SqlTypes
#if FMOD_LIVEUPDATE # define RUN_IN_BACKGROUND #endif using UnityEngine; using System.Collections; using FMOD.Studio; using System.IO; using System; public class FMOD_Listener : MonoBehaviour { public string[] pluginPaths; static FMOD_Listener sListener = null; Rigidbody cachedRigidBody; void OnEnable() { Initialize(); } void OnDisable() { if (sListener == this) sListener = null; } void loadBank(string fileName) { string bankPath = getStreamingAsset(fileName); FMOD.Studio.Bank bank = null; FMOD.RESULT result = FMOD_StudioSystem.instance.System.loadBankFile(bankPath, LOAD_BANK_FLAGS.NORMAL, out bank); if (result == FMOD.RESULT.ERR_VERSION) { FMOD.Studio.UnityUtil.LogError("These banks were built with an incompatible version of FMOD Studio."); } FMOD.Studio.UnityUtil.Log("bank load: " + (bank != null ? "suceeded" : "failed!!")); } string getStreamingAsset(string fileName) { string bankPath = ""; if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.LinuxPlayer #if UNITY_PS4 || Application.platform == RuntimePlatform.PS4 #endif #if UNITY_XBOXONE || Application.platform == RuntimePlatform.XboxOne #endif ) { bankPath = Application.dataPath + "/StreamingAssets"; } else if (Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXDashboardPlayer) { bankPath = Application.dataPath + "/Data/StreamingAssets"; } else if (Application.platform == RuntimePlatform.IPhonePlayer) { bankPath = Application.dataPath + "/Raw"; } else if (Application.platform == RuntimePlatform.Android) { bankPath = "jar:file://" + Application.dataPath + "!/assets"; } #if (UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6) else if (Application.platform == RuntimePlatform.MetroPlayerARM || Application.platform == RuntimePlatform.MetroPlayerX86 || Application.platform == RuntimePlatform.MetroPlayerX64 ) { bankPath = "ms-appx:///Data/StreamingAssets"; } #else // UNITY 5 enum else if (Application.platform == RuntimePlatform.WSAPlayerARM || Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 ) { bankPath = "ms-appx:///Data/StreamingAssets"; } #endif else { FMOD.Studio.UnityUtil.LogError("Unknown platform!"); return ""; } string assetPath = bankPath + "/" + fileName; #if UNITY_ANDROID && !UNITY_EDITOR // Unpack the compressed JAR file string unpackedJarPath = Application.persistentDataPath + "/" + fileName; FMOD.Studio.UnityUtil.Log("Unpacking bank from JAR file into:" + unpackedJarPath); if (File.Exists(unpackedJarPath)) { FMOD.Studio.UnityUtil.Log("File already unpacked!!"); File.Delete(unpackedJarPath); if (File.Exists(unpackedJarPath)) { FMOD.Studio.UnityUtil.Log("Could NOT delete!!"); } } WWW dataStream = new WWW(assetPath); while(!dataStream.isDone) {} // FIXME: not safe if (!String.IsNullOrEmpty(dataStream.error)) { FMOD.Studio.UnityUtil.LogError("### WWW ERROR IN DATA STREAM:" + dataStream.error); } FMOD.Studio.UnityUtil.Log("Android unpacked jar path: " + unpackedJarPath); File.WriteAllBytes(unpackedJarPath, dataStream.bytes); //FileInfo fi = new FileInfo(unpackedJarPath); //FMOD.Studio.UnityUtil.Log("Unpacked bank size = " + fi.Length); assetPath = unpackedJarPath; #endif return assetPath; } #if UNITY_METRO && NETFX_CORE async void Initialize() #else void Initialize() #endif { FMOD.Studio.UnityUtil.Log("Initialize Listener"); if (sListener != null) { FMOD.Studio.UnityUtil.LogError("Too many listeners"); } sListener = this; LoadPlugins(); const string listFileName = "FMOD_bank_list.txt"; string bankListPath = getStreamingAsset(listFileName); FMOD.Studio.UnityUtil.Log("Loading Banks"); try { #if UNITY_METRO && NETFX_CORE var reader = Windows.Storage.PathIO.ReadLinesAsync(bankListPath, Windows.Storage.Streams.UnicodeEncoding.Utf8); await reader.AsTask().ConfigureAwait(true); var bankList = reader.GetResults(); #else var bankList = System.IO.File.ReadAllLines(bankListPath); #endif foreach (var bankName in bankList) { FMOD.Studio.UnityUtil.Log("Load " + bankName); loadBank(bankName); } } catch (Exception e) { FMOD.Studio.UnityUtil.LogError("Cannot read " + bankListPath + ": " + e.Message + " : No banks loaded."); } cachedRigidBody = GetComponent<Rigidbody>(); Update3DAttributes(); } void Start() { #if UNITY_EDITOR && RUN_IN_BACKGROUND Application.runInBackground = true; // Prevent execution pausing when editor loses focus #endif } void Update() { Update3DAttributes(); } void Update3DAttributes() { var sys = FMOD_StudioSystem.instance.System; if (sys != null && sys.isValid()) { var attributes = UnityUtil.to3DAttributes(gameObject, cachedRigidBody); ERRCHECK(sys.setListenerAttributes(attributes)); } } void LoadPlugins() { FMOD.System sys = null; ERRCHECK(FMOD_StudioSystem.instance.System.getLowLevelSystem(out sys)); if (Application.platform == RuntimePlatform.IPhonePlayer && pluginPaths.Length != 0) { FMOD.Studio.UnityUtil.LogError("DSP Plugins not currently supported on iOS, contact support@fmod.org for more information"); return; } foreach (var name in pluginPaths) { var path = pluginPath + "/" + GetPluginFileName(name); FMOD.Studio.UnityUtil.Log("Loading plugin: " + path); #if !UNITY_METRO if (!System.IO.File.Exists(path)) { FMOD.Studio.UnityUtil.LogWarning("plugin not found: " + path); } #endif uint handle; ERRCHECK(sys.loadPlugin(path, out handle)); } } string pluginPath { get { #if UNITY_METRO if (Application.platform == RuntimePlatform.MetroPlayerARM) { return Application.dataPath + "/Plugins/arm"; } else if (Application.platform == RuntimePlatform.MetroPlayerX86) { return Application.dataPath + "/Plugins/x86"; } #else if (Application.platform == RuntimePlatform.WindowsEditor) { return Application.dataPath + "/Plugins/x86"; } else if (Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXDashboardPlayer || Application.platform == RuntimePlatform.LinuxPlayer #if UNITY_PS4 || Application.platform == RuntimePlatform.PS4 #endif #if UNITY_XBOXONE || Application.platform == RuntimePlatform.XboxOne #endif ) { return Application.dataPath + "/Plugins"; } else if (Application.platform == RuntimePlatform.IPhonePlayer) { FMOD.Studio.UnityUtil.LogError("DSP Plugins not currently supported on iOS, contact support@fmod.org for more information"); return ""; } else if (Application.platform == RuntimePlatform.Android) { var dirInfo = new System.IO.DirectoryInfo(Application.persistentDataPath); string packageName = dirInfo.Parent.Name; return "/data/data/" + packageName + "/lib"; } #endif // #if !UNITY_METRO FMOD.Studio.UnityUtil.LogError("Unknown platform!"); return ""; } } string GetPluginFileName(string rawName) { if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer #if UNITY_XBOXONE || Application.platform == RuntimePlatform.XboxOne #endif ) { return rawName + ".dll"; } else if (Application.platform == RuntimePlatform.OSXEditor || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.OSXDashboardPlayer) { return rawName + ".dylib"; } else if (Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.LinuxPlayer) { return "lib" + rawName + ".so"; } #if UNITY_PS4 else if (Application.platform == RuntimePlatform.PS4) { return rawName + ".prx"; } #endif FMOD.Studio.UnityUtil.LogError("Unknown platform!"); return ""; } void ERRCHECK(FMOD.RESULT result) { FMOD.Studio.UnityUtil.ERRCHECK(result); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using JustGestures.Properties; using JustGestures.Features; using JustGestures.Languages; namespace JustGestures.OptionItems { public partial class UC_autoBehaviour : BaseOptionControl { public const string STATE_ENABLED = "enabled"; public const string STATE_DISABLED = "disabled"; public const int AUTO_CHECK_MIN = 100; public const int AUTO_CHECK_MAX = 2000; const string AUTO_1 = "auto1"; const string AUTO_2 = "auto2"; const string FULLSCREEN = "fullscreen"; const string DEFAULT = "default"; List<PrgNamePath> whiteList; List<PrgNamePath> blackList; List<PrgNamePath> finalList; bool onLoad; public override void Translate() { base.Translate(); gB_conditions.Text = Translation.GetText("O_AB_gB_conditions"); lbl_autocheck.Text = Translation.GetText("O_AB_lbl_autocheck"); lbl_defaultState.Text = Translation.GetText("O_AB_lbl_defaultState"); lbl_fullscreenState.Text = Translation.GetText("O_AB_lbl_fullscreenState"); lbl_1AutoState.Text = Translation.GetText("O_AB_lbl_1AutoState"); lbl_2AutoState.Text = Translation.GetText("O_AB_lbl_2AutoState"); gB_finalList.Text = Translation.GetText("O_AB_gB_finalList"); cH_appState.Text = Translation.GetText("O_AB_cH_appState"); cH_name.Text = Translation.GetText("O_AB_cH_name"); cH_path.Text = Translation.GetText("O_AB_cH_path"); cB_default.Items[0] = cB_fullscreen.Items[0] = Translation.GetText("O_AB_cBI_none"); cB_default.Items[1] = cB_fullscreen.Items[1] = Translation.GetText("O_AB_cBI_autoEnable"); cB_default.Items[2] = cB_fullscreen.Items[2] = Translation.GetText("O_AB_cBI_autoDisable"); cB_auto1.Items[0] = cB_auto2.Items[0] = Translation.GetText("O_AB_cBI_none"); cB_auto1.Items[1] = cB_auto2.Items[1] = Translation.GetText("O_AB_whiteList"); cB_auto1.Items[2] = cB_auto2.Items[2] = Translation.GetText("O_AB_blackList"); } public UC_autoBehaviour() { InitializeComponent(); I_infoText = new MyText("O_AB_info"); m_name = new MyText("O_AB_name"); m_caption = new MyText("O_AB_caption"); this.Dock = DockStyle.Fill; onLoad = true; cB_default.Tag = DEFAULT; cB_fullscreen.Tag = FULLSCREEN; cB_auto1.Tag = AUTO_1; cB_auto2.Tag = AUTO_2; cB_default.SelectedIndex = Config.User.StateDefault; cB_fullscreen.SelectedIndex = Config.User.StateFullScreen; cB_auto1.SelectedIndex = Config.User.StateAuto1; cB_auto2.SelectedIndex = Config.User.StateAuto2; nUD_autocheckTime.Value = Math.Min(Math.Max(Config.User.CheckWndLoop, nUD_autocheckTime.Minimum), nUD_autocheckTime.Maximum); onLoad = false; OnEnableApply(false); } public override void SaveSettings() { UpdateFinalList(); Config.User.StateDefault = cB_default.SelectedIndex; Config.User.StateFullScreen = cB_fullscreen.SelectedIndex; Config.User.StateAuto1 = cB_auto1.SelectedIndex; Config.User.StateAuto2 = cB_auto2.SelectedIndex; Config.User.CheckWndLoop = (int)nUD_autocheckTime.Value; } private void comboBox_selectedIndexChanged(object sender, EventArgs e) { if (onLoad) return; OnEnableApply(true); UpdateFinalList(); } private void UpdateFinalList() { lV_programs.Items.Clear(); finalList.Clear(); if (cB_auto1.SelectedIndex != 0 || cB_auto2.SelectedIndex != 0) { lV_programs.Enabled = true; switch (cB_auto1.SelectedIndex) { case 0: switch (cB_auto2.SelectedIndex) { case 0: lV_programs.Enabled = false; break; case 1: AddToFinalList(whiteList, STATE_ENABLED); break; case 2: AddToFinalList(blackList, STATE_DISABLED); break; } break; case 1: switch (cB_auto2.SelectedIndex) { case 0: case 1: AddToFinalList(whiteList, STATE_ENABLED); break; case 2: MergeWhiteBlackList(whiteList, blackList, false); break; } break; case 2: switch (cB_auto2.SelectedIndex) { case 0: case 2: AddToFinalList(blackList, STATE_DISABLED); break; case 1: MergeWhiteBlackList(whiteList, blackList, true); break; } break; } lV_programs.Items.AddRange(finalList.ToArray()); } else { lV_programs.Enabled = false; } } private void AddToFinalList(List<PrgNamePath> list, string state) { foreach (PrgNamePath prog in list) { if (prog.Active) finalList.Add(new PrgNamePath(state, prog.PrgName, prog.Path)); } } private bool ListContainItem(List<PrgNamePath> list, PrgNamePath item) { foreach (PrgNamePath prog in list) if (prog.Active && prog.PrgName == item.PrgName && prog.Path == item.Path) return true; return false; } /// <summary> /// Merge like the first list is White and second is Black /// </summary> /// <param name="list1">list in auto1</param> /// <param name="list2">list in auto2</param> /// <param name="reversed">reverse order of lists</param> private void MergeWhiteBlackList(List<PrgNamePath> list1, List<PrgNamePath> list2, bool reversed) { foreach (PrgNamePath prog in whiteList) { if (prog.Active) { if (ListContainItem(blackList, prog)) { if (reversed) finalList.Add(new PrgNamePath(STATE_ENABLED, prog.PrgName, prog.Path)); else finalList.Add(new PrgNamePath(STATE_DISABLED, prog.PrgName, prog.Path)); } else { finalList.Add(new PrgNamePath(STATE_ENABLED, prog.PrgName, prog.Path)); } } } foreach (PrgNamePath prog in blackList) { if (prog.Active) { if (!ListContainItem(whiteList, prog)) { finalList.Add(new PrgNamePath(STATE_DISABLED, prog.PrgName, prog.Path)); } } } } public List<PrgNamePath> WhiteList { set { whiteList = value; } } public List<PrgNamePath> BlackList { set { blackList = value; } } public List<PrgNamePath> FinalList { get { return finalList; } set { finalList = value; } } private void UC_autoBehaviour_VisibleChanged(object sender, EventArgs e) { if (((UC_autoBehaviour)sender).Visible) UpdateFinalList(); } private void UC_autoBehaviour_Load(object sender, EventArgs e) { lV_programs.Items.Clear(); if (finalList != null) foreach (PrgNamePath item in finalList) lV_programs.Items.Add((ListViewItem)item.Clone()); } private void nUD_autocheckTime_ValueChanged(object sender, EventArgs e) { OnEnableApply(true); } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing a BTreeDatabase. The Btree format is a /// representation of a sorted, balanced tree structure. /// </summary> public class BTreeDatabase : Database { private BTreeCompressDelegate compressHandler; private BTreeDecompressDelegate decompressHandler; private EntryComparisonDelegate compareHandler, dupCompareHandler; private EntryPrefixComparisonDelegate prefixCompareHandler; private BDB_CompareDelegate doCompareRef; private BDB_CompareDelegate doDupCompareRef; private BDB_PrefixCompareDelegate doPrefixCompareRef; private BDB_CompressDelegate doCompressRef; private BDB_DecompressDelegate doDecompressRef; #region Constructors private BTreeDatabase(DatabaseEnvironment env, uint flags) : base(env, flags) { } internal BTreeDatabase(BaseDatabase clone) : base(clone) { } private void Config(BTreeDatabaseConfig cfg) { base.Config(cfg); /* * Database.Config calls set_flags, but that doesn't get the BTree * specific flags. No harm in calling it again. */ db.set_flags(cfg.flags); if (cfg.BTreeCompare != null) Compare = cfg.BTreeCompare; if (cfg.BTreePrefixCompare != null) PrefixCompare = cfg.BTreePrefixCompare; // The duplicate comparison function cannot change. if (cfg.DuplicateCompare != null) DupCompare = cfg.DuplicateCompare; if (cfg.minkeysIsSet) db.set_bt_minkey(cfg.MinKeysPerPage); if (cfg.compressionIsSet) { Compress = cfg.Compress; Decompress = cfg.Decompress; if (Compress == null) doCompressRef = null; else doCompressRef = new BDB_CompressDelegate(doCompress); if (Decompress == null) doDecompressRef = null; else doDecompressRef = new BDB_DecompressDelegate(doDecompress); db.set_bt_compress(doCompressRef, doDecompressRef); } } /// <summary> /// Instantiate a new BTreeDatabase object and open the database /// represented by <paramref name="Filename"/>. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static BTreeDatabase Open( string Filename, BTreeDatabaseConfig cfg) { return Open(Filename, null, cfg, null); } /// <summary> /// Instantiate a new BTreeDatabase object and open the database /// represented by <paramref name="Filename"/> and /// <paramref name="DatabaseName"/>. /// </summary> /// <remarks> /// <para> /// If both <paramref name="Filename"/> and /// <paramref name="DatabaseName"/> are null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. If /// <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <see cref="DatabaseConfig.AutoCommit"/> is set, the operation /// will be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <returns>A new, open database object</returns> public static BTreeDatabase Open( string Filename, string DatabaseName, BTreeDatabaseConfig cfg) { return Open(Filename, DatabaseName, cfg, null); } /// <summary> /// Instantiate a new BTreeDatabase object and open the database /// represented by <paramref name="Filename"/>. /// </summary> /// <remarks> /// <para> /// If <paramref name="Filename"/> is null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. /// </para> /// <para> /// If <paramref name="txn"/> is null, but /// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will /// be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. Also note that the /// transaction must be committed before the object is closed. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static BTreeDatabase Open( string Filename, BTreeDatabaseConfig cfg, Transaction txn) { return Open(Filename, null, cfg, txn); } /// <summary> /// Instantiate a new BTreeDatabase object and open the database /// represented by <paramref name="Filename"/> and /// <paramref name="DatabaseName"/>. /// </summary> /// <remarks> /// <para> /// If both <paramref name="Filename"/> and /// <paramref name="DatabaseName"/> are null, the database is strictly /// temporary and cannot be opened by any other thread of control, thus /// the database can only be accessed by sharing the single database /// object that created it, in circumstances where doing so is safe. If /// <paramref name="Filename"/> is null and /// <paramref name="DatabaseName"/> is non-null, the database can be /// opened by other threads of control and will be replicated to client /// sites in any replication group. /// </para> /// <para> /// If <paramref name="txn"/> is null, but /// <see cref="DatabaseConfig.AutoCommit"/> is set, the operation will /// be implicitly transaction protected. Note that transactionally /// protected operations on a datbase object requires the object itself /// be transactionally protected during its open. Also note that the /// transaction must be committed before the object is closed. /// </para> /// </remarks> /// <param name="Filename"> /// The name of an underlying file that will be used to back the /// database. In-memory databases never intended to be preserved on disk /// may be created by setting this parameter to null. /// </param> /// <param name="DatabaseName"> /// This parameter allows applications to have multiple databases in a /// single file. Although no DatabaseName needs to be specified, it is /// an error to attempt to open a second database in a file that was not /// initially created using a database name. /// </param> /// <param name="cfg">The database's configuration</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>A new, open database object</returns> public static BTreeDatabase Open(string Filename, string DatabaseName, BTreeDatabaseConfig cfg, Transaction txn) { BTreeDatabase ret = new BTreeDatabase(cfg.Env, 0); ret.Config(cfg); ret.db.open(Transaction.getDB_TXN(txn), Filename, DatabaseName, DBTYPE.DB_BTREE, cfg.openFlags, 0); ret.isOpen = true; return ret; } #endregion Constructors #region Callbacks private static int doCompare(IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbtp1, false); DBT dbt2 = new DBT(dbtp2, false); BTreeDatabase btdb = (BTreeDatabase)(db.api_internal); return btdb.Compare( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } private static int doCompress(IntPtr dbp, IntPtr prevKeyp, IntPtr prevDatap, IntPtr keyp, IntPtr datap, IntPtr destp) { DB db = new DB(dbp, false); DatabaseEntry prevKey = DatabaseEntry.fromDBT(new DBT(prevKeyp, false)); DatabaseEntry prevData = DatabaseEntry.fromDBT(new DBT(prevDatap, false)); DatabaseEntry key = DatabaseEntry.fromDBT(new DBT(keyp, false)); DatabaseEntry data = DatabaseEntry.fromDBT(new DBT(datap, false)); DBT dest = new DBT(destp, false); BTreeDatabase btdb = (BTreeDatabase)(db.api_internal); byte[] arr = new byte[(int)dest.ulen]; int len; try { if (btdb.Compress(prevKey, prevData, key, data, ref arr, out len)) { Marshal.Copy(arr, 0, dest.dataPtr, len); dest.size = (uint)len; return 0; } else { return DbConstants.DB_BUFFER_SMALL; } } catch (Exception) { return -1; } } private static int doDecompress(IntPtr dbp, IntPtr prevKeyp, IntPtr prevDatap, IntPtr cmpp, IntPtr destKeyp, IntPtr destDatap) { DB db = new DB(dbp, false); DatabaseEntry prevKey = DatabaseEntry.fromDBT(new DBT(prevKeyp, false)); DatabaseEntry prevData = DatabaseEntry.fromDBT(new DBT(prevDatap, false)); DBT compressed = new DBT(cmpp, false); DBT destKey = new DBT(destKeyp, false); DBT destData = new DBT(destDatap, false); BTreeDatabase btdb = (BTreeDatabase)(db.api_internal); uint size; try { KeyValuePair<DatabaseEntry, DatabaseEntry> kvp = btdb.Decompress(prevKey, prevData, compressed.data, out size); int keylen = kvp.Key.Data.Length; int datalen = kvp.Value.Data.Length; destKey.size = (uint)keylen; destData.size = (uint)datalen; if (keylen > destKey.ulen || datalen > destData.ulen) return DbConstants.DB_BUFFER_SMALL; Marshal.Copy(kvp.Key.Data, 0, destKey.dataPtr, keylen); Marshal.Copy(kvp.Value.Data, 0, destData.dataPtr, datalen); compressed.size = size; return 0; } catch (Exception) { return -1; } } private static int doDupCompare( IntPtr dbp, IntPtr dbt1p, IntPtr dbt2p) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbt1p, false); DBT dbt2 = new DBT(dbt2p, false); BTreeDatabase btdb = (BTreeDatabase)(db.api_internal); return btdb.DupCompare( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } private static uint doPrefixCompare( IntPtr dbp, IntPtr dbtp1, IntPtr dbtp2) { DB db = new DB(dbp, false); DBT dbt1 = new DBT(dbtp1, false); DBT dbt2 = new DBT(dbtp2, false); BTreeDatabase btdb = (BTreeDatabase)(db.api_internal); return btdb.PrefixCompare( DatabaseEntry.fromDBT(dbt1), DatabaseEntry.fromDBT(dbt2)); } #endregion Callbacks #region Properties // Sorted alpha by property name /// <summary> /// The Btree key comparison function. The comparison function is called /// whenever it is necessary to compare a key specified by the /// application with a key currently stored in the tree. /// </summary> public EntryComparisonDelegate Compare { get { return compareHandler; } private set { if (value == null) db.set_bt_compare(null); else if (compareHandler == null) { if (doCompareRef == null) doCompareRef = new BDB_CompareDelegate(doCompare); db.set_bt_compare(doCompareRef); } compareHandler = value; } } /// <summary> /// The compression function used to store key/data pairs in the /// database. /// </summary> public BTreeCompressDelegate Compress { get { return compressHandler; } private set { compressHandler = value; } } /// <summary> /// The decompression function used to retrieve key/data pairs from the /// database. /// </summary> public BTreeDecompressDelegate Decompress { get { return decompressHandler; } private set { decompressHandler = value; } } /// <summary> /// The duplicate data item comparison function. /// </summary> public EntryComparisonDelegate DupCompare { get { return dupCompareHandler; } private set { /* Cannot be called after open. */ if (value == null) db.set_dup_compare(null); else if (dupCompareHandler == null) { if (doDupCompareRef == null) doDupCompareRef = new BDB_CompareDelegate(doDupCompare); db.set_dup_compare(doDupCompareRef); } dupCompareHandler = value; } } /// <summary> /// Whether the insertion of duplicate data items in the database is /// permitted, and whether duplicates items are sorted. /// </summary> public DuplicatesPolicy Duplicates { get { uint flags = 0; db.get_flags(ref flags); if ((flags & DbConstants.DB_DUPSORT) != 0) return DuplicatesPolicy.SORTED; else if ((flags & DbConstants.DB_DUP) != 0) return DuplicatesPolicy.UNSORTED; else return DuplicatesPolicy.NONE; } } /// <summary> /// The minimum number of key/data pairs intended to be stored on any /// single Btree leaf page. /// </summary> public uint MinKeysPerPage { get { uint ret = 0; db.get_bt_minkey(ref ret); return ret; } } /// <summary> /// The Btree prefix function. The prefix function is used to determine /// the amount by which keys stored on the Btree internal pages can be /// safely truncated without losing their uniqueness. /// </summary> public EntryPrefixComparisonDelegate PrefixCompare { get { return prefixCompareHandler; } private set { if (value == null) db.set_bt_prefix(null); else if (prefixCompareHandler == null) { if (doPrefixCompareRef == null) doPrefixCompareRef = new BDB_PrefixCompareDelegate(doPrefixCompare); db.set_bt_prefix(doPrefixCompareRef); } prefixCompareHandler = value; } } /// <summary> /// If true, this object supports retrieval from the Btree using record /// numbers. /// </summary> public bool RecordNumbers { get { uint flags = 0; db.get_flags(ref flags); return (flags & DbConstants.DB_RECNUM) != 0; } } /// <summary> /// If false, empty pages will not be coalesced into higher-level pages. /// </summary> public bool ReverseSplit { get { uint flags = 0; db.get_flags(ref flags); return (flags & DbConstants.DB_REVSPLITOFF) == 0; } } #endregion Properties #region Methods // Sorted alpha by method name /// <summary> /// Compact the database, and optionally return unused database pages to /// the underlying filesystem. /// </summary> /// <remarks> /// If the operation occurs in a transactional database, the operation /// will be implicitly transaction protected using multiple /// transactions. These transactions will be periodically committed to /// avoid locking large sections of the tree. Any deadlocks encountered /// cause the compaction operation to be retried from the point of the /// last transaction commit. /// </remarks> /// <param name="cdata">Compact configuration parameters</param> /// <returns>Compact operation statistics</returns> public CompactData Compact(CompactConfig cdata) { return Compact(cdata, null); } /// <summary> /// Compact the database, and optionally return unused database pages to /// the underlying filesystem. /// </summary> /// <remarks> /// <para> /// If <paramref name="txn"/> is non-null, then the operation is /// performed using that transaction. In this event, large sections of /// the tree may be locked during the course of the transaction. /// </para> /// <para> /// If <paramref name="txn"/> is null, but the operation occurs in a /// transactional database, the operation will be implicitly transaction /// protected using multiple transactions. These transactions will be /// periodically committed to avoid locking large sections of the tree. /// Any deadlocks encountered cause the compaction operation to be /// retried from the point of the last transaction commit. /// </para> /// </remarks> /// <param name="cdata">Compact configuration parameters</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>Compact operation statistics</returns> public CompactData Compact(CompactConfig cdata, Transaction txn) { DatabaseEntry end = null; if (cdata.returnEnd) end = new DatabaseEntry(); db.compact(Transaction.getDB_TXN(txn), cdata.start, cdata.stop, CompactConfig.getDB_COMPACT(cdata), cdata.flags, end); return new CompactData(CompactConfig.getDB_COMPACT(cdata), end); } /// <summary> /// Create a database cursor. /// </summary> /// <returns>A newly created cursor</returns> public new BTreeCursor Cursor() { return Cursor(new CursorConfig(), null); } /// <summary> /// Create a database cursor with the given configuration. /// </summary> /// <param name="cfg"> /// The configuration properties for the cursor. /// </param> /// <returns>A newly created cursor</returns> public new BTreeCursor Cursor(CursorConfig cfg) { return Cursor(cfg, null); } /// <summary> /// Create a transactionally protected database cursor. /// </summary> /// <param name="txn"> /// The transaction context in which the cursor may be used. /// </param> /// <returns>A newly created cursor</returns> public new BTreeCursor Cursor(Transaction txn) { return Cursor(new CursorConfig(), txn); } /// <summary> /// Create a transactionally protected database cursor with the given /// configuration. /// </summary> /// <param name="cfg"> /// The configuration properties for the cursor. /// </param> /// <param name="txn"> /// The transaction context in which the cursor may be used. /// </param> /// <returns>A newly created cursor</returns> public new BTreeCursor Cursor(CursorConfig cfg, Transaction txn) { if (cfg.Priority == CachePriority.DEFAULT) return new BTreeCursor(db.cursor( Transaction.getDB_TXN(txn), cfg.flags), Pagesize); else return new BTreeCursor(db.cursor(Transaction.getDB_TXN(txn), cfg.flags), Pagesize, cfg.Priority); } /// <summary> /// Return the database statistical information which does not require /// traversal of the database. /// </summary> /// <returns> /// The database statistical information which does not require /// traversal of the database. /// </returns> public BTreeStats FastStats() { return Stats(null, true, Isolation.DEGREE_THREE); } /// <summary> /// Return the database statistical information which does not require /// traversal of the database. /// </summary> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns> /// The database statistical information which does not require /// traversal of the database. /// </returns> public BTreeStats FastStats(Transaction txn) { return Stats(txn, true, Isolation.DEGREE_THREE); } /// <summary> /// Return the database statistical information which does not require /// traversal of the database. /// </summary> /// <overloads> /// <para> /// Among other things, this method makes it possible for applications /// to request key and record counts without incurring the performance /// penalty of traversing the entire database. /// </para> /// <para> /// The statistical information is described by the /// <see cref="BTreeStats"/>, <see cref="HashStats"/>, /// <see cref="QueueStats"/>, and <see cref="RecnoStats"/> classes. /// </para> /// </overloads> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <param name="isoDegree"> /// The level of isolation for database reads. /// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for /// databases which did not specify /// <see cref="DatabaseConfig.ReadUncommitted"/>. /// </param> /// <returns> /// The database statistical information which does not require /// traversal of the database. /// </returns> public BTreeStats FastStats(Transaction txn, Isolation isoDegree) { return Stats(txn, true, isoDegree); } /// <summary> /// Retrieve a specific numbered key/data pair from the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key /// parameter is <paramref name="recno"/> and whose Value parameter is the /// retrieved data. /// </returns> public KeyValuePair<DatabaseEntry, DatabaseEntry> Get(uint recno) { return Get(recno, null, null); } /// <summary> /// Retrieve a specific numbered key/data pair from the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <param name="txn"> /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key /// parameter is <paramref name="recno"/> and whose Value parameter is the /// retrieved data. /// </returns> public KeyValuePair<DatabaseEntry, DatabaseEntry> Get( uint recno, Transaction txn) { return Get(recno, txn, null); } /// <summary> /// Retrieve a specific numbered key/data pair from the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <param name="txn"> /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <param name="info">The locking behavior to use.</param> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key /// parameter is <paramref name="recno"/> and whose Value parameter is /// the retrieved data. /// </returns> public KeyValuePair<DatabaseEntry, DatabaseEntry> Get( uint recno, Transaction txn, LockingInfo info) { DatabaseEntry key = new DatabaseEntry(); key.Data = BitConverter.GetBytes(recno); return Get(key, null, txn, info, DbConstants.DB_SET_RECNO); } /// <summary> /// Retrieve a specific numbered key and all duplicate data items from /// the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <exception cref="NotFoundException"> /// A NotFoundException is thrown if <paramref name="recno"/> is not in /// the database. /// </exception> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is /// <paramref name="recno"/> and whose Value parameter is the retrieved /// data items. /// </returns> public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple( uint recno) { return GetMultiple(recno, (int)Pagesize, null, null); } /// <summary> /// Retrieve a specific numbered key and all duplicate data items from /// the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <param name="BufferSize"> /// The initial size of the buffer to fill with duplicate data items. If /// the buffer is not large enough, it will be automatically resized. /// </param> /// <exception cref="NotFoundException"> /// A NotFoundException is thrown if <paramref name="recno"/> is not in /// the database. /// </exception> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is /// <paramref name="recno"/> and whose Value parameter is the retrieved /// data items. /// </returns> public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple( uint recno, int BufferSize) { return GetMultiple(recno, BufferSize, null, null); } /// <summary> /// Retrieve a specific numbered key and all duplicate data items from /// the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <param name="BufferSize"> /// The initial size of the buffer to fill with duplicate data items. If /// the buffer is not large enough, it will be automatically resized. /// </param> /// <param name="txn"> /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <exception cref="NotFoundException"> /// A NotFoundException is thrown if <paramref name="recno"/> is not in /// the database. /// </exception> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is /// <paramref name="recno"/> and whose Value parameter is the retrieved /// data items. /// </returns> public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple( uint recno, int BufferSize, Transaction txn) { return GetMultiple(recno, BufferSize, txn, null); } /// <summary> /// Retrieve a specific numbered key and all duplicate data items from /// the database. /// </summary> /// <param name="recno"> /// The record number of the record to be retrieved. /// </param> /// <param name="BufferSize"> /// The initial size of the buffer to fill with duplicate data items. If /// the buffer is not large enough, it will be automatically resized. /// </param> /// <param name="txn"> /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <param name="info">The locking behavior to use.</param> /// <exception cref="NotFoundException"> /// A NotFoundException is thrown if <paramref name="recno"/> is not in /// the database. /// </exception> /// <returns> /// A <see cref="KeyValuePair{T,T}"/> whose Key parameter is /// <paramref name="recno"/> and whose Value parameter is the retrieved /// data items. /// </returns> public KeyValuePair<DatabaseEntry, MultipleDatabaseEntry> GetMultiple( uint recno, int BufferSize, Transaction txn, LockingInfo info) { KeyValuePair<DatabaseEntry, DatabaseEntry> kvp; DatabaseEntry key = new DatabaseEntry(); key.Data = BitConverter.GetBytes(recno); DatabaseEntry data = new DatabaseEntry(); for (; ; ) { data.UserData = new byte[BufferSize]; try { kvp = Get(key, data, txn, info, DbConstants.DB_MULTIPLE | DbConstants.DB_SET_RECNO); break; } catch (MemoryException) { int sz = (int)data.size; if (sz > BufferSize) BufferSize = sz; else BufferSize *= 2; } } MultipleDatabaseEntry dbe = new MultipleDatabaseEntry(kvp.Value); return new KeyValuePair<DatabaseEntry, MultipleDatabaseEntry>( kvp.Key, dbe); } /// <summary> /// Return an estimate of the proportion of keys that are less than, /// equal to, and greater than the specified key. /// </summary> /// <param name="key">The key to search for</param> /// <returns> /// An estimate of the proportion of keys that are less than, equal to, /// and greater than the specified key. /// </returns> public KeyRange KeyRange(DatabaseEntry key) { return KeyRange(key, null); } /// <summary> /// Return an estimate of the proportion of keys that are less than, /// equal to, and greater than the specified key. /// </summary> /// <param name="key">The key to search for</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns> /// An estimate of the proportion of keys that are less than, equal to, /// and greater than the specified key. /// </returns> public KeyRange KeyRange(DatabaseEntry key, Transaction txn) { DB_KEY_RANGE range = new DB_KEY_RANGE(); db.key_range(Transaction.getDB_TXN(txn), key, range, 0); return new KeyRange(range); } /// <summary> /// Store the key/data pair in the database only if it does not already /// appear in the database. /// </summary> /// <param name="key">The key to store in the database</param> /// <param name="data">The data item to store in the database</param> public void PutNoDuplicate(DatabaseEntry key, DatabaseEntry data) { PutNoDuplicate(key, data, null); } /// <summary> /// Store the key/data pair in the database only if it does not already /// appear in the database. /// </summary> /// <param name="key">The key to store in the database</param> /// <param name="data">The data item to store in the database</param> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> public void PutNoDuplicate( DatabaseEntry key, DatabaseEntry data, Transaction txn) { Put(key, data, txn, DbConstants.DB_NODUPDATA); } /// <summary> /// Return the database statistical information for this database. /// </summary> /// <returns>Database statistical information.</returns> public BTreeStats Stats() { return Stats(null, false, Isolation.DEGREE_THREE); } /// <summary> /// Return the database statistical information for this database. /// </summary> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns>Database statistical information.</returns> public BTreeStats Stats(Transaction txn) { return Stats(txn, false, Isolation.DEGREE_THREE); } /// <summary> /// Return the database statistical information for this database. /// </summary> /// <overloads> /// The statistical information is described by /// <see cref="BTreeStats"/>. /// </overloads> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <param name="isoDegree"> /// The level of isolation for database reads. /// <see cref="Isolation.DEGREE_ONE"/> will be silently ignored for /// databases which did not specify /// <see cref="DatabaseConfig.ReadUncommitted"/>. /// </param> /// <returns>Database statistical information.</returns> public BTreeStats Stats(Transaction txn, Isolation isoDegree) { return Stats(txn, false, isoDegree); } private BTreeStats Stats( Transaction txn, bool fast, Isolation isoDegree) { uint flags = 0; flags |= fast ? DbConstants.DB_FAST_STAT : 0; switch (isoDegree) { case Isolation.DEGREE_ONE: flags |= DbConstants.DB_READ_UNCOMMITTED; break; case Isolation.DEGREE_TWO: flags |= DbConstants.DB_READ_COMMITTED; break; } BTreeStatStruct st = db.stat_bt(Transaction.getDB_TXN(txn), flags); return new BTreeStats(st); } /// <summary> /// Return pages to the filesystem that are already free and at the end /// of the file. /// </summary> /// <returns> /// The number of database pages returned to the filesystem /// </returns> public uint TruncateUnusedPages() { return TruncateUnusedPages(null); } /// <summary> /// Return pages to the filesystem that are already free and at the end /// of the file. /// </summary> /// <param name="txn"> /// If the operation is part of an application-specified transaction, /// <paramref name="txn"/> is a Transaction object returned from /// <see cref="DatabaseEnvironment.BeginTransaction"/>; if /// the operation is part of a Berkeley DB Concurrent Data Store group, /// <paramref name="txn"/> is a handle returned from /// <see cref="DatabaseEnvironment.BeginCDSGroup"/>; otherwise null. /// </param> /// <returns> /// The number of database pages returned to the filesystem /// </returns> public uint TruncateUnusedPages(Transaction txn) { DB_COMPACT cdata = new DB_COMPACT(); db.compact(Transaction.getDB_TXN(txn), null, null, cdata, DbConstants.DB_FREELIST_ONLY, null); return cdata.compact_pages_truncated; } #endregion Methods } }
// // CodeReader.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using ScriptSharp.Importer.IL.PE; using ScriptSharp.Collections.Generic; using RVA = System.UInt32; namespace ScriptSharp.Importer.IL.Cil { sealed class CodeReader : ByteBuffer { readonly internal MetadataReader reader; int start; Section code_section; MethodDefinition method; MethodBody body; int Offset { get { return base.position - start; } } CodeReader (Section section, MetadataReader reader) : base (section.Data) { this.code_section = section; this.reader = reader; } public static CodeReader CreateCodeReader (MetadataReader metadata) { return new CodeReader (metadata.image.MetadataSection, metadata); } public MethodBody ReadMethodBody (MethodDefinition method) { this.method = method; this.body = new MethodBody (method); reader.context = method; ReadMethodBody (); return this.body; } public void MoveTo (int rva) { if (!IsInSection (rva)) { code_section = reader.image.GetSectionAtVirtualAddress ((uint) rva); Reset (code_section.Data); } base.position = rva - (int) code_section.VirtualAddress; } bool IsInSection (int rva) { return code_section.VirtualAddress <= rva && rva < code_section.VirtualAddress + code_section.SizeOfRawData; } void ReadMethodBody () { MoveTo (method.RVA); var flags = ReadByte (); switch (flags & 0x3) { case 0x2: // tiny body.code_size = flags >> 2; body.MaxStackSize = 8; ReadCode (); break; case 0x3: // fat base.position--; ReadFatMethod (); break; default: throw new InvalidOperationException (); } var symbol_reader = reader.module.SymbolReader; if (symbol_reader != null) { var instructions = body.Instructions; symbol_reader.Read (body, offset => GetInstruction (instructions, offset)); } } void ReadFatMethod () { var flags = ReadUInt16 (); body.max_stack_size = ReadUInt16 (); body.code_size = (int) ReadUInt32 (); body.local_var_token = new MetadataToken (ReadUInt32 ()); body.init_locals = (flags & 0x10) != 0; if (body.local_var_token.RID != 0) body.variables = ReadVariables (body.local_var_token); ReadCode (); if ((flags & 0x8) != 0) ReadSection (); } public VariableDefinitionCollection ReadVariables (MetadataToken local_var_token) { var position = reader.position; var variables = reader.ReadVariables (local_var_token); reader.position = position; return variables; } void ReadCode () { start = position; var code_size = body.code_size; if (code_size < 0 || buffer.Length <= (uint) (code_size + position)) code_size = 0; var end = start + code_size; var instructions = body.instructions = new InstructionCollection (code_size / 3); while (position < end) { var offset = base.position - start; var opcode = ReadOpCode (); var current = new Instruction (offset, opcode); if (opcode.OperandType != OperandType.InlineNone) current.operand = ReadOperand (current); instructions.Add (current); } ResolveBranches (instructions); } OpCode ReadOpCode () { var il_opcode = ReadByte (); return il_opcode != 0xfe ? OpCodes.OneByteOpCode [il_opcode] : OpCodes.TwoBytesOpCode [ReadByte ()]; } object ReadOperand (Instruction instruction) { switch (instruction.opcode.OperandType) { case OperandType.InlineSwitch: var length = ReadInt32 (); var base_offset = Offset + (4 * length); var branches = new int [length]; for (int i = 0; i < length; i++) branches [i] = base_offset + ReadInt32 (); return branches; case OperandType.ShortInlineBrTarget: return ReadSByte () + Offset; case OperandType.InlineBrTarget: return ReadInt32 () + Offset; case OperandType.ShortInlineI: if (instruction.opcode == OpCodes.Ldc_I4_S) return ReadSByte (); return ReadByte (); case OperandType.InlineI: return ReadInt32 (); case OperandType.ShortInlineR: return ReadSingle (); case OperandType.InlineR: return ReadDouble (); case OperandType.InlineI8: return ReadInt64 (); case OperandType.ShortInlineVar: return GetVariable (ReadByte ()); case OperandType.InlineVar: return GetVariable (ReadUInt16 ()); case OperandType.ShortInlineArg: return GetParameter (ReadByte ()); case OperandType.InlineArg: return GetParameter (ReadUInt16 ()); case OperandType.InlineSig: return GetCallSite (ReadToken ()); case OperandType.InlineString: return GetString (ReadToken ()); case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: return reader.LookupToken (ReadToken ()); default: throw new NotSupportedException (); } } public string GetString (MetadataToken token) { return reader.image.UserStringHeap.Read (token.RID); } public ParameterDefinition GetParameter (int index) { return body.GetParameter (index); } public VariableDefinition GetVariable (int index) { return body.GetVariable (index); } public CallSite GetCallSite (MetadataToken token) { return reader.ReadCallSite (token); } void ResolveBranches (Collection<Instruction> instructions) { var items = instructions.items; var size = instructions.size; for (int i = 0; i < size; i++) { var instruction = items [i]; switch (instruction.opcode.OperandType) { case OperandType.ShortInlineBrTarget: case OperandType.InlineBrTarget: instruction.operand = GetInstruction ((int) instruction.operand); break; case OperandType.InlineSwitch: var offsets = (int []) instruction.operand; var branches = new Instruction [offsets.Length]; for (int j = 0; j < offsets.Length; j++) branches [j] = GetInstruction (offsets [j]); instruction.operand = branches; break; } } } Instruction GetInstruction (int offset) { return GetInstruction (body.Instructions, offset); } static Instruction GetInstruction (Collection<Instruction> instructions, int offset) { var size = instructions.size; var items = instructions.items; if (offset < 0 || offset > items [size - 1].offset) return null; int min = 0; int max = size - 1; while (min <= max) { int mid = min + ((max - min) / 2); var instruction = items [mid]; var instruction_offset = instruction.offset; if (offset == instruction_offset) return instruction; if (offset < instruction_offset) max = mid - 1; else min = mid + 1; } return null; } void ReadSection () { Align (4); const byte fat_format = 0x40; const byte more_sects = 0x80; var flags = ReadByte (); if ((flags & fat_format) == 0) ReadSmallSection (); else ReadFatSection (); if ((flags & more_sects) != 0) ReadSection (); } void ReadSmallSection () { var count = ReadByte () / 12; Advance (2); ReadExceptionHandlers ( count, () => (int) ReadUInt16 (), () => (int) ReadByte ()); } void ReadFatSection () { position--; var count = (ReadInt32 () >> 8) / 24; ReadExceptionHandlers ( count, ReadInt32, ReadInt32); } // inline ? void ReadExceptionHandlers (int count, Func<int> read_entry, Func<int> read_length) { for (int i = 0; i < count; i++) { var handler = new ExceptionHandler ( (ExceptionHandlerType) (read_entry () & 0x7)); handler.TryStart = GetInstruction (read_entry ()); handler.TryEnd = GetInstruction (handler.TryStart.Offset + read_length ()); handler.HandlerStart = GetInstruction (read_entry ()); handler.HandlerEnd = GetInstruction (handler.HandlerStart.Offset + read_length ()); ReadExceptionHandlerSpecific (handler); this.body.ExceptionHandlers.Add (handler); } } void ReadExceptionHandlerSpecific (ExceptionHandler handler) { switch (handler.HandlerType) { case ExceptionHandlerType.Catch: handler.CatchType = (TypeReference) reader.LookupToken (ReadToken ()); break; case ExceptionHandlerType.Filter: handler.FilterStart = GetInstruction (ReadInt32 ()); break; default: Advance (4); break; } } void Align (int align) { align--; Advance (((position + align) & ~align) - position); } public MetadataToken ReadToken () { return new MetadataToken (ReadUInt32 ()); } #if !IL_READ_ONLY public ByteBuffer PatchRawMethodBody (MethodDefinition method, CodeWriter writer, out MethodSymbols symbols) { var buffer = new ByteBuffer (); symbols = new MethodSymbols (method.Name); this.method = method; reader.context = method; MoveTo (method.RVA); var flags = ReadByte (); MetadataToken local_var_token; switch (flags & 0x3) { case 0x2: // tiny buffer.WriteByte (flags); local_var_token = MetadataToken.Zero; symbols.code_size = flags >> 2; PatchRawCode (buffer, symbols.code_size, writer); break; case 0x3: // fat base.position--; PatchRawFatMethod (buffer, symbols, writer, out local_var_token); break; default: throw new NotSupportedException (); } var symbol_reader = reader.module.SymbolReader; if (symbol_reader != null && writer.metadata.write_symbols) { symbols.method_token = GetOriginalToken (writer.metadata, method); symbols.local_var_token = local_var_token; symbol_reader.Read (symbols); } return buffer; } void PatchRawFatMethod (ByteBuffer buffer, MethodSymbols symbols, CodeWriter writer, out MetadataToken local_var_token) { var flags = ReadUInt16 (); buffer.WriteUInt16 (flags); buffer.WriteUInt16 (ReadUInt16 ()); symbols.code_size = ReadInt32 (); buffer.WriteInt32 (symbols.code_size); local_var_token = ReadToken (); if (local_var_token.RID > 0) { var variables = symbols.variables = ReadVariables (local_var_token); buffer.WriteUInt32 (variables != null ? writer.GetStandAloneSignature (symbols.variables).ToUInt32 () : 0); } else buffer.WriteUInt32 (0); PatchRawCode (buffer, symbols.code_size, writer); if ((flags & 0x8) != 0) PatchRawSection (buffer, writer.metadata); } static MetadataToken GetOriginalToken (MetadataBuilder metadata, MethodDefinition method) { MetadataToken original; if (metadata.TryGetOriginalMethodToken (method.token, out original)) return original; return MetadataToken.Zero; } void PatchRawCode (ByteBuffer buffer, int code_size, CodeWriter writer) { var metadata = writer.metadata; buffer.WriteBytes (ReadBytes (code_size)); var end = buffer.position; buffer.position -= code_size; while (buffer.position < end) { OpCode opcode; var il_opcode = buffer.ReadByte (); if (il_opcode != 0xfe) { opcode = OpCodes.OneByteOpCode [il_opcode]; } else { var il_opcode2 = buffer.ReadByte (); opcode = OpCodes.TwoBytesOpCode [il_opcode2]; } switch (opcode.OperandType) { case OperandType.ShortInlineI: case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineVar: case OperandType.ShortInlineArg: buffer.position += 1; break; case OperandType.InlineVar: case OperandType.InlineArg: buffer.position += 2; break; case OperandType.InlineBrTarget: case OperandType.ShortInlineR: case OperandType.InlineI: buffer.position += 4; break; case OperandType.InlineI8: case OperandType.InlineR: buffer.position += 8; break; case OperandType.InlineSwitch: var length = buffer.ReadInt32 (); buffer.position += length * 4; break; case OperandType.InlineString: var @string = GetString (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 ( new MetadataToken ( TokenType.String, metadata.user_string_heap.GetStringIndex (@string)).ToUInt32 ()); break; case OperandType.InlineSig: var call_site = GetCallSite (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 (writer.GetStandAloneSignature (call_site).ToUInt32 ()); break; case OperandType.InlineTok: case OperandType.InlineType: case OperandType.InlineMethod: case OperandType.InlineField: var provider = reader.LookupToken (new MetadataToken (buffer.ReadUInt32 ())); buffer.position -= 4; buffer.WriteUInt32 (metadata.LookupToken (provider).ToUInt32 ()); break; } } } void PatchRawSection (ByteBuffer buffer, MetadataBuilder metadata) { var position = base.position; Align (4); buffer.WriteBytes (base.position - position); const byte fat_format = 0x40; const byte more_sects = 0x80; var flags = ReadByte (); if ((flags & fat_format) == 0) { buffer.WriteByte (flags); PatchRawSmallSection (buffer, metadata); } else PatchRawFatSection (buffer, metadata); if ((flags & more_sects) != 0) PatchRawSection (buffer, metadata); } void PatchRawSmallSection (ByteBuffer buffer, MetadataBuilder metadata) { var length = ReadByte (); buffer.WriteByte (length); Advance (2); buffer.WriteUInt16 (0); var count = length / 12; PatchRawExceptionHandlers (buffer, metadata, count, false); } void PatchRawFatSection (ByteBuffer buffer, MetadataBuilder metadata) { position--; var length = ReadInt32 (); buffer.WriteInt32 (length); var count = (length >> 8) / 24; PatchRawExceptionHandlers (buffer, metadata, count, true); } void PatchRawExceptionHandlers (ByteBuffer buffer, MetadataBuilder metadata, int count, bool fat_entry) { const int fat_entry_size = 16; const int small_entry_size = 6; for (int i = 0; i < count; i++) { ExceptionHandlerType handler_type; if (fat_entry) { var type = ReadUInt32 (); handler_type = (ExceptionHandlerType) (type & 0x7); buffer.WriteUInt32 (type); } else { var type = ReadUInt16 (); handler_type = (ExceptionHandlerType) (type & 0x7); buffer.WriteUInt16 (type); } buffer.WriteBytes (ReadBytes (fat_entry ? fat_entry_size : small_entry_size)); switch (handler_type) { case ExceptionHandlerType.Catch: var exception = reader.LookupToken (ReadToken ()); buffer.WriteUInt32 (metadata.LookupToken (exception).ToUInt32 ()); break; default: buffer.WriteUInt32 (ReadUInt32 ()); break; } } } #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.IO; #if NETFX_CORE using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using SetUp = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestInitializeAttribute; using TearDown = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestCleanupAttribute; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #else using NUnit.Framework; #endif namespace SQLite.Tests { [TestFixture, NUnit.Framework.Ignore("Fails to run on .NET Core 3.1 Mac")] public class ConcurrencyTest { public class TestObj { [AutoIncrement, PrimaryKey] public int Id { get; set; } public override string ToString() { return string.Format("[TestObj: Id={0}]", Id); } } public class DbReader { private CancellationToken cancellationToken; public DbReader(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } public Task Run() { var t = Task.Run(() => { try { while (true) { // // NOTE: Change this to readwrite and then it does work ??? // No more IOERROR // var flags = SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadOnly; #if __IOS__ flags = SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite; #endif using (var dbConnection = new DbConnection(flags)) { var records = dbConnection.Table<TestObj>().ToList(); System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Read records: {records.Count}"); } // No await so we stay on the same thread Task.Delay(10).GetAwaiter().GetResult(); cancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { } }); return t; } } public class DbWriter { private CancellationToken cancellationToken; public DbWriter(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } public Task Run() { var t = Task.Run(() => { try { while (true) { using (var dbConnection = new DbConnection(SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite)) { System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Start insert"); for (var i = 0; i < 50; i++) { var newRecord = new TestObj() { }; dbConnection.Insert(newRecord); } System.Diagnostics.Debug.WriteLine($"{Environment.CurrentManagedThreadId} Inserted records"); } // No await so we stay on the same thread Task.Delay(1).GetAwaiter().GetResult(); cancellationToken.ThrowIfCancellationRequested(); } } catch (OperationCanceledException) { } }); return t; } } public class DbConnection : SQLiteConnection { private static string DbPath = GetTempFileName(); private static string GetTempFileName() { #if NETFX_CORE var name = Guid.NewGuid() + ".sqlite"; return Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, name); #else return Path.GetTempFileName(); #endif } public DbConnection(SQLiteOpenFlags openflags) : base(DbPath, openflags) { this.BusyTimeout = TimeSpan.FromSeconds(5); } public void CreateTables() { CreateTable<TestObj>(); } } [SetUp] public void Setup() { using (var dbConenction = new DbConnection(SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create)) { dbConenction.CreateTables(); } } [Test] public void TestLoad() { try { //var result = SQLitePCL.raw.sqlite3_threadsafe(); //Assert.AreEqual(2, result); // Yes it's threadsafe on iOS var tokenSource = new CancellationTokenSource(); var tasks = new List<Task>(); tasks.Add(new DbReader(tokenSource.Token).Run()); tasks.Add(new DbWriter(tokenSource.Token).Run()); // Wait 5sec tokenSource.CancelAfter(5000); Task.WhenAll(tasks).GetAwaiter().GetResult(); } catch (Exception ex) { Assert.Fail(ex.ToString()); } } /// <summary> /// Test for issue #761. Because the nature of this test is a race condition, /// it is not guaranteed to fail if the issue is present. It does appear to /// fail most of the time, though. /// </summary> [Test] public void TestInsertCommandCreation () { using (var dbConnection = new DbConnection (SQLiteOpenFlags.FullMutex | SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create)) { var obj1 = new TestObj (); var obj2 = new TestObj (); var taskA = Task.Run (() => { dbConnection.Insert (obj1); }); var taskB = Task.Run (() => { dbConnection.Insert (obj2); }); Task.WhenAll (taskA, taskB).Wait (); } } } }
using System; using System.Linq; using System.Threading.Tasks; using DioLive.Cache.WebUI.Data; using DioLive.Cache.WebUI.Models; using DioLive.Cache.WebUI.Models.BudgetSharingViewModels; using DioLive.Cache.WebUI.Models.BudgetViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace DioLive.Cache.WebUI.Controllers { [Authorize] public class BudgetsController : Controller { private const string Bind_Create = nameof(CreateBudgetVM.Name); private const string Bind_Manage = nameof(ManageBudgetVM.Id) + "," + nameof(ManageBudgetVM.Name); private readonly ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; public BudgetsController(ApplicationDbContext context, UserManager<ApplicationUser> userManager) { _context = context; _userManager = userManager; } public async Task<IActionResult> Choose(Guid id) { var budget = await Get(id); if (budget == null) { return NotFound(); } if (!HasRights(budget, ShareAccess.ReadOnly)) { return Forbid(); } if (budget.Version == 1) { MigrationHelper.MigrateBudget(id, _context); } HttpContext.Session.SetGuid(nameof(SessionKeys.CurrentBudget), id); return RedirectToAction(nameof(PurchasesController.Index), "Purchases"); } // GET: Budgets/Create public IActionResult Create() { return View(); } // POST: Budgets/Create [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind(Bind_Create)] CreateBudgetVM model) { if (ModelState.IsValid) { var currentUserId = _userManager.GetUserId(User); Budget budget = new Budget { Name = model.Name, Id = Guid.NewGuid(), AuthorId = currentUserId, Version = 2, }; foreach (var c in _context.Category.Include(c => c.Localizations).Where(c => c.OwnerId == null).AsNoTracking().ToList()) { c.Id = default(int); c.OwnerId = currentUserId; foreach (var item in c.Localizations) { item.CategoryId = default(int); } budget.Categories.Add(c); } _context.Add(budget); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Choose), new { budget.Id }); } return View(model); } // GET: Budgets/Edit/5 public async Task<IActionResult> Manage(Guid? id) { if (!id.HasValue) { return NotFound(); } var budget = await Get(id.Value); if (budget == null) { return NotFound(); } if (!HasRights(budget, ShareAccess.Manage)) { return Forbid(); } ManageBudgetVM model = new ManageBudgetVM { Id = budget.Id, Name = budget.Name, }; return View(model); } // POST: Budgets/Edit/5 [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Manage(Guid id, [Bind(Bind_Manage)] ManageBudgetVM model) { if (id != model.Id) { return NotFound(); } Budget budget = await Get(id); if (budget == null) { return NotFound(); } if (!HasRights(budget, ShareAccess.Manage)) { return Forbid(); } if (ModelState.IsValid) { budget.Name = model.Name; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!BudgetExists(budget.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(HomeController.Index), "Home"); } return View(model); } // GET: Budgets/Delete/5 public async Task<IActionResult> Delete(Guid? id) { if (!id.HasValue) { return NotFound(); } var budget = await Get(id.Value); if (budget == null) { return NotFound(); } if (!HasRights(budget, ShareAccess.Delete)) { return Forbid(); } return View(budget); } // POST: Budgets/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(Guid id) { var budget = await Get(id); if (budget == null) { return NotFound(); } if (!HasRights(budget, ShareAccess.Delete)) { return Forbid(); } _context.Budget.Remove(budget); await _context.SaveChangesAsync(); return RedirectToAction(nameof(HomeController.Index), "Home"); } [HttpPost] public async Task<IActionResult> Share(NewShareVM model) { var budget = await Get(model.BudgetId); if (budget == null) { return NotFound("Budget not found"); } if (!HasRights(budget, ShareAccess.Manage)) { return Forbid(); } var user = await _context.Users.SingleOrDefaultAsync(u => u.NormalizedUserName == model.UserName.ToUpperInvariant()); if (user == null) { return NotFound("User not found"); } Share share = budget.Shares.SingleOrDefault(s => s.UserId == user.Id); if (share != null) { share.Access = model.Access; } else { budget.Shares.Add(new Share { UserId = user.Id, Access = model.Access }); } await _context.SaveChangesAsync(); return RedirectToAction(nameof(Manage), new { id = model.BudgetId }); } private bool BudgetExists(Guid id) { return _context.Budget.Any(e => e.Id == id); } private Task<Budget> Get(Guid id) { return Budget.GetWithShares(_context, id); } private bool HasRights(Budget budget, ShareAccess requiredAccess) { var userId = _userManager.GetUserId(User); return budget.HasRights(userId, requiredAccess); } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using directives #define USE_TRACING using System; using System.Xml; using System.IO; #endregion // <summary>basenametable, holds common names for atom&rss parsing</summary> namespace Google.GData.Client { /// <summary>BaseNameTable. An initialized nametable for faster XML processing /// parses: /// * opensearch:totalResults - the total number of search results available (not necessarily all present in the feed). /// * opensearch:startIndex - the 1-based index of the first result. /// * opensearch:itemsPerPage - the maximum number of items that appear on one page. This allows clients to generate direct links to any set of subsequent pages. /// * gData:processed /// </summary> public class BaseNameTable { /// <summary>the nametable itself, based on XML core</summary> private NameTable atomNameTable; /// <summary>opensearch:totalResults</summary> private object totalResults; /// <summary>opensearch:startIndex</summary> private object startIndex; /// <summary>opensearch:itemsPerPage</summary> private object itemsPerPage; /// <summary>xml base</summary> private object baseUri; /// <summary>xml language</summary> private object language; // batch extensions private object batchId; private object batchStatus; private object batchOperation; private object batchInterrupt; private object batchContentType; private object batchStatusCode; private object batchReason; private object batchErrors; private object batchError; private object batchSuccessCount; private object batchFailureCount; private object batchParsedCount; private object batchField; private object batchUnprocessed; private object type; private object value; private object name; private object eTagAttribute; /// <summary> /// namespace of the opensearch v1.0 elements /// </summary> public const string NSOpenSearchRss = "http://a9.com/-/spec/opensearchrss/1.0/"; /// <summary> /// namespace of the opensearch v1.1 elements /// </summary> public const string NSOpenSearch11 = "http://a9.com/-/spec/opensearch/1.1/"; /// <summary>static namespace string declaration</summary> public const string NSAtom = "http://www.w3.org/2005/Atom"; /// <summary>namespace for app publishing control, draft version</summary> public const string NSAppPublishing = "http://purl.org/atom/app#"; /// <summary>namespace for app publishing control, final version</summary> public const string NSAppPublishingFinal = "http://www.w3.org/2007/app"; /// <summary>xml namespace</summary> public const string NSXml = "http://www.w3.org/XML/1998/namespace"; /// <summary>GD namespace</summary> public const string gNamespace = "http://schemas.google.com/g/2005"; /// <summary>GData batch extension namespace</summary> public const string gBatchNamespace = "http://schemas.google.com/gdata/batch"; /// <summary>GD namespace prefix</summary> public const string gNamespacePrefix = gNamespace + "#"; /// <summary>the post definiton in the link collection</summary> public const string ServicePost = gNamespacePrefix + "post"; /// <summary>the feed definition in the link collection</summary> public const string ServiceFeed = gNamespacePrefix + "feed"; /// <summary>the batch URI definition in the link collection</summary> public const string ServiceBatch = gNamespacePrefix + "batch"; /// <summary>GData Kind Scheme</summary> public const string gKind = gNamespacePrefix + "kind"; /// <summary>label scheme</summary> public const string gLabels = gNamespace + "/labels"; /// <summary>the edit definition in the link collection</summary> public const string ServiceEdit = "edit"; /// <summary>the next chunk URI in the link collection</summary> public const string ServiceNext = "next"; /// <summary>the previous chunk URI in the link collection</summary> public const string ServicePrev = "previous"; /// <summary>the self URI in the link collection</summary> public const string ServiceSelf = "self"; /// <summary>the alternate URI in the link collection</summary> public const string ServiceAlternate = "alternate"; /// <summary>the alternate URI in the link collection</summary> public const string ServiceMedia = "edit-media"; /// <summary>prefix for atom if writing</summary> public const string AtomPrefix = "atom"; /// <summary>prefix for gNamespace if writing</summary> public const string gDataPrefix = "gd"; /// <summary>prefix for gdata:batch if writing</summary> public const string gBatchPrefix = "batch"; /// <summary>prefix for gd:errors</summary> public const string gdErrors = "errors"; /// <summary>prefix for gd:error</summary> public const string gdError = "error"; /// <summary>prefix for gd:domain</summary> public const string gdDomain = "domain"; /// <summary>prefix for gd:code</summary> public const string gdCode = "code"; /// <summary>prefix for gd:location</summary> public const string gdLocation = "location"; /// <summary>prefix for gd:internalReason</summary> public const string gdInternalReason = "internalReason"; // app publishing control strings /// <summary>prefix for appPublishing if writing</summary> public const string gAppPublishingPrefix = "app"; /// <summary>xmlelement for app:control</summary> public const string XmlElementPubControl = "control"; /// <summary>xmlelement for app:draft</summary> public const string XmlElementPubDraft = "draft"; /// <summary>xmlelement for app:draft</summary> public const string XmlElementPubEdited = "edited"; /// <summary> /// static string for parsing the etag attribute /// </summary> /// <returns></returns> public const string XmlEtagAttribute = "etag"; // batch strings: /// <summary>xmlelement for batch:id</summary> public const string XmlElementBatchId = "id"; /// <summary>xmlelement for batch:operation</summary> public const string XmlElementBatchOperation = "operation"; /// <summary>xmlelement for batch:status</summary> public const string XmlElementBatchStatus = "status"; /// <summary>xmlelement for batch:interrupted</summary> public const string XmlElementBatchInterrupt = "interrupted"; /// <summary>xmlattribute for batch:status@contentType</summary> public const string XmlAttributeBatchContentType = "content-type"; /// <summary>xmlattribute for batch:status@code</summary> public const string XmlAttributeBatchStatusCode = "code"; /// <summary>xmlattribute for batch:status@reason</summary> public const string XmlAttributeBatchReason = "reason"; /// <summary>xmlelement for batch:status:errors</summary> public const string XmlElementBatchErrors = "errors"; /// <summary>xmlelement for batch:status:errors:error</summary> public const string XmlElementBatchError = "error"; /// <summary>xmlattribute for batch:interrupted@success</summary> public const string XmlAttributeBatchSuccess = "success"; /// <summary>XmlAttribute for batch:interrupted@parsed</summary> public const string XmlAttributeBatchParsed = "parsed"; /// <summary>XmlAttribute for batch:interrupted@field</summary> public const string XmlAttributeBatchField = "field"; /// <summary>XmlAttribute for batch:interrupted@unprocessed</summary> public const string XmlAttributeBatchUnprocessed = "unprocessed"; /// <summary>XmlConstant for value in enums</summary> public const string XmlValue = "value"; /// <summary>XmlConstant for name in enums</summary> public const string XmlName = "name"; /// <summary>XmlAttribute for type in enums</summary> public const string XmlAttributeType = "type"; /// <summary>XmlAttribute for key in enums</summary> public const string XmlAttributeKey = "key"; /// <summary>initializes the name table for use with atom parsing. This is the /// only place where strings are defined for parsing</summary> public virtual void InitAtomParserNameTable() { // create the nametable object Tracing.TraceCall("Initializing basenametable support"); this.atomNameTable = new NameTable(); // <summary>add the keywords for the Feed this.totalResults = this.atomNameTable.Add("totalResults"); this.startIndex = this.atomNameTable.Add("startIndex"); this.itemsPerPage = this.atomNameTable.Add("itemsPerPage"); this.baseUri = this.atomNameTable.Add("base"); this.language = this.atomNameTable.Add("lang"); // batch keywords this.batchId = this.atomNameTable.Add(BaseNameTable.XmlElementBatchId); this.batchOperation = this.atomNameTable.Add(BaseNameTable.XmlElementBatchOperation); this.batchStatus = this.atomNameTable.Add(BaseNameTable.XmlElementBatchStatus); this.batchInterrupt = this.atomNameTable.Add(BaseNameTable.XmlElementBatchInterrupt); this.batchContentType = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchContentType); this.batchStatusCode = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchStatusCode); this.batchReason = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchReason); this.batchErrors = this.atomNameTable.Add(BaseNameTable.XmlElementBatchErrors); this.batchError = this.atomNameTable.Add(BaseNameTable.XmlElementBatchError); this.batchSuccessCount = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchSuccess); this.batchFailureCount = this.batchError; this.batchParsedCount = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchParsed); this.batchField = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchField); this.batchUnprocessed = this.atomNameTable.Add(BaseNameTable.XmlAttributeBatchUnprocessed); this.type = this.atomNameTable.Add(BaseNameTable.XmlAttributeType); this.value = this.atomNameTable.Add(BaseNameTable.XmlValue); this.name = this.atomNameTable.Add(BaseNameTable.XmlName); this.eTagAttribute = this.atomNameTable.Add(BaseNameTable.XmlEtagAttribute); } #region Read only accessors 8/10/2005 /// <summary>Read only accessor for atomNameTable</summary> internal NameTable Nametable { get { return this.atomNameTable; } } /// <summary>Read only accessor for BatchId</summary> public object BatchId { get { return this.batchId; } } /// <summary>Read only accessor for BatchOperation</summary> public object BatchOperation { get { return this.batchOperation; } } /// <summary>Read only accessor for BatchStatus</summary> public object BatchStatus { get { return this.batchStatus; } } /// <summary>Read only accessor for BatchInterrupt</summary> public object BatchInterrupt { get { return this.batchInterrupt; } } /// <summary>Read only accessor for BatchContentType</summary> public object BatchContentType { get { return this.batchContentType; } } /// <summary>Read only accessor for BatchStatusCode</summary> public object BatchStatusCode { get { return this.batchStatusCode; } } /// <summary>Read only accessor for BatchErrors</summary> public object BatchErrors { get { return this.batchErrors; } } /// <summary>Read only accessor for BatchError</summary> public object BatchError { get { return this.batchError; } } /// <summary>Read only accessor for BatchReason</summary> public object BatchReason { get { return this.batchReason; } } /// <summary>Read only accessor for BatchReason</summary> public object BatchField { get { return this.batchField; } } /// <summary>Read only accessor for BatchUnprocessed</summary> public object BatchUnprocessed { get { return this.batchUnprocessed; } } /// <summary>Read only accessor for BatchSuccessCount</summary> public object BatchSuccessCount { get { return this.batchSuccessCount; } } /// <summary>Read only accessor for BatchFailureCount</summary> public object BatchFailureCount { get { return this.batchFailureCount; } } /// <summary>Read only accessor for BatchParsedCount</summary> public object BatchParsedCount { get { return this.batchParsedCount; } } /// <summary>Read only accessor for totalResults</summary> public object TotalResults { get { return this.totalResults; } } /// <summary>Read only accessor for startIndex</summary> public object StartIndex { get { return this.startIndex; } } /// <summary>Read only accessor for itemsPerPage</summary> public object ItemsPerPage { get { return this.itemsPerPage; } } /// <summary>Read only accessor for parameter</summary> static public string Parameter { get { return "parameter"; } } /// <summary>Read only accessor for baseUri</summary> public object Base { get { return this.baseUri; } } /// <summary>Read only accessor for language</summary> public object Language { get { return this.language; } } /// <summary>Read only accessor for value</summary> public object Value { get { return this.value; } } /// <summary>Read only accessor for value</summary> public object Type { get { return this.type; } } /// <summary>Read only accessor for name</summary> public object Name { get { return this.name; } } /// <summary>Read only accessor for etag</summary> public object ETag { get { return this.eTagAttribute; } } #endregion end of Read only accessors /// <summary> /// returns the correct opensearchnamespace to use based /// on the version information passed in. All protocols with /// version > 1 use opensearch1.1 where version 1 uses /// opensearch 1.0 /// </summary> /// <param name="v">The versioninformation</param> /// <returns></returns> public static string OpenSearchNamespace(IVersionAware v) { int major = VersionDefaults.Major; if (v != null) { major = v.ProtocolMajor; } if (major == 1) { return BaseNameTable.NSOpenSearchRss; } return BaseNameTable.NSOpenSearch11; } /// <summary> /// returns the correct app:publishing namespace to use based /// on the version information passed in. All protocols with /// version > 1 use the final version of the namespace, where /// version 1 uses the draft version. /// </summary> /// <param name="v">The versioninformation</param> /// <returns></returns> public static string AppPublishingNamespace(IVersionAware v) { int major = VersionDefaults.Major; if (v != null) { major = v.ProtocolMajor; } if (major == 1) { return BaseNameTable.NSAppPublishing; } return BaseNameTable.NSAppPublishingFinal; } } }
//------------------------------------------------------------------------------ // <copyright file="ButtonBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms.ButtonInternal { using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms.Internal; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Drawing.Text; using System.Windows.Forms; using System.Windows.Forms.Layout; using System.Windows.Forms.VisualStyles; using System.Runtime.InteropServices; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; internal class ButtonStandardAdapter : ButtonBaseAdapter { private const int borderWidth = 2; internal ButtonStandardAdapter(ButtonBase control) : base(control) {} private PushButtonState DetermineState(bool up) { PushButtonState state = PushButtonState.Normal; if (!up) { state = PushButtonState.Pressed; } else if (Control.MouseIsOver) { state = PushButtonState.Hot; } else if (!Control.Enabled) { state = PushButtonState.Disabled; } else if (Control.Focused || Control.IsDefault) { state = PushButtonState.Default; } return state; } internal override void PaintUp(PaintEventArgs e, CheckState state) { PaintWorker(e, true, state); } internal override void PaintDown(PaintEventArgs e, CheckState state) { PaintWorker(e, false, state); } internal override void PaintOver(PaintEventArgs e, CheckState state) { PaintUp(e, state); } private void PaintThemedButtonBackground(PaintEventArgs e, Rectangle bounds, bool up) { PushButtonState pbState = DetermineState(up); // First handle transparent case if (ButtonRenderer.IsBackgroundPartiallyTransparent(pbState)) { ButtonRenderer.DrawParentBackground(e.Graphics, bounds, Control); } // Now draw the actual themed background ButtonRenderer.DrawButton(e.Graphics, Control.ClientRectangle, false, pbState); // Now overlay the background image or backcolor (the former overrides the latter), leaving a // margin. We hardcode this margin for now since GetThemeMargins returns 0 all the // time. //HACK We need to see what's best here. changing this to HACK because GetThemeMargins simply does not // work in some cases. bounds.Inflate(-buttonBorderSize, -buttonBorderSize); //only paint if the user said not to use the themed backcolor. if (!Control.UseVisualStyleBackColor) { bool painted = false; Color color = Control.BackColor; // Note: PaintEvent.HDC == 0 if GDI+ has used the HDC -- it wouldn't be safe for us // to use it without enough bookkeeping to negate any performance gain of using GDI. if (color.A == 255 && e.HDC != IntPtr.Zero) { if (DisplayInformation.BitsPerPixel > 8) { NativeMethods.RECT r = new NativeMethods.RECT(bounds.X, bounds.Y, bounds.Right, bounds.Bottom); SafeNativeMethods.FillRect(new HandleRef(e, e.HDC), ref r, new HandleRef(this, Control.BackColorBrush)); painted = true; } } if (!painted) { // don't paint anything from 100% transparent background // if (color.A > 0) { if (color.A == 255) { color = e.Graphics.GetNearestColor(color); } // Color has some transparency or we have no HDC, so we must // fall back to using GDI+. // using (Brush brush = new SolidBrush(color)) { e.Graphics.FillRectangle(brush, bounds); } } } } //This code is mostly taken from the non-themed rendering code path. if (Control.BackgroundImage != null && !DisplayInformation.HighContrast) { ControlPaint.DrawBackgroundImage(e.Graphics, Control.BackgroundImage, Color.Transparent, Control.BackgroundImageLayout, Control.ClientRectangle, bounds, Control.DisplayRectangle.Location, Control.RightToLeft); } } void PaintWorker(PaintEventArgs e, bool up, CheckState state) { up = up && state == CheckState.Unchecked; ColorData colors = PaintRender(e.Graphics).Calculate(); LayoutData layout; if (Application.RenderWithVisualStyles) { //don't have the text-pressed-down effect when we use themed painting //this is for consistency with win32 app. layout = PaintLayout(e, true).Layout(); } else { layout = PaintLayout(e, up).Layout(); } Graphics g = e.Graphics; Button thisbutton = this.Control as Button; if (Application.RenderWithVisualStyles) { PaintThemedButtonBackground(e, Control.ClientRectangle, up); } else { Brush backbrush = null; if (state == CheckState.Indeterminate) { backbrush = CreateDitherBrush(colors.highlight, colors.buttonFace); } try { Rectangle bounds = Control.ClientRectangle; if (up) { // We are going to draw a 2 pixel border bounds.Inflate(-borderWidth, -borderWidth); // VS Whidbey #459900 } else { // We are going to draw a 1 pixel border. bounds.Inflate(-1, -1); // VS Whidbey #503487 } PaintButtonBackground(e, bounds, backbrush); } finally { if (backbrush != null) { backbrush.Dispose(); backbrush = null; } } } PaintImage(e, layout); //inflate the focus rectangle to be consistent with the behavior of Win32 app if (Application.RenderWithVisualStyles) { layout.focus.Inflate(1, 1); } PaintField(e, layout, colors, colors.windowText, true); if (!Application.RenderWithVisualStyles) { Rectangle r = Control.ClientRectangle; if (Control.IsDefault) { r.Inflate(-1, -1); } DrawDefaultBorder(g, r, colors.windowFrame, this.Control.IsDefault); if (up) { Draw3DBorder(g, r, colors, up); } else { // contrary to popular belief, not Draw3DBorder(..., false); // ControlPaint.DrawBorder(g, r, colors.buttonShadow, ButtonBorderStyle.Solid); } } } #region Layout protected override LayoutOptions Layout(PaintEventArgs e) { LayoutOptions layout = PaintLayout(e, /* up = */ false); Debug.Assert(layout.GetPreferredSizeCore(LayoutUtils.MaxSize) == PaintLayout(e, /* up = */ true).GetPreferredSizeCore(LayoutUtils.MaxSize), "The state of up should not effect PreferredSize"); return layout; } [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // removed graphics, may have to put it back private LayoutOptions PaintLayout(PaintEventArgs e, bool up) { LayoutOptions layout = CommonLayout(); layout.textOffset = !up; layout.everettButtonCompat = !Application.RenderWithVisualStyles; return layout; } #endregion } }
using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.IO; using System.Web; using Rainbow.Framework.Settings; using Rainbow.Framework.Site.Configuration; using Rainbow.Framework.Users.Data; using Path=Rainbow.Framework.Settings.Path; namespace Rainbow.Framework.Site.Data { /// <summary> /// Class that encapsulates all data logic necessary to add/query/delete /// Portals within the Portal database. /// /// </summary> public class PortalsDB { private const string stradmin = "admin"; private const string strAdmins = "Admins;"; private const string strAllUsers = "All Users"; private const string strATAlwaysShowEditButton = "@AlwaysShowEditButton"; private const string strATPortalID = "@PortalID"; private const string strATPortalName = "@PortalName"; private const string strATPortalPath = "@PortalPath"; private const string strContentPane = "ContentPane"; private const string strGUIDHTMLDocument = "{0B113F51-FEA3-499A-98E7-7B83C192FDBB}"; private const string strGUIDLanguageSwitcher = "{25E3290E-3B9A-4302-9384-9CA01243C00F}"; private const string strGUIDLogin = "{A0F1F62B-FDC7-4DE5-BBAD-A5DAF31D960A}"; private const string strGUIDManageUsers = "{B6A48596-9047-4564-8555-61E3B31D7272}"; private const string strGUIDModules = "{5E0DB0C7-FD54-4F55-ACF5-6ECF0EFA59C0}"; private const string strGUIDSecurityRoles = "{A406A674-76EB-4BC1-BB35-50CD2C251F9C}"; private const string strGUIDSiteSettings = "{EBBB01B1-FBB5-4E79-8FC4-59BCA1D0554E}"; private const string strGUIDPages = "{1C575D94-70FC-4A83-80C3-2087F726CBB3}"; private const string strLeftPane = "LeftPane"; //jes1111 - const string strPortalsDirectory = "PortalsDirectory"; private const string strrb_GetPortals = "rb_GetPortals"; private const string strRightPane = "RightPane"; /// <summary> /// The AddPortal method add a new portal.<br/> /// AddPortal Stored Procedure /// </summary> /// <param name="portalAlias">The portal alias.</param> /// <param name="portalName">Name of the portal.</param> /// <param name="portalPath">The portal path.</param> /// <returns></returns> public int AddPortal(string portalAlias, string portalName, string portalPath) { // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand("rb_AddPortal", myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterPortalAlias = new SqlParameter("@PortalAlias", SqlDbType.NVarChar, 128); parameterPortalAlias.Value = portalAlias; myCommand.Parameters.Add(parameterPortalAlias); SqlParameter parameterPortalName = new SqlParameter(strATPortalName, SqlDbType.NVarChar, 128); parameterPortalName.Value = portalName; myCommand.Parameters.Add(parameterPortalName); //jes1111 // string pd = ConfigurationSettings.AppSettings[strPortalsDirectory]; // // if(pd!=null) // { // if (portalPath.IndexOf (pd) > -1) // portalPath = portalPath.Substring(portalPath.IndexOf (pd) + pd.Length); // } string pd = Config.PortalsDirectory; if (portalPath.IndexOf(pd) > -1) portalPath = portalPath.Substring(portalPath.IndexOf(pd) + pd.Length); SqlParameter parameterPortalPath = new SqlParameter(strATPortalPath, SqlDbType.NVarChar, 128); parameterPortalPath.Value = portalPath; myCommand.Parameters.Add(parameterPortalPath); SqlParameter parameterAlwaysShow = new SqlParameter(strATAlwaysShowEditButton, SqlDbType.Bit, 1); parameterAlwaysShow.Value = false; myCommand.Parameters.Add(parameterAlwaysShow); SqlParameter parameterPortalID = new SqlParameter(strATPortalID, SqlDbType.Int, 4); parameterPortalID.Direction = ParameterDirection.Output; myCommand.Parameters.Add(parameterPortalID); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } return (int) parameterPortalID.Value; } } } /// <summary> /// The CreatePortal method create a new basic portal based on solutions table. /// </summary> /// <param name="solutionID">The solution ID.</param> /// <param name="portalAlias">The portal alias.</param> /// <param name="portalName">Name of the portal.</param> /// <param name="portalPath">The portal path.</param> /// <returns></returns> [ History("john.mandia@whitelightsolutions.com", "2003/05/26", "Added extra info so that sign in is added to home tab of new portal and lang switcher is added to module list" )] [History("bja@reedtek.com", "2003/05/16", "Added extra parameter for collpasable window")] public int CreatePortal(int solutionID, string portalAlias, string portalName, string portalPath) { int portalID; PagesDB tabs = new PagesDB(); ModulesDB modules = new ModulesDB(); // Create a new portal portalID = AddPortal(portalAlias, portalName, portalPath); // get module definitions SqlDataReader myReader; myReader = modules.GetSolutionModuleDefinitions(solutionID); // Always call Read before accessing data. try { while (myReader.Read()) { modules.UpdateModuleDefinitions(new Guid(myReader["GeneralModDefID"].ToString()), portalID, true); } } finally { myReader.Close(); //by Manu, fixed bug 807858 } if ( !Config.UseSingleUserBase ) { string AdminEmail = "admin@rainbowportal.net"; // Create the stradmin User for the new portal UsersDB User = new UsersDB(); // Create the "Admins" role for the new portal Guid roleID = User.AddRole( "Admins" ); Guid userID = User.AddUser( stradmin, AdminEmail, stradmin ); // Create a new row in a many to many table (userroles) // giving the "admins" role to the stradmin user User.AddUserRole( roleID, userID ); } // Create a new Page "home" int homePageID = tabs.AddPage(portalID, "Home", 1); // Create a new Page "admin" string localizedString = General.GetString("ADMIN_TAB_NAME"); int adminPageID = tabs.AddPage(portalID, localizedString, strAdmins, 9999); // Add Modules for portal use // Html Document modules.UpdateModuleDefinitions(new Guid(strGUIDHTMLDocument), portalID, true); // Add Modules for portal administration // Site Settings (Admin) localizedString = General.GetString("MODULE_SITE_SETTINGS"); modules.UpdateModuleDefinitions(new Guid(strGUIDSiteSettings), portalID, true); modules.AddModule(adminPageID, 1, strContentPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDSiteSettings)), 0, strAdmins, strAllUsers, strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // Pages (Admin) localizedString = General.GetString("MODULE_TABS"); modules.UpdateModuleDefinitions(new Guid(strGUIDPages), portalID, true); modules.AddModule(adminPageID, 2, strContentPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDPages)), 0, strAdmins, strAllUsers, strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // Roles (Admin) localizedString = General.GetString("MODULE_SECURITY_ROLES"); modules.UpdateModuleDefinitions(new Guid(strGUIDSecurityRoles), portalID, true); modules.AddModule(adminPageID, 3, strContentPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDSecurityRoles)), 0, strAdmins, strAllUsers, strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // Manage Users (Admin) localizedString = General.GetString("MODULE_MANAGE_USERS"); modules.UpdateModuleDefinitions(new Guid(strGUIDManageUsers), portalID, true); modules.AddModule(adminPageID, 4, strContentPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDManageUsers)), 0, strAdmins, strAllUsers, strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // Module Definitions (Admin) localizedString = General.GetString("MODULE_MODULES"); modules.UpdateModuleDefinitions(new Guid(strGUIDModules), portalID, true); modules.AddModule(adminPageID, 1, strRightPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDModules)), 0, strAdmins, strAllUsers, strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // End Change Geert.Audenaert@Syntegra.Com // Change by john.mandia@whitelightsolutions.com // Add Signin Module and put it on the hometab // Signin localizedString = General.GetString("MODULE_LOGIN", "Login"); modules.UpdateModuleDefinitions(new Guid(strGUIDLogin), portalID, true); modules.AddModule(homePageID, -1, strLeftPane, localizedString, modules.GetModuleDefinitionByGuid(portalID, new Guid(strGUIDLogin)), 0, strAdmins, "Unauthenticated Users;Admins;", strAdmins, strAdmins, strAdmins, strAdmins, strAdmins, false, string.Empty, false, false, false); // Add language switcher to available modules // Language Switcher modules.UpdateModuleDefinitions(new Guid(strGUIDLanguageSwitcher), portalID, true); // End of change by john.mandia@whitelightsolutions.com // Create paths CreatePortalPath(portalPath); return portalID; } /// <summary> /// Creates the portal path. /// </summary> /// <param name="portalPath">The portal path.</param> public void CreatePortalPath(string portalPath) { portalPath = portalPath.Replace("/", string.Empty); portalPath = portalPath.Replace("\\", string.Empty); portalPath = portalPath.Replace(".", string.Empty); if (!portalPath.StartsWith("_")) portalPath = "_" + portalPath; // jes1111 // string pd = ConfigurationSettings.AppSettings[strPortalsDirectory]; // // if(pd!=null) // { // if (portalPath.IndexOf (pd) > -1) // portalPath = portalPath.Substring(portalPath.IndexOf (pd) + pd.Length); // } string pd = Config.PortalsDirectory; if (portalPath.IndexOf(pd) > -1) portalPath = portalPath.Substring(portalPath.IndexOf(pd) + pd.Length); // jes1111 - string portalPhisicalDir = HttpContext.Current.Server.MapPath(Path.ApplicationRoot + "/" + ConfigurationSettings.AppSettings[strPortalsDirectory] + "/" + portalPath); string portalPhisicalDir = HttpContext.Current.Server.MapPath( Path.WebPathCombine(Path.ApplicationRoot, Config.PortalsDirectory, portalPath)); if (!Directory.Exists(portalPhisicalDir)) Directory.CreateDirectory(portalPhisicalDir); // Subdirs string[] subdirs = {"images", "polls", "documents", "xml"}; for (int i = 0; i <= subdirs.GetUpperBound(0); i++) if (!Directory.Exists(portalPhisicalDir + "\\" + subdirs[i])) Directory.CreateDirectory(portalPhisicalDir + "\\" + subdirs[i]); } /// <summary> /// Removes portal from database. All tabs, modules and data wil be removed. /// </summary> /// <param name="portalID">The portal ID.</param> public void DeletePortal(int portalID) { // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand("rb_DeletePortal", myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterPortalID = new SqlParameter(strATPortalID, SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.Parameters.Add(parameterPortalID); // Execute the command myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } } /// <summary> /// The GetPortals method returns a SqlDataReader containing all of the /// Portals registered in this database.<br/> /// GetPortals Stored Procedure /// </summary> /// <returns></returns> // TODO --> [Obsolete("Replace me")] public SqlDataReader GetPortals() { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand("rb_GetPortals", myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The GetPortals method returns an ArrayList containing all of the /// Portals registered in this database.<br/> /// GetPortals Stored Procedure /// </summary> /// <returns>portals</returns> public ArrayList GetPortalsArrayList() { ArrayList portals = new ArrayList(); // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand(strrb_GetPortals, myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Execute the command myConnection.Open(); using (SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection)) { try { while (dr.Read()) { PortalItem p = new PortalItem(); p.Name = dr["PortalName"].ToString(); p.Path = dr["PortalPath"].ToString(); p.ID = Convert.ToInt32(dr["PortalID"].ToString()); portals.Add(p); } } finally { dr.Close(); //by Manu, fixed bug 807858 } } // Return the portals return portals; } } } /// <summary> /// The GetTemplates method returns a SqlDataReader containing all of the /// Templates Availables. /// </summary> /// <returns></returns> // TODO --> [Obsolete("Replace me")] public SqlDataReader GetTemplates() { // Create Instance of Connection and Command Object SqlConnection myConnection = Config.SqlConnectionString; SqlCommand myCommand = new SqlCommand(strrb_GetPortals, myConnection); // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Execute the command myConnection.Open(); SqlDataReader result = myCommand.ExecuteReader(CommandBehavior.CloseConnection); // Return the datareader return result; } /// <summary> /// The UpdatePortalInfo method updates the name and access settings for the portal.<br/> /// Uses UpdatePortalInfo Stored Procedure. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="portalName">Name of the portal.</param> /// <param name="portalPath">The portal path.</param> /// <param name="alwaysShow">if set to <c>true</c> [always show].</param> public void UpdatePortalInfo(int portalID, string portalName, string portalPath, bool alwaysShow) { // Create Instance of Connection and Command Object using (SqlConnection myConnection = Config.SqlConnectionString) { using (SqlCommand myCommand = new SqlCommand("rb_UpdatePortalInfo", myConnection)) { // Mark the Command as a SPROC myCommand.CommandType = CommandType.StoredProcedure; // Add Parameters to SPROC SqlParameter parameterPortalID = new SqlParameter(strATPortalID, SqlDbType.Int, 4); parameterPortalID.Value = portalID; myCommand.Parameters.Add(parameterPortalID); SqlParameter parameterPortalName = new SqlParameter(strATPortalName, SqlDbType.NVarChar, 128); parameterPortalName.Value = portalName; myCommand.Parameters.Add(parameterPortalName); // jes1111 // string pd = ConfigurationSettings.AppSettings[strPortalsDirectory]; // // if(pd!=null) // { // if (portalPath.IndexOf (pd) > -1) // portalPath = portalPath.Substring(portalPath.IndexOf (pd) + pd.Length); // } string pd = Config.PortalsDirectory; if (portalPath.IndexOf(pd) > -1) portalPath = portalPath.Substring(portalPath.IndexOf(pd) + pd.Length); SqlParameter parameterPortalPath = new SqlParameter(strATPortalPath, SqlDbType.NVarChar, 128); parameterPortalPath.Value = portalPath; myCommand.Parameters.Add(parameterPortalPath); SqlParameter parameterAlwaysShow = new SqlParameter(strATAlwaysShowEditButton, SqlDbType.Bit, 1); parameterAlwaysShow.Value = alwaysShow; myCommand.Parameters.Add(parameterAlwaysShow); myConnection.Open(); try { myCommand.ExecuteNonQuery(); } finally { myConnection.Close(); } } } } /// <summary> /// The UpdatePortalSetting Method updates a single module setting /// in the PortalSettings database table. /// </summary> /// <param name="portalID">The portal ID.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("UpdatePortalSetting was moved in PortalSettings.UpdatePortalSetting", false)] public void UpdatePortalSetting(int portalID, string key, string value) { PortalSettings.UpdatePortalSetting(portalID, key, value); } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Data; using System.Diagnostics; using ESRI.ArcGIS.Framework; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.CartoUI; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; namespace MultivariateRenderers { public class PropPageForm : System.Windows.Forms.Form { private enum eRendererType: int { eShapePattern, eColor, eSize } private bool m_PageIsDirty = false; private IComPropertyPageSite m_pSite; private IMap m_pMap; private IGeoFeatureLayer m_pCurrentLayer; private IFeatureRenderer m_pRend; private IFeatureRenderer[] m_pShapePatternRendList; private IFeatureRenderer[] m_pColorRendList; // we could have separate lists for hue, sat/val, etc, but keep it simple for now private IFeatureRenderer[] m_pSizeRendList; private EColorCombinationType m_eColorCombinationMethod; private IFeatureRenderer m_pShapePatternRend; private IFeatureRenderer m_pColorRend1; private IFeatureRenderer m_pColorRend2; private IFeatureRenderer m_pSizeRend; #region Windows Form Designer generated code public PropPageForm() : base() { //This call is required by the Windows Form Designer. InitializeComponent(); //Add any initialization after the InitializeComponent() call } //Form overrides dispose to clean up the component list. protected override void Dispose(bool disposing) { if (disposing) { if (components != null) components.Dispose(); } base.Dispose(disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. internal System.Windows.Forms.ComboBox cboShapePattern; internal System.Windows.Forms.ComboBox cboHue; internal System.Windows.Forms.CheckBox chkShapePattern; internal System.Windows.Forms.CheckBox chkColor; internal System.Windows.Forms.RadioButton radComponents; internal System.Windows.Forms.Label lblHue; internal System.Windows.Forms.Label lblPrimaryColor; internal System.Windows.Forms.RadioButton radCombination; internal System.Windows.Forms.ComboBox cboPrimaryColor; internal System.Windows.Forms.ComboBox cboSatValue; internal System.Windows.Forms.Label lblSatValue; internal System.Windows.Forms.Label lblSecondaryColor; internal System.Windows.Forms.ComboBox cboSecondaryColor; internal System.Windows.Forms.CheckBox chkSize; internal System.Windows.Forms.ComboBox cboSize; internal System.Windows.Forms.CheckBox chkRotation; internal System.Windows.Forms.Button butRotation; internal System.Windows.Forms.ComboBox cboSize1; [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.cboShapePattern = new System.Windows.Forms.ComboBox(); this.cboHue = new System.Windows.Forms.ComboBox(); this.chkShapePattern = new System.Windows.Forms.CheckBox(); this.chkColor = new System.Windows.Forms.CheckBox(); this.radComponents = new System.Windows.Forms.RadioButton(); this.lblHue = new System.Windows.Forms.Label(); this.lblPrimaryColor = new System.Windows.Forms.Label(); this.radCombination = new System.Windows.Forms.RadioButton(); this.cboPrimaryColor = new System.Windows.Forms.ComboBox(); this.cboSatValue = new System.Windows.Forms.ComboBox(); this.lblSatValue = new System.Windows.Forms.Label(); this.lblSecondaryColor = new System.Windows.Forms.Label(); this.cboSecondaryColor = new System.Windows.Forms.ComboBox(); this.chkSize = new System.Windows.Forms.CheckBox(); this.chkRotation = new System.Windows.Forms.CheckBox(); this.butRotation = new System.Windows.Forms.Button(); this.cboSize1 = new System.Windows.Forms.ComboBox(); this.SuspendLayout(); // // cboShapePattern // this.cboShapePattern.Location = new System.Drawing.Point(224, 11); this.cboShapePattern.Name = "cboShapePattern"; this.cboShapePattern.Size = new System.Drawing.Size(121, 21); this.cboShapePattern.TabIndex = 24; this.cboShapePattern.SelectedIndexChanged += new System.EventHandler(this.cboShapePattern_SelectedIndexChanged); // // cboHue // this.cboHue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboHue.Enabled = false; this.cboHue.Location = new System.Drawing.Point(224, 48); this.cboHue.Name = "cboHue"; this.cboHue.Size = new System.Drawing.Size(192, 21); this.cboHue.TabIndex = 5; this.cboHue.EnabledChanged += new System.EventHandler(this.cboHue_EnabledChanged); this.cboHue.SelectedIndexChanged += new System.EventHandler(this.cboHue_SelectedIndexChanged); // // chkShapePattern // this.chkShapePattern.Location = new System.Drawing.Point(8, 8); this.chkShapePattern.Name = "chkShapePattern"; this.chkShapePattern.Size = new System.Drawing.Size(152, 24); this.chkShapePattern.TabIndex = 6; this.chkShapePattern.Text = "Shape/Pattern"; this.chkShapePattern.CheckedChanged += new System.EventHandler(this.chkShapePattern_CheckedChanged); // // chkColor // this.chkColor.Location = new System.Drawing.Point(8, 32); this.chkColor.Name = "chkColor"; this.chkColor.Size = new System.Drawing.Size(152, 24); this.chkColor.TabIndex = 7; this.chkColor.Text = "Color"; this.chkColor.CheckedChanged += new System.EventHandler(this.chkColor_CheckedChanged); // // radComponents // this.radComponents.Enabled = false; this.radComponents.Location = new System.Drawing.Point(24, 56); this.radComponents.Name = "radComponents"; this.radComponents.Size = new System.Drawing.Size(128, 24); this.radComponents.TabIndex = 8; this.radComponents.Text = "Color Components"; this.radComponents.CheckedChanged += new System.EventHandler(this.radComponents_CheckedChanged); this.radComponents.EnabledChanged += new System.EventHandler(this.radComponents_EnabledChanged); // // lblHue // this.lblHue.Enabled = false; this.lblHue.Location = new System.Drawing.Point(136, 48); this.lblHue.Name = "lblHue"; this.lblHue.Size = new System.Drawing.Size(88, 24); this.lblHue.TabIndex = 9; this.lblHue.Text = "Hue"; // // lblPrimaryColor // this.lblPrimaryColor.Enabled = false; this.lblPrimaryColor.Location = new System.Drawing.Point(136, 104); this.lblPrimaryColor.Name = "lblPrimaryColor"; this.lblPrimaryColor.Size = new System.Drawing.Size(88, 24); this.lblPrimaryColor.TabIndex = 12; this.lblPrimaryColor.Text = "Color 1"; // // radCombination // this.radCombination.Enabled = false; this.radCombination.Location = new System.Drawing.Point(24, 112); this.radCombination.Name = "radCombination"; this.radCombination.Size = new System.Drawing.Size(128, 24); this.radCombination.TabIndex = 11; this.radCombination.Text = "Color Combination"; this.radCombination.CheckedChanged += new System.EventHandler(this.radCombination_CheckedChanged); this.radCombination.EnabledChanged += new System.EventHandler(this.radCombination_EnabledChanged); // // cboPrimaryColor // this.cboPrimaryColor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboPrimaryColor.Enabled = false; this.cboPrimaryColor.Location = new System.Drawing.Point(224, 104); this.cboPrimaryColor.Name = "cboPrimaryColor"; this.cboPrimaryColor.Size = new System.Drawing.Size(192, 21); this.cboPrimaryColor.TabIndex = 10; this.cboPrimaryColor.EnabledChanged += new System.EventHandler(this.cboPrimaryColor_EnabledChanged); this.cboPrimaryColor.SelectedIndexChanged += new System.EventHandler(this.cboPrimaryColor_SelectedIndexChanged); // // cboSatValue // this.cboSatValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSatValue.Enabled = false; this.cboSatValue.Location = new System.Drawing.Point(224, 72); this.cboSatValue.Name = "cboSatValue"; this.cboSatValue.Size = new System.Drawing.Size(192, 21); this.cboSatValue.TabIndex = 13; this.cboSatValue.EnabledChanged += new System.EventHandler(this.cboSatValue_EnabledChanged); this.cboSatValue.SelectedIndexChanged += new System.EventHandler(this.cboSatValue_selectedIndexChanged); // // lblSatValue // this.lblSatValue.Enabled = false; this.lblSatValue.Location = new System.Drawing.Point(136, 72); this.lblSatValue.Name = "lblSatValue"; this.lblSatValue.Size = new System.Drawing.Size(88, 24); this.lblSatValue.TabIndex = 14; this.lblSatValue.Text = "Saturation/Value"; // // lblSecondaryColor // this.lblSecondaryColor.Enabled = false; this.lblSecondaryColor.Location = new System.Drawing.Point(136, 128); this.lblSecondaryColor.Name = "lblSecondaryColor"; this.lblSecondaryColor.Size = new System.Drawing.Size(88, 24); this.lblSecondaryColor.TabIndex = 16; this.lblSecondaryColor.Text = "Color 2"; // // cboSecondaryColor // this.cboSecondaryColor.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSecondaryColor.Enabled = false; this.cboSecondaryColor.Location = new System.Drawing.Point(224, 128); this.cboSecondaryColor.Name = "cboSecondaryColor"; this.cboSecondaryColor.Size = new System.Drawing.Size(192, 21); this.cboSecondaryColor.TabIndex = 15; this.cboSecondaryColor.EnabledChanged += new System.EventHandler(this.cboSecondaryColor_EnabledChanged); this.cboSecondaryColor.SelectedIndexChanged += new System.EventHandler(this.cboSecondaryColor_SelectedIndexChanged); // // chkSize // this.chkSize.Location = new System.Drawing.Point(8, 160); this.chkSize.Name = "chkSize"; this.chkSize.Size = new System.Drawing.Size(152, 24); this.chkSize.TabIndex = 18; this.chkSize.Text = "Size"; this.chkSize.CheckedChanged += new System.EventHandler(this.chkSize_CheckedChanged); // // chkRotation // this.chkRotation.Location = new System.Drawing.Point(8, 192); this.chkRotation.Name = "chkRotation"; this.chkRotation.Size = new System.Drawing.Size(152, 24); this.chkRotation.TabIndex = 19; this.chkRotation.Text = "Rotation"; this.chkRotation.CheckedChanged += new System.EventHandler(this.chkRotation_CheckedChanged); // // butRotation // this.butRotation.Enabled = false; this.butRotation.Location = new System.Drawing.Point(224, 192); this.butRotation.Name = "butRotation"; this.butRotation.Size = new System.Drawing.Size(192, 24); this.butRotation.TabIndex = 21; this.butRotation.Text = "Properties"; this.butRotation.Click += new System.EventHandler(this.butRotation_Click); // // cboSize1 // this.cboSize1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSize1.Enabled = false; this.cboSize1.Location = new System.Drawing.Point(224, 160); this.cboSize1.Name = "cboSize1"; this.cboSize1.Size = new System.Drawing.Size(192, 21); this.cboSize1.TabIndex = 23; this.cboSize1.SelectedIndexChanged += new System.EventHandler(this.cboSize1_selectedindexchanged); // // PropPageForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(424, 285); this.Controls.Add(this.cboSize1); this.Controls.Add(this.butRotation); this.Controls.Add(this.chkRotation); this.Controls.Add(this.chkSize); this.Controls.Add(this.lblSecondaryColor); this.Controls.Add(this.cboSecondaryColor); this.Controls.Add(this.lblSatValue); this.Controls.Add(this.cboSatValue); this.Controls.Add(this.lblPrimaryColor); this.Controls.Add(this.radCombination); this.Controls.Add(this.cboPrimaryColor); this.Controls.Add(this.lblHue); this.Controls.Add(this.radComponents); this.Controls.Add(this.chkColor); this.Controls.Add(this.chkShapePattern); this.Controls.Add(this.cboHue); this.Controls.Add(this.cboShapePattern); this.Name = "PropPageForm"; this.Text = "ColorPropPageForm"; this.Load += new System.EventHandler(this.PropPageForm_Load); this.ResumeLayout(false); } #endregion public bool IsDirty { get { return m_PageIsDirty; } } public IComPropertyPageSite PageSite { set { m_pSite = value; } } public void InitControls(IMultivariateRenderer pMultiRend, IMap pMap, IGeoFeatureLayer pGeoLayer) { // copy properties from the renderer and map to the form m_eColorCombinationMethod = pMultiRend.ColorCombinationMethod; m_pShapePatternRend = pMultiRend.ShapePatternRend; m_pColorRend1 = pMultiRend.ColorRend1; m_pColorRend2 = pMultiRend.ColorRend2; m_pSizeRend = pMultiRend.SizeRend; if (m_pShapePatternRend != null) { chkShapePattern.CheckState = System.Windows.Forms.CheckState.Checked; cboShapePattern.Enabled = true; } if (m_eColorCombinationMethod == EColorCombinationType.enuComponents) { radComponents.Checked = true; radCombination.Checked = false; UpdateColorComb(); } else { //disabled //radComponents.Checked = false; //radCombination.Checked = true; radComponents.Checked = true; radCombination.Checked = false; UpdateColorComb(); } if (m_pColorRend1 != null) { chkColor.CheckState = System.Windows.Forms.CheckState.Checked; radComponents.Enabled = true; //disabled //radCombination.Enabled = true; radCombination.Enabled = false; } if (m_pSizeRend != null) { chkSize.CheckState = System.Windows.Forms.CheckState.Checked; cboSize1.Enabled = true; } IRotationRenderer pRotRend = null; pRotRend = pMultiRend as IRotationRenderer; if (pRotRend.RotationField != "") { chkRotation.CheckState = System.Windows.Forms.CheckState.Checked; butRotation.Enabled = true; } //ITransparencyRenderer pTransRend = null; //pTransRend = pMultiRend as ITransparencyRenderer; //if (pTransRend.TransparencyField != "") //{ // chkTransparency.CheckState = System.Windows.Forms.CheckState.Checked; // butTransparency.Enabled = true; //} m_pMap = pMap; m_pCurrentLayer = pGeoLayer; m_pRend = pMultiRend as IFeatureRenderer; // we need this object to support the root transparency dialogs m_PageIsDirty = false; } public void InitRenderer(IMultivariateRenderer pMultiRend) { // copy properties from the form to the renderer if (chkShapePattern.CheckState == System.Windows.Forms.CheckState.Checked) pMultiRend.ShapePatternRend = m_pShapePatternRend; else pMultiRend.ShapePatternRend = null; if (chkColor.CheckState == System.Windows.Forms.CheckState.Checked) { pMultiRend.ColorRend1 = m_pColorRend1; pMultiRend.ColorRend2 = m_pColorRend2; pMultiRend.ColorCombinationMethod = m_eColorCombinationMethod; } else { pMultiRend.ColorRend1 = null; pMultiRend.ColorRend2 = null; pMultiRend.ColorCombinationMethod = EColorCombinationType.enuCIELabMatrix; // default (?) } if (chkSize.CheckState == System.Windows.Forms.CheckState.Checked) pMultiRend.SizeRend = m_pSizeRend; else pMultiRend.SizeRend = null; IRotationRenderer pRotRend = null; IRotationRenderer pFormRotRend = null; pRotRend = pMultiRend as IRotationRenderer; if (chkRotation.CheckState == System.Windows.Forms.CheckState.Checked) { pFormRotRend = m_pRend as IRotationRenderer; pRotRend.RotationField = pFormRotRend.RotationField; pRotRend.RotationType = pFormRotRend.RotationType; } else { pRotRend.RotationField = ""; pRotRend.RotationType = esriSymbolRotationType.esriRotateSymbolArithmetic; // default (?) } //ITransparencyRenderer pTransRend = null; //ITransparencyRenderer pFormTransRend = null; //pTransRend = pMultiRend as ITransparencyRenderer; //if (chkTransparency.CheckState == System.Windows.Forms.CheckState.Checked) //{ // pFormTransRend = m_pRend as ITransparencyRenderer; // pTransRend.TransparencyField = pFormTransRend.TransparencyField; //} //else // pTransRend.TransparencyField = ""; } private void PropPageForm_Load(object sender, System.EventArgs e) { // initialize form controls from data members IEnumLayer pGeoLayers = null; UID pUID = new UID(); pUID.Value = "{E156D7E5-22AF-11D3-9F99-00C04F6BC78E}"; pGeoLayers = m_pMap.get_Layers(pUID, true); pGeoLayers.Reset(); IGeoFeatureLayer pGeoLayer = null; IFeatureRenderer pFeatRend = null; int iColor = 0; int iShapePattern = 0; int iSize = 0; pGeoLayer = pGeoLayers.Next() as IGeoFeatureLayer; string sColor1 = ""; string sColor2 = ""; string sShapePattern = ""; string sSize = ""; while (pGeoLayer != null) { // to keep things simple, filter for layers with same feat class geometry (point, line, poly) as current layer if ((pGeoLayer.FeatureClass.ShapeType) == (m_pCurrentLayer.FeatureClass.ShapeType)) { // filter out the current layer if (! (pGeoLayer == m_pCurrentLayer)) { pFeatRend = pGeoLayer.Renderer; // filter for only layers currently assigned a renderer that is valid for each renderer type (shape, color, size) if (RendererIsValidForType(pFeatRend, eRendererType.eColor)) { iColor = iColor + 1; System.Array.Resize(ref m_pColorRendList, iColor + 1); m_pColorRendList[iColor - 1] = pFeatRend; cboHue.Items.Add(pGeoLayer.Name); cboSatValue.Items.Add(pGeoLayer.Name); cboPrimaryColor.Items.Add(pGeoLayer.Name); cboSecondaryColor.Items.Add(pGeoLayer.Name); if (CompareRenderers(pGeoLayer.Renderer, m_pColorRend1)) sColor1 = pGeoLayer.Name; if (CompareRenderers(pGeoLayer.Renderer, m_pColorRend2)) sColor2 = pGeoLayer.Name; } if (RendererIsValidForType(pFeatRend, eRendererType.eShapePattern)) { iShapePattern = iShapePattern + 1; System.Array.Resize(ref m_pShapePatternRendList, iShapePattern + 1); m_pShapePatternRendList[iShapePattern - 1] = pFeatRend; cboShapePattern.Items.Add(pGeoLayer.Name); //if (pGeoLayer.Renderer == m_pShapePatternRend) // sShapePattern = pGeoLayer.Name; if (CompareRenderers(pGeoLayer.Renderer, m_pShapePatternRend)) sShapePattern = pGeoLayer.Name; } if (RendererIsValidForType(pFeatRend, eRendererType.eSize)) { iSize = iSize + 1; System.Array.Resize(ref m_pSizeRendList, iSize + 1); m_pSizeRendList[iSize - 1] = pFeatRend; cboSize1.Items.Add(pGeoLayer.Name); //if (pGeoLayer.Renderer == m_pSizeRend) // sSize = pGeoLayer.Name; if (CompareRenderers(pGeoLayer.Renderer, m_pSizeRend)) sSize = pGeoLayer.Name; } } } pGeoLayer = pGeoLayers.Next() as IGeoFeatureLayer; } // select correct items in combos cboShapePattern.Text = sShapePattern; if (radComponents.Checked) { cboHue.Text = sColor1; cboSatValue.Text = sColor2; } else { cboPrimaryColor.Text = sColor1; cboSecondaryColor.Text = sColor2; } cboSize1.Text = sSize; // disable if there aren't any layers in the map of the correct type if (iShapePattern <= 0) cboShapePattern.Enabled = false; if (iColor <= 0) { if (radComponents.Checked) { cboHue.Enabled = false; cboSatValue.Enabled = false; } else { cboPrimaryColor.Enabled = false; cboSecondaryColor.Enabled = false; } } if (iSize <= 0) cboSize1.Enabled = false; } private void cboShapePattern_SelectedIndexChanged(object sender, System.EventArgs e) { m_pShapePatternRend = m_pShapePatternRendList[cboShapePattern.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void cboHue_SelectedIndexChanged(object sender, System.EventArgs e) { m_pColorRend1 = m_pColorRendList[cboHue.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void cboSatValue_selectedIndexChanged(object sender, System.EventArgs e) { m_pColorRend2 = m_pColorRendList[cboSatValue.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void cboPrimaryColor_SelectedIndexChanged(object sender, System.EventArgs e) { m_pColorRend1 = m_pColorRendList[cboPrimaryColor.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void cboSecondaryColor_SelectedIndexChanged(object sender, System.EventArgs e) { m_pColorRend2 = m_pColorRendList[cboSecondaryColor.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void cboSize1_selectedindexchanged(object sender, System.EventArgs e) { m_pSizeRend = m_pSizeRendList[cboSize1.SelectedIndex]; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void radComponents_CheckedChanged(object sender, System.EventArgs e) { UpdateColorComb(); } private void radCombination_CheckedChanged(object sender, System.EventArgs e) { UpdateColorComb(); } private void UpdateColorComb() { if (radComponents.Checked) { m_eColorCombinationMethod = EColorCombinationType.enuComponents; cboHue.Enabled = true; cboSatValue.Enabled = true; cboPrimaryColor.Enabled = false; cboSecondaryColor.Enabled = false; } else { m_eColorCombinationMethod = EColorCombinationType.enuCIELabMatrix; cboHue.Enabled = false; cboSatValue.Enabled = false; cboPrimaryColor.Enabled = true; cboSecondaryColor.Enabled = true; } if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private bool RendererIsValidForType(IFeatureRenderer pFeatRend, eRendererType eMultiRendType) { // indicates whether or not pFeatRend is valid for the eMultiRendType for the current layer // e.g. if pFeatRend is an IProportionalSymbolRenderer, then it's valid for eMultiRendType = eSize ILegendInfo pLegendInfo = null; if (eMultiRendType == eRendererType.eShapePattern) return pFeatRend is IUniqueValueRenderer; else if (eMultiRendType == eRendererType.eColor) { pLegendInfo = pFeatRend as ILegendInfo; return (pFeatRend is IUniqueValueRenderer) | (pFeatRend is IClassBreaksRenderer & ! pLegendInfo.SymbolsAreGraduated); } else // size { pLegendInfo = pFeatRend as ILegendInfo; return (pFeatRend is IClassBreaksRenderer & pLegendInfo.SymbolsAreGraduated) | (pFeatRend is IProportionalSymbolRenderer); } } private void butRotation_Click(object sender, System.EventArgs e) { IRendererUIDialog2 pRendUIDlg2 = null; pRendUIDlg2 = new MarkerRotationDialog() as IRendererUIDialog2; pRendUIDlg2.FeatureLayer = m_pCurrentLayer; pRendUIDlg2.Renderer = m_pRend; SecondaryForm pMyForm = null; pMyForm = new SecondaryForm(); pRendUIDlg2.DoModal(pMyForm.Handle.ToInt32()); } private void chkShapePattern_CheckedChanged(object sender, System.EventArgs e) { cboShapePattern.Enabled = (chkShapePattern.CheckState == System.Windows.Forms.CheckState.Checked); if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void chkColor_CheckedChanged(object sender, System.EventArgs e) { radComponents.Enabled = (chkColor.CheckState == System.Windows.Forms.CheckState.Checked); //radCombination.Enabled = (chkColor.CheckState == System.Windows.Forms.CheckState.Checked); radCombination.Enabled = false; if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void chkSize_CheckedChanged(object sender, System.EventArgs e) { cboSize1.Enabled = (chkSize.CheckState == System.Windows.Forms.CheckState.Checked); if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } private void chkRotation_CheckedChanged(object sender, System.EventArgs e) { butRotation.Enabled = (chkRotation.CheckState == System.Windows.Forms.CheckState.Checked); if (m_pSite != null) m_pSite.PageChanged(); m_PageIsDirty = true; } //private void chkTransparency_CheckedChanged(object sender, System.EventArgs e) //{ // butTransparency.Enabled = (chkTransparency.CheckState == System.Windows.Forms.CheckState.Checked); // if (m_pSite != null) // m_pSite.PageChanged(); // m_PageIsDirty = true; //} private void radComponents_EnabledChanged(object sender, System.EventArgs e) { cboHue.Enabled = radComponents.Enabled & radComponents.Checked; cboSatValue.Enabled = radComponents.Enabled & radComponents.Checked; } private void radCombination_EnabledChanged(object sender, System.EventArgs e) { //disabled //cboPrimaryColor.Enabled = radCombination.Enabled & radCombination.Checked; //cboSecondaryColor.Enabled = radCombination.Enabled & radCombination.Checked; cboPrimaryColor.Enabled = false; cboSecondaryColor.Enabled = false; } private void cboHue_EnabledChanged(object sender, System.EventArgs e) { lblHue.Enabled = cboHue.Enabled; } private void cboSatValue_EnabledChanged(object sender, System.EventArgs e) { lblSatValue.Enabled = cboSatValue.Enabled; } private void cboPrimaryColor_EnabledChanged(object sender, System.EventArgs e) { lblPrimaryColor.Enabled = cboPrimaryColor.Enabled; } private void cboSecondaryColor_EnabledChanged(object sender, System.EventArgs e) { lblSecondaryColor.Enabled = cboSecondaryColor.Enabled; } private bool CompareRenderers(IFeatureRenderer pRend, IFeatureRenderer pCheckRend) { if (pRend is IClassBreaksRenderer) { // type if (! (pCheckRend is IClassBreaksRenderer)) return false; IClassBreaksRenderer pCBRend = null; pCBRend = pRend as IClassBreaksRenderer; IClassBreaksRenderer pCBCheckRend = null; pCBCheckRend = pCheckRend as IClassBreaksRenderer; // break count if (pCBRend.BreakCount != pCBCheckRend.BreakCount) return false; // field if (pCBRend.Field != pCBCheckRend.Field) return false; } return true; } } } //end of root namespace
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Json { #region Namespaces using System; using System.Diagnostics; using System.Globalization; using System.Xml; using Microsoft.Data.Edm; using Microsoft.Data.Edm.Library; using Microsoft.Data.OData.Metadata; using o = Microsoft.Data.OData; #endregion Namespaces /// <summary> /// Helper methods used by the OData reader for the JSON format. /// </summary> internal static class ODataJsonReaderUtils { /// <summary> /// An enumeration of the various kinds of properties on a feed wrapper object. /// </summary> internal enum FeedPropertyKind { /// <summary>An unsupported property at the feed level.</summary> Unsupported, /// <summary>The inline count property of a feed.</summary> Count, /// <summary>The results property of a feed.</summary> Results, /// <summary>The next page link property of a feed.</summary> NextPageLink, } /// <summary> /// An enumeration of the various kinds of properties on an entity reference link collection. /// </summary> [Flags] internal enum EntityReferenceLinksWrapperPropertyBitMask { /// <summary>An unsupported property at the wrapper level.</summary> None = 0, /// <summary>The inline count property of an entity reference links wrapper.</summary> Count = 1, /// <summary>The results property of an entity reference links wrapper.</summary> Results = 2, /// <summary>The next page link property of an entity reference links wrapper.</summary> NextPageLink = 4, } /// <summary> /// Enumeration of all properties in error payloads, the value of the enum is the bitmask which identifies /// a bit per property. /// </summary> /// <remarks> /// We only use a single enumeration for both top-level as well as inner errors. /// This means that some bits are never set for top-level (or inner errors). /// </remarks> [Flags] internal enum ErrorPropertyBitMask { /// <summary>No property found yet.</summary> None = 0, /// <summary>The "error" of the top-level object.</summary> Error = 1, /// <summary>The "code" property.</summary> Code = 2, /// <summary>The "message" property of either the error object or the inner error object.</summary> Message = 4, /// <summary>The "lang" property of the message object.</summary> MessageLanguage = 8, /// <summary>The "value" property of the message object.</summary> MessageValue = 16, /// <summary>The "innererror" or "internalexception" property of the error object or an inner error object.</summary> InnerError = 32, /// <summary>The "type" property of an inner error object.</summary> TypeName = 64, /// <summary>The "stacktrace" property of an inner error object.</summary> StackTrace = 128, } /// <summary> /// Enumeration of all properties in __metadata, the value of the enum is the bitmask which identifies /// a bit per property. /// </summary> [Flags] internal enum MetadataPropertyBitMask { /// <summary>No property found yet.</summary> None = 0, /// <summary>The "uri" property.</summary> Uri = 1, /// <summary>The "type" property.</summary> Type = 2, /// <summary>The "etag" property.</summary> ETag = 4, /// <summary>The "media_src" property.</summary> MediaUri = 8, /// <summary>The "edit_media" property.</summary> EditMedia = 16, /// <summary>The "content_type" property.</summary> ContentType = 32, /// <summary>The "media_etag" property.</summary> MediaETag = 64, /// <summary>The "properties" property.</summary> Properties = 128, /// <summary>The "id" property.</summary> Id = 256, /// <summary>The "actions" property.</summary> Actions = 512, /// <summary>The "functions" property.</summary> Functions = 1024, } /// <summary> /// Compares the <paramref name="propertyName"/> against the list of supported feed-level properties and /// returns the kind of property. /// </summary> /// <param name="propertyName">The name of the property to check.</param> /// <returns>The kind of feed-level property of the property with name <paramref name="propertyName"/>.</returns> internal static FeedPropertyKind DetermineFeedPropertyKind(string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(propertyName), "Property names must not be null or empty."); if (string.CompareOrdinal(JsonConstants.ODataCountName, propertyName) == 0) { return FeedPropertyKind.Count; } else if (string.CompareOrdinal(JsonConstants.ODataNextLinkName, propertyName) == 0) { return FeedPropertyKind.NextPageLink; } else if (string.CompareOrdinal(JsonConstants.ODataResultsName, propertyName) == 0) { return FeedPropertyKind.Results; } return FeedPropertyKind.Unsupported; } /// <summary> /// Converts the given JSON value to the expected type as per OData conversion rules for JSON values. /// </summary> /// <param name="value">Value to the converted.</param> /// <param name="primitiveTypeReference">Type reference to which the value needs to be converted.</param> /// <param name="messageReaderSettings">The message reader settings used for reading.</param> /// <param name="version">The version of the OData protocol used for reading.</param> /// <param name="validateNullValue">true to validate null values; otherwise false.</param> /// <returns>Object which is in sync with the property type (modulo the V1 exception of converting numbers to non-compatible target types).</returns> internal static object ConvertValue( object value, IEdmPrimitiveTypeReference primitiveTypeReference, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, bool validateNullValue) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(primitiveTypeReference != null, "primitiveTypeReference != null"); //// NOTE: this method was copied from WCF DS (and changed to take a type reference instead of a CLR target type) if (value == null) { // Only primitive type references are validated. Core model is sufficient. ReaderValidationUtils.ValidateNullValue(EdmCoreModel.Instance, primitiveTypeReference, messageReaderSettings, validateNullValue, version); return null; } try { Type targetType = EdmLibraryExtensions.GetPrimitiveClrType(primitiveTypeReference.PrimitiveDefinition(), false); ODataReaderBehavior readerBehavior = messageReaderSettings.ReaderBehavior; string stringValue = value as string; if (stringValue != null) { return ConvertStringValue(stringValue, targetType, version); } else if (value is Int32) { return ConvertInt32Value((int)value, targetType, primitiveTypeReference, readerBehavior == null ? false : readerBehavior.UseV1ProviderBehavior); } else if (value is Double) { Double doubleValue = (Double)value; if (targetType == typeof(Single)) { return Convert.ToSingle(doubleValue); } if (!IsV1PrimitiveType(targetType) || (targetType != typeof(Double) && (readerBehavior == null || !readerBehavior.UseV1ProviderBehavior))) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDouble(primitiveTypeReference.ODataFullName())); } } else if (value is bool) { if (targetType != typeof(bool) && (readerBehavior == null || readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertBoolean(primitiveTypeReference.ODataFullName())); } } else if (value is DateTime) { if (targetType != typeof(DateTime) && (readerBehavior == null || readerBehavior.FormatBehaviorKind != ODataBehaviorKind.WcfDataServicesServer)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDateTime(primitiveTypeReference.ODataFullName())); } } else if (value is DateTimeOffset) { // Currently, we do not support any conversion for DateTimeOffset date type. Hence failing if the target // type is not DateTimeOffset. if (targetType != typeof(DateTimeOffset)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertDateTimeOffset(primitiveTypeReference.ODataFullName())); } } } catch (Exception e) { if (!ExceptionUtils.IsCatchableExceptionType(e)) { throw; } throw ReaderValidationUtils.GetPrimitiveTypeConversionException(primitiveTypeReference, e); } // otherwise just return the value without doing any conversion return value; } /// <summary> /// Ensure that the <paramref name="instance"/> is not null; if so create a new instance. /// </summary> /// <typeparam name="T">The type of the instance to check.</typeparam> /// <param name="instance">The instance to check for null.</param> internal static void EnsureInstance<T>(ref T instance) where T : class, new() { DebugUtils.CheckNoExternalCallers(); if (instance == null) { instance = new T(); } } /// <summary> /// Checks whether the specified property has already been found before. /// </summary> /// <param name="propertiesFoundBitField"> /// The bit field which stores which properties of an error or inner error were found so far. /// </param> /// <param name="propertyFoundBitMask">The bit mask for the property to check.</param> /// <returns>true if the property has not been read before; otherwise false.</returns> internal static bool ErrorPropertyNotFound( ref ODataJsonReaderUtils.ErrorPropertyBitMask propertiesFoundBitField, ODataJsonReaderUtils.ErrorPropertyBitMask propertyFoundBitMask) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(((int)propertyFoundBitMask & (((int)propertyFoundBitMask) - 1)) == 0, "propertyFoundBitMask is not a power of 2."); if ((propertiesFoundBitField & propertyFoundBitMask) == propertyFoundBitMask) { return false; } propertiesFoundBitField |= propertyFoundBitMask; return true; } /// <summary> /// Validates that the string property in __metadata is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> /// <param name="propertyName">The name of the property (used for error reporting).</param> internal static void ValidateMetadataStringProperty(string propertyValue, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if (propertyValue == null) { throw new ODataException(o.Strings.ODataJsonReaderUtils_MetadataPropertyWithNullValue(propertyName)); } } /// <summary> /// Verifies that the specified property was not yet found. /// </summary> /// <param name="propertiesFoundBitField">The bit field which stores which metadata properties were found so far.</param> /// <param name="propertyFoundBitMask">The bit mask for the property to check.</param> /// <param name="propertyName">The name of the property to check (used for error reporting).</param> internal static void VerifyMetadataPropertyNotFound(ref MetadataPropertyBitMask propertiesFoundBitField, MetadataPropertyBitMask propertyFoundBitMask, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(((int)propertyFoundBitMask & (((int)propertyFoundBitMask) - 1)) == 0, "propertyFoundBitMask is not a power of 2."); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if ((propertiesFoundBitField & propertyFoundBitMask) != 0) { throw new ODataException(o.Strings.ODataJsonReaderUtils_MultipleMetadataPropertiesWithSameName(propertyName)); } propertiesFoundBitField |= propertyFoundBitMask; } /// <summary> /// Validates that the string property in an entity reference links collection is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> /// <param name="propertyName">The name of the property (used for error reporting).</param> internal static void ValidateEntityReferenceLinksStringProperty(string propertyValue, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if (propertyValue == null) { throw new ODataException(o.Strings.ODataJsonReaderUtils_EntityReferenceLinksPropertyWithNullValue(propertyName)); } } /// <summary> /// Validates that the count property in an OData-owned object wrapper is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> internal static void ValidateCountPropertyInEntityReferenceLinks(long? propertyValue) { DebugUtils.CheckNoExternalCallers(); if (!propertyValue.HasValue) { throw new ODataException(o.Strings.ODataJsonReaderUtils_EntityReferenceLinksInlineCountWithNullValue(JsonConstants.ODataCountName)); } } /// <summary> /// Verifies that the specified property was not yet found. /// </summary> /// <param name="propertiesFoundBitField"> /// The bit field which stores which properties of an entity reference link collection were found so far. /// </param> /// <param name="propertyFoundBitMask">The bit mask for the property to check.</param> /// <param name="propertyName">The name of the property to check (used for error reporting).</param> internal static void VerifyEntityReferenceLinksWrapperPropertyNotFound( ref EntityReferenceLinksWrapperPropertyBitMask propertiesFoundBitField, EntityReferenceLinksWrapperPropertyBitMask propertyFoundBitMask, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(((int)propertyFoundBitMask & (((int)propertyFoundBitMask) - 1)) == 0, "propertyFoundBitMask is not a power of 2."); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if ((propertiesFoundBitField & propertyFoundBitMask) == propertyFoundBitMask) { throw new ODataException(o.Strings.ODataJsonReaderUtils_MultipleEntityReferenceLinksWrapperPropertiesWithSameName(propertyName)); } propertiesFoundBitField |= propertyFoundBitMask; } /// <summary> /// Verifies that the specified property was not yet found. /// </summary> /// <param name="propertiesFoundBitField"> /// The bit field which stores which properties of an error or inner error were found so far. /// </param> /// <param name="propertyFoundBitMask">The bit mask for the property to check.</param> /// <param name="propertyName">The name of the property to check (used for error reporting).</param> internal static void VerifyErrorPropertyNotFound( ref ErrorPropertyBitMask propertiesFoundBitField, ErrorPropertyBitMask propertyFoundBitMask, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(((int)propertyFoundBitMask & (((int)propertyFoundBitMask) - 1)) == 0, "propertyFoundBitMask is not a power of 2."); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if (!ErrorPropertyNotFound(ref propertiesFoundBitField, propertyFoundBitMask)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_MultipleErrorPropertiesWithSameName(propertyName)); } } /// <summary> /// Validates that the string property in __mediaresource is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> /// <param name="propertyName">The name of the property (used for error reporting).</param> internal static void ValidateMediaResourceStringProperty(string propertyValue, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if (propertyValue == null) { throw new ODataException(o.Strings.ODataJsonReaderUtils_MediaResourcePropertyWithNullValue(propertyName)); } } /// <summary> /// Validates that the property in feed wrapper is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> /// <param name="propertyName">The name of the property (used for error reporting).</param> internal static void ValidateFeedProperty(object propertyValue, string propertyName) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); if (propertyValue == null) { throw new ODataException(o.Strings.ODataJsonReaderUtils_FeedPropertyWithNullValue(propertyName)); } } /// <summary> /// Validates that the property in an operation (an action or a function) is valid. /// </summary> /// <param name="propertyValue">The value of the property.</param> /// <param name="propertyName">The name of the property (used for error reporting).</param> /// <param name="metadata">The metadata value for the operation (used for error reporting).</param> /// <param name="operationsHeader">The header for the operation, either 'actions' or 'functions'.</param> internal static void ValidateOperationJsonProperty(object propertyValue, string propertyName, string metadata, string operationsHeader) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(!string.IsNullOrEmpty(metadata), "!string.IsNullOrEmpty(metadata)"); Debug.Assert(operationsHeader == "actions" || operationsHeader == "functions", "operationsHeader should be either 'actions' or 'functions'"); if (propertyValue == null) { throw new ODataException(o.Strings.ODataJsonReaderUtils_OperationPropertyCannotBeNull( propertyName, metadata, operationsHeader)); } } /// <summary> /// Gets the payload type name for an OData OM instance for JSON. /// </summary> /// <param name="payloadItem">The payload item to get the type name for.</param> /// <returns>The type name as read from the payload item (or constructed for primitive items).</returns> internal static string GetPayloadTypeName(object payloadItem) { DebugUtils.CheckNoExternalCallers(); if (payloadItem == null) { return null; } TypeCode typeCode = o.PlatformHelper.GetTypeCode(payloadItem.GetType()); switch (typeCode) { // In JSON only boolean, DateTime, String, Int32 and Double are recognized as primitive types // (without additional type conversion). So only check for those; if not one of these primitive // types it must be a complex, entity or collection value. case TypeCode.Boolean: return Metadata.EdmConstants.EdmBooleanTypeName; case TypeCode.DateTime: return Metadata.EdmConstants.EdmDateTimeTypeName; case TypeCode.String: return Metadata.EdmConstants.EdmStringTypeName; case TypeCode.Int32: return Metadata.EdmConstants.EdmInt32TypeName; case TypeCode.Double: return Metadata.EdmConstants.EdmDoubleTypeName; default: Debug.Assert(typeCode == TypeCode.Object, "If not one of the primitive types above, it must be an object in JSON."); break; } ODataComplexValue complexValue = payloadItem as ODataComplexValue; if (complexValue != null) { return complexValue.TypeName; } ODataCollectionValue collectionValue = payloadItem as ODataCollectionValue; if (collectionValue != null) { return collectionValue.TypeName; } ODataEntry entry = payloadItem as ODataEntry; if (entry != null) { return entry.TypeName; } throw new ODataException(o.Strings.General_InternalError(InternalErrorCodes.ODataJsonReader_ReadEntryStart)); } /// <summary> /// Converts the given JSON string value to the expected type as per OData conversion rules for JSON values. /// </summary> /// <param name="stringValue">String value to the converted.</param> /// <param name="targetType">Target type to which the string value needs to be converted.</param> /// <param name="version">The version of the payload being read.</param> /// <returns>Object which is in sync with the target type.</returns> private static object ConvertStringValue(string stringValue, Type targetType, ODataVersion version) { if (targetType == typeof(byte[])) { return Convert.FromBase64String(stringValue); } if (targetType == typeof(Guid)) { return new Guid(stringValue); } // Convert.ChangeType does not support TimeSpan. if (targetType == typeof(TimeSpan)) { return XmlConvert.ToTimeSpan(stringValue); } // Convert.ChangeType does not support DateTimeOffset. // Convert.ChangeType does support DateTime, and hence the ChangeType // call below should handle the DateTime case. if (targetType == typeof(DateTimeOffset)) { return XmlConvert.ToDateTimeOffset(stringValue); } // In Verbose JSON V3 the DateTime fomat is the ISO one, so we need to call XmlConvert instead of Convert // Convert doesn't read that value correctly (converts the result to Local kind always). if (targetType == typeof(DateTime) && version >= ODataVersion.V3) { try { return PlatformHelper.ConvertStringToDateTime(stringValue); } catch (FormatException) { // If the XmlConvert fails to convert we need to try Convert.ChangeType on the value anyway // so that we can still read values like MM/DD/YYYY which we supported just fine in V1/V2. } } // For string types, we support conversion to all possible primitive types return Convert.ChangeType(stringValue, targetType, CultureInfo.InvariantCulture); } /// <summary> /// Converts the given JSON int value to the expected type as per OData conversion rules for JSON values. /// </summary> /// <param name="intValue">Int32 value to the converted.</param> /// <param name="targetType">Target type to which the int value needs to be converted.</param> /// <param name="primitiveTypeReference">Type reference to which the value needs to be converted.</param> /// <param name="usesV1ProviderBehavior">true if the conversion should use the V1 provider behavior, false if the default behavior should be used.</param> /// <returns>Object which is in sync with the property type (modulo the V1 exception of converting numbers to non-compatible target types).</returns> private static object ConvertInt32Value(int intValue, Type targetType, IEdmPrimitiveTypeReference primitiveTypeReference, bool usesV1ProviderBehavior) { if (targetType == typeof(Int16)) { return Convert.ToInt16(intValue); } if (targetType == typeof(Byte)) { return Convert.ToByte(intValue); } if (targetType == typeof(SByte)) { return Convert.ToSByte(intValue); } if (targetType == typeof(Single)) { return Convert.ToSingle(intValue); } if (targetType == typeof(Double)) { return Convert.ToDouble(intValue); } if (targetType == typeof(Decimal) || targetType == typeof(Int64)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertInt64OrDecimal); } if (!IsV1PrimitiveType(targetType) || (targetType != typeof(Int32) && !usesV1ProviderBehavior)) { throw new ODataException(o.Strings.ODataJsonReaderUtils_CannotConvertInt32(primitiveTypeReference.ODataFullName())); } return intValue; } /// <summary> /// Checks if the given type is a V1 primitive type or not. /// </summary> /// <param name="targetType">Type instance.</param> /// <returns>True if the given target type is a V1 primitive type otherwise returns false.</returns> private static bool IsV1PrimitiveType(Type targetType) { if (targetType == typeof(DateTimeOffset) || targetType == typeof(TimeSpan)) { return false; } return true; } } }
using System; using System.Collections.Generic; using System.Reflection; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Installer; namespace Bmz.Framework.Dependency { /// <summary> /// This class is used to directly perform dependency injection tasks. /// </summary> public class IocManager : IIocManager { /// <summary> /// The Singleton instance. /// </summary> public static IocManager Instance { get; private set; } /// <summary> /// Reference to the Castle Windsor Container. /// </summary> public IWindsorContainer IocContainer { get; private set; } /// <summary> /// List of all registered conventional registrars. /// </summary> private readonly List<IConventionalDependencyRegistrar> _conventionalRegistrars; static IocManager() { Instance = new IocManager(); } /// <summary> /// Creates a new <see cref="IocManager"/> object. /// Normally, you don't directly instantiate an <see cref="IocManager"/>. /// This may be useful for test purposes. /// </summary> public IocManager() { IocContainer = new WindsorContainer(); _conventionalRegistrars = new List<IConventionalDependencyRegistrar>(); //Register self! IocContainer.Register( Component.For<IocManager, IIocManager, IIocRegistrar, IIocResolver>().UsingFactoryMethod(() => this) ); } /// <summary> /// Adds a dependency registrar for conventional registration. /// </summary> /// <param name="registrar">dependency registrar</param> public void AddConventionalRegistrar(IConventionalDependencyRegistrar registrar) { _conventionalRegistrars.Add(registrar); } /// <summary> /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method. /// </summary> /// <param name="assembly">Assembly to register</param> public void RegisterAssemblyByConvention(Assembly assembly) { RegisterAssemblyByConvention(assembly, new ConventionalRegistrationConfig()); } /// <summary> /// Registers types of given assembly by all conventional registrars. See <see cref="AddConventionalRegistrar"/> method. /// </summary> /// <param name="assembly">Assembly to register</param> /// <param name="config">Additional configuration</param> public void RegisterAssemblyByConvention(Assembly assembly, ConventionalRegistrationConfig config) { var context = new ConventionalRegistrationContext(assembly, this, config); foreach (var registerer in _conventionalRegistrars) { registerer.RegisterAssembly(context); } if (config.InstallInstallers) { IocContainer.Install(FromAssembly.Instance(assembly)); } } /// <summary> /// Registers a type as self registration. /// </summary> /// <typeparam name="TType">Type of the class</typeparam> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register<TType>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class { IocContainer.Register(ApplyLifestyle(Component.For<TType>(), lifeStyle)); } /// <summary> /// Registers a type as self registration. /// </summary> /// <param name="type">Type of the class</param> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register(Type type, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) { IocContainer.Register(ApplyLifestyle(Component.For(type), lifeStyle)); } /// <summary> /// Registers a type with it's implementation. /// </summary> /// <typeparam name="TType">Registering type</typeparam> /// <typeparam name="TImpl">The type that implements <see cref="TType"/></typeparam> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register<TType, TImpl>(DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) where TType : class where TImpl : class, TType { IocContainer.Register(ApplyLifestyle(Component.For<TType, TImpl>().ImplementedBy<TImpl>(), lifeStyle)); } /// <summary> /// Registers a type with it's implementation. /// </summary> /// <param name="type">Type of the class</param> /// <param name="impl">The type that implements <paramref name="type"/></param> /// <param name="lifeStyle">Lifestyle of the objects of this type</param> public void Register(Type type, Type impl, DependencyLifeStyle lifeStyle = DependencyLifeStyle.Singleton) { IocContainer.Register(ApplyLifestyle(Component.For(type, impl).ImplementedBy(impl), lifeStyle)); } /// <summary> /// Checks whether given type is registered before. /// </summary> /// <param name="type">Type to check</param> public bool IsRegistered(Type type) { return IocContainer.Kernel.HasComponent(type); } /// <summary> /// Checks whether given type is registered before. /// </summary> /// <typeparam name="TType">Type to check</typeparam> public bool IsRegistered<TType>() { return IocContainer.Kernel.HasComponent(typeof(TType)); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to get</typeparam> /// <returns>The instance object</returns> public T Resolve<T>() { return IocContainer.Resolve<T>(); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to cast</typeparam> /// <param name="type">Type of the object to resolve</param> /// <returns>The object instance</returns> public T Resolve<T>(Type type) { return (T)IocContainer.Resolve(type); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <typeparam name="T">Type of the object to get</typeparam> /// <param name="argumentsAsAnonymousType">Constructor arguments</param> /// <returns>The instance object</returns> public T Resolve<T>(object argumentsAsAnonymousType) { return IocContainer.Resolve<T>(argumentsAsAnonymousType); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <param name="type">Type of the object to get</param> /// <returns>The instance object</returns> public object Resolve(Type type) { return IocContainer.Resolve(type); } /// <summary> /// Gets an object from IOC container. /// Returning object must be Released (see <see cref="IIocResolver.Release"/>) after usage. /// </summary> /// <param name="type">Type of the object to get</param> /// <param name="argumentsAsAnonymousType">Constructor arguments</param> /// <returns>The instance object</returns> public object Resolve(Type type, object argumentsAsAnonymousType) { return IocContainer.Resolve(type, argumentsAsAnonymousType); } /// <summary> /// Releases a pre-resolved object. See Resolve methods. /// </summary> /// <param name="obj">Object to be released</param> public void Release(object obj) { IocContainer.Release(obj); } /// <inheritdoc/> public void Dispose() { IocContainer.Dispose(); } private static ComponentRegistration<T> ApplyLifestyle<T>(ComponentRegistration<T> registration, DependencyLifeStyle lifeStyle) where T : class { switch (lifeStyle) { case DependencyLifeStyle.Transient: return registration.LifestyleTransient(); case DependencyLifeStyle.Singleton: return registration.LifestyleSingleton(); default: return registration; } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: PoweredBy.cs 640 2009-06-01 17:22:02Z azizatif $")] namespace Elmah { #region Imports using System; using System.Reflection; using System.Web.UI; using System.Web.UI.WebControls; using Assembly = System.Reflection.Assembly; using HttpUtility = System.Web.HttpUtility; using Cache = System.Web.Caching.Cache; using CacheItemPriority = System.Web.Caching.CacheItemPriority; using HttpRuntime = System.Web.HttpRuntime; #endregion /// <summary> /// Displays a "Powered-by ELMAH" message that also contains the assembly /// file version informatin and copyright notice. /// </summary> public sealed class PoweredBy : WebControl { private AboutSet _about; /// <summary> /// Renders the contents of the control into the specified writer. /// </summary> protected override void RenderContents(HtmlTextWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); // // Write out the assembly title, version number, copyright and // license. // AboutSet about = this.About; writer.Write("Powered by "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://elmah.googlecode.com/"); writer.RenderBeginTag(HtmlTextWriterTag.A); HttpUtility.HtmlEncode(Mask.EmptyString(about.Product, "(product)"), writer); writer.RenderEndTag(); writer.Write(", version "); string version = about.GetFileVersionString(); if (version.Length == 0) version = about.GetVersionString(); HttpUtility.HtmlEncode(Mask.EmptyString(version, "?.?.?.?"), writer); #if DEBUG writer.Write(" (" + Build.Configuration + ")"); #endif writer.Write(". "); string copyright = about.Copyright; if (copyright.Length > 0) { HttpUtility.HtmlEncode(copyright, writer); writer.Write(' '); } writer.Write("Licensed under "); writer.AddAttribute(HtmlTextWriterAttribute.Href, "http://www.apache.org/licenses/LICENSE-2.0"); writer.RenderBeginTag(HtmlTextWriterTag.A); writer.Write("Apache License, Version 2.0"); writer.RenderEndTag(); writer.Write(". "); } private AboutSet About { get { string cacheKey = GetType().FullName; // // If cache is available then check if the version // information is already residing in there. // if (this.Cache != null) _about = (AboutSet) this.Cache[cacheKey]; // // Not found in the cache? Go out and get the version // information of the assembly housing this component. // if (_about == null) { // // NOTE: The assembly information is picked up from the // applied attributes rather that the more convenient // FileVersionInfo because the latter required elevated // permissions and may throw a security exception if // called from a partially trusted environment, such as // the medium trust level in ASP.NET. // AboutSet about = new AboutSet(); Assembly assembly = this.GetType().Assembly; about.Version = assembly.GetName().Version; AssemblyFileVersionAttribute version = (AssemblyFileVersionAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute)); if (version != null) about.FileVersion = new Version(version.Version); AssemblyProductAttribute product = (AssemblyProductAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyProductAttribute)); if (product != null) about.Product = product.Product; AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute) Attribute.GetCustomAttribute(assembly, typeof(AssemblyCopyrightAttribute)); if (copyright != null) about.Copyright = copyright.Copyright; // // Cache for next time if the cache is available. // if (this.Cache != null) { this.Cache.Add(cacheKey, about, /* absoluteExpiration */ null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(2), CacheItemPriority.Normal, null); } _about = about; } return _about; } } private Cache Cache { get { // // Get the cache from the container page, or failing that, // from the runtime. The Page property can be null // if the control has not been added to a page's controls // hierarchy. // return this.Page != null? this.Page.Cache : HttpRuntime.Cache; } } [ Serializable ] private sealed class AboutSet { private string _product; private Version _version; private Version _fileVersion; private string _copyright; public string Product { get { return _product ?? string.Empty; } set { _product = value; } } public Version Version { get { return _version; } set { _version = value; } } public string GetVersionString() { return _version != null ? _version.ToString() : string.Empty; } public Version FileVersion { get { return _fileVersion; } set { _fileVersion = value; } } public string GetFileVersionString() { return _fileVersion != null ? _fileVersion.ToString() : string.Empty; } public string Copyright { get { return _copyright ?? string.Empty; } set { _copyright = 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; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Diagnostics; using System.Collections; using System.ComponentModel; namespace System.Xml.Xsl.Runtime { /// <summary> /// Iterate over all child content nodes (this is different from the QIL Content operator, which iterates over content + attributes). /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct ContentIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the ContentIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the next child content node. Return true if such a child exists and /// set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToFirstChild(); return !_needFirst; } return _navCurrent.MoveToNext(); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all child elements with a matching name. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct ElementContentIterator { private string _localName, _ns; private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the ElementContentIterator. /// </summary> public void Create(XPathNavigator context, string localName, string ns) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _localName = localName; _ns = ns; _needFirst = true; } /// <summary> /// Position the iterator on the next child element with a matching name. Return true if such a child exists and /// set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToChild(_localName, _ns); return !_needFirst; } return _navCurrent.MoveToNext(_localName, _ns); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all child content nodes with a matching node kind. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct NodeKindContentIterator { private XPathNodeType _nodeType; private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the NodeKindContentIterator. /// </summary> public void Create(XPathNavigator context, XPathNodeType nodeType) { Debug.Assert(nodeType != XPathNodeType.Attribute && nodeType != XPathNodeType.Namespace); _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _nodeType = nodeType; _needFirst = true; } /// <summary> /// Position the iterator on the next child content node with a matching node kind. Return true if such a child /// exists and set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToChild(_nodeType); return !_needFirst; } return _navCurrent.MoveToNext(_nodeType); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all attributes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct AttributeIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the AttributeIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the attribute. Return true if such a child exists and set Current /// property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !_navCurrent.MoveToFirstAttribute(); return !_needFirst; } return _navCurrent.MoveToNextAttribute(); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all namespace nodes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct NamespaceIterator { private XPathNavigator _navCurrent; private XmlNavigatorStack _navStack; /// <summary> /// Initialize the NamespaceIterator. /// </summary> public void Create(XPathNavigator context) { // Push all of context's in-scope namespaces onto a stack in order to return them in document order // (MoveToXXXNamespace methods return namespaces in reverse document order) _navStack.Reset(); if (context.MoveToFirstNamespace(XPathNamespaceScope.All)) { do { // Don't return the default namespace undeclaration if (context.LocalName.Length != 0 || context.Value.Length != 0) _navStack.Push(context.Clone()); } while (context.MoveToNextNamespace(XPathNamespaceScope.All)); context.MoveToParent(); } } /// <summary> /// Pop the top namespace from the stack and save it as navCurrent. If there are no more namespaces, return false. /// </summary> public bool MoveNext() { if (_navStack.IsEmpty) return false; _navCurrent = _navStack.Pop(); return true; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over all attribute and child content nodes. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public struct AttributeContentIterator { private XPathNavigator _navCurrent; private bool _needFirst; /// <summary> /// Initialize the AttributeContentIterator. /// </summary> public void Create(XPathNavigator context) { _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, context); _needFirst = true; } /// <summary> /// Position the iterator on the next child content node with a matching node kind. Return true if such a child /// exists and set Current property. Otherwise, return false (Current property is undefined). /// </summary> public bool MoveNext() { if (_needFirst) { _needFirst = !XmlNavNeverFilter.MoveToFirstAttributeContent(_navCurrent); return !_needFirst; } return XmlNavNeverFilter.MoveToNextAttributeContent(_navCurrent); } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned true. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } } /// <summary> /// Iterate over child content nodes or following-sibling nodes. Maintain document order by using a stack. Input /// nodes are assumed to be in document order, but can contain one another (ContentIterator doesn't allow this). /// </summary> /// <remarks> /// 1. Assume that the list I of input nodes is in document order, with no duplicates. There are N nodes in list I. /// 2. For each node in list I, derive a list of nodes consisting of matching children or following-sibling nodes. /// Call these lists S(1)...S(N). /// 3. Let F be the first node in any list S(X), where X >= 1 and X < N /// 4. There exists exactly one contiguous sequence of lists S(Y)...S(Z), where Y > X and Z <= N, such that the lists /// S(X+1)...S(N) can be partitioned into these three groups: /// a. 1st group (S(X+1)...S(Y-1)) -- All nodes in these lists precede F in document order /// b. 2nd group (S(Y)...S(Z)) -- All nodes in these lists are duplicates of nodes in list S(X) /// c. 3rd group (> S(Z)) -- All nodes in these lists succeed F in document order /// 5. Given #4, node F can be returned once all nodes in the 1st group have been returned. Lists S(Y)...S(Z) can be /// discarded. And only a single node in the 3rd group need be generated in order to guarantee that all nodes in /// the 1st and 2nd groups have already been generated. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public struct ContentMergeIterator { private XmlNavigatorFilter _filter; private XPathNavigator _navCurrent, _navNext; private XmlNavigatorStack _navStack; private IteratorState _state; private enum IteratorState { NeedCurrent = 0, HaveCurrentNeedNext, HaveCurrentNoNext, HaveCurrentHaveNext, }; /// <summary> /// Initialize the ContentMergeIterator (merge multiple sets of content nodes in document order and remove duplicates). /// </summary> public void Create(XmlNavigatorFilter filter) { _filter = filter; _navStack.Reset(); _state = IteratorState.NeedCurrent; } /// <summary> /// Position this iterator to the next content or sibling node. Return IteratorResult.NoMoreNodes if there are /// no more content or sibling nodes. Return IteratorResult.NeedInputNode if the next input node needs to be /// fetched first. Return IteratorResult.HaveCurrent if the Current property is set to the next node in the /// iteration. /// </summary> public IteratorResult MoveNext(XPathNavigator input) { return MoveNext(input, true); } /// <summary> /// Position this iterator to the next content or sibling node. Return IteratorResult.NoMoreNodes if there are /// no more content or sibling nodes. Return IteratorResult.NeedInputNode if the next input node needs to be /// fetched first. Return IteratorResult.HaveCurrent if the Current property is set to the next node in the /// iteration. /// </summary> internal IteratorResult MoveNext(XPathNavigator input, bool isContent) { switch (_state) { case IteratorState.NeedCurrent: // If there are no more input nodes, then iteration is complete if (input == null) return IteratorResult.NoMoreNodes; // Save the input node as the current node _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, input); // If matching child or sibling is found, then we have a current node if (isContent ? _filter.MoveToContent(_navCurrent) : _filter.MoveToFollowingSibling(_navCurrent)) _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; case IteratorState.HaveCurrentNeedNext: if (input == null) { // There are no more input nodes, so enter HaveCurrentNoNext state and return Current _state = IteratorState.HaveCurrentNoNext; return IteratorResult.HaveCurrentNode; } // Save the input node as the next node _navNext = XmlQueryRuntime.SyncToNavigator(_navNext, input); // If matching child or sibling is found, if (isContent ? _filter.MoveToContent(_navNext) : _filter.MoveToFollowingSibling(_navNext)) { // Then compare position of current and next nodes _state = IteratorState.HaveCurrentHaveNext; return DocOrderMerge(); } // Input node does not result in matching child or sibling, so get next input node return IteratorResult.NeedInputNode; case IteratorState.HaveCurrentNoNext: case IteratorState.HaveCurrentHaveNext: // If the current node has no more matching siblings, if (isContent ? !_filter.MoveToNextContent(_navCurrent) : !_filter.MoveToFollowingSibling(_navCurrent)) { if (_navStack.IsEmpty) { if (_state == IteratorState.HaveCurrentNoNext) { // No more input nodes, so iteration is complete return IteratorResult.NoMoreNodes; } // Make navNext the new current node and fetch a new navNext _navCurrent = XmlQueryRuntime.SyncToNavigator(_navCurrent, _navNext); _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; } // Pop new current node from the stack _navCurrent = _navStack.Pop(); } // If there is no next node, then no need to call DocOrderMerge; just return the current node if (_state == IteratorState.HaveCurrentNoNext) return IteratorResult.HaveCurrentNode; // Compare positions of current and next nodes return DocOrderMerge(); } Debug.Assert(false, "Invalid IteratorState " + _state); return IteratorResult.NoMoreNodes; } /// <summary> /// Return the current result navigator. This is only defined after MoveNext() has returned IteratorResult.HaveCurrentNode. /// </summary> public XPathNavigator Current { get { return _navCurrent; } } /// <summary> /// If the context node-set returns a node that is contained in the subtree of the previous node, /// then returning children of each node in "natural" order may not correspond to document order. /// Therefore, in order to guarantee document order, keep a stack in order to push the sibling of /// ancestor nodes. These siblings will not be returned until all of the descendants' children are /// returned first. /// </summary> private IteratorResult DocOrderMerge() { XmlNodeOrder cmp; Debug.Assert(_state == IteratorState.HaveCurrentHaveNext); // Compare location of navCurrent with navNext cmp = _navCurrent.ComparePosition(_navNext); // If navCurrent is before navNext in document order, // If cmp = XmlNodeOrder.Unknown, then navCurrent is before navNext (since input is is doc order) if (cmp == XmlNodeOrder.Before || cmp == XmlNodeOrder.Unknown) { // Then navCurrent can be returned (it is guaranteed to be first in document order) return IteratorResult.HaveCurrentNode; } // If navCurrent is after navNext in document order, then delay returning navCurrent // Otherwise, discard navNext since it is positioned to the same node as navCurrent if (cmp == XmlNodeOrder.After) { _navStack.Push(_navCurrent); _navCurrent = _navNext; _navNext = null; } // Need next input node _state = IteratorState.HaveCurrentNeedNext; return IteratorResult.NeedInputNode; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Text; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; [assembly: System.Reflection.CustomAttributesTests.Data.Attr(77, name = "AttrSimple")] [assembly: System.Reflection.CustomAttributesTests.Data.Int32Attr(77, name = "Int32AttrSimple"), System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = "Int64AttrSimple"), System.Reflection.CustomAttributesTests.Data.StringAttr("hello", name = "StringAttrSimple"), System.Reflection.CustomAttributesTests.Data.EnumAttr(System.Reflection.CustomAttributesTests.Data.MyColorEnum.RED, name = "EnumAttrSimple"), System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(Object), name = "TypeAttrSimple")] [assembly: System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)] [assembly: System.Diagnostics.Debuggable((System.Diagnostics.DebuggableAttribute.DebuggingModes)263)] [assembly: System.CLSCompliant(false)] namespace System.Reflection.Tests { public class AssemblyCustomAttributeTest { //Test for custom Attribute of type Int32AttrSimple [Fact] public void Test_Int32AttrSimple() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int32Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type Int64Attr [Fact] public void Test_Int64Attr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Int64Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of TypeStringAttr [Fact] public void Test_StringAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.StringAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.StringAttr(\"hello\", name = \"StringAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of type EnumAttr [Fact] public void Test_EnumAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.EnumAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.EnumAttr((System.Reflection.CustomAttributesTests.Data.MyColorEnum)1, name = \"EnumAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of type TypeAttr [Fact] public void Test_TypeAttr() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.TypeAttr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type CompilationRelaxationsAttribute [Fact] public void Test_CompilationRelaxationsAttr() { bool result = false; Type attrType = typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute); string attrstr = "[System.Runtime.CompilerServices.CompilationRelaxationsAttribute((Int32)8)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type AssemblyTitleAttribute [Fact] public void Test_AssemblyIdentityAttr() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyTitleAttribute); string attrstr = "[System.Reflection.AssemblyTitleAttribute(\"System.Reflection.Tests\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type AssemblyDescriptionAttribute [Fact] public void Test_AssemblyDescriptionAttribute() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyDescriptionAttribute); string attrstr = "[System.Reflection.AssemblyDescriptionAttribute(\"System.Reflection.Tests\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type AssemblyCompanyAttribute [Fact] public void Test_AssemblyCompanyAttribute() { bool result = false; Type attrType = typeof(System.Reflection.AssemblyCompanyAttribute); string attrstr = "[System.Reflection.AssemblyCompanyAttribute(\"Microsoft Corporation\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type CLSCompliantAttribute [Fact] public void Test_CLSCompliantAttribute() { bool result = false; Type attrType = typeof(System.CLSCompliantAttribute); string attrstr = "[System.CLSCompliantAttribute((Boolean)True)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of Type DebuggableAttribute [Fact] public void Test_DebuggableAttribute() { bool result = false; Type attrType = typeof(System.Diagnostics.DebuggableAttribute); string attrstr = "[System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute+DebuggingModes)263)]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } //Test for custom Attribute of type Attribute [Fact] public void Test_SimpleAttribute() { bool result = false; Type attrType = typeof(System.Reflection.CustomAttributesTests.Data.Attr); string attrstr = "[System.Reflection.CustomAttributesTests.Data.Attr((Int32)77, name = \"AttrSimple\")]"; result = VerifyCustomAttribute(attrType, attrstr); Assert.True(result, string.Format("Did not find custom attribute of type {0} ", attrType)); } private static bool VerifyCustomAttribute(Type type, String attributeStr) { Assembly asm = GetExecutingAssembly(); IEnumerator<CustomAttributeData> customAttrs = asm.CustomAttributes.GetEnumerator(); CustomAttributeData current = null; bool result = false; while (customAttrs.MoveNext()) { current = customAttrs.Current; if (current.AttributeType.Equals(type)) { result = true; break; } } return result; } public static Assembly GetExecutingAssembly() { Assembly asm = null; Type t = typeof(AssemblyCustomAttributeTest); TypeInfo ti = t.GetTypeInfo(); asm = ti.Assembly; return asm; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrInt64() { var test = new SimpleBinaryOpTest__OrInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrInt64 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static SimpleBinaryOpTest__OrInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__OrInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Or( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Or( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Or( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Or), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse2.Or(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__OrInt64(); var result = Sse2.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if ((long)(left[0] | right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((long)(left[i] | right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Or)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // 2010-08-13 Sky Sanders - Modified for Silverlight 3/4 and Windows Phone 7 using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> internal class Deflater { #region Deflater Documentation /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,--------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ #endregion #region Public Constants /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public const int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public const int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public const int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public const int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public const int DEFLATED = 8; #endregion #region Local Constants private const int IS_SETDICT = 0x01; private const int IS_FLUSHING = 0x04; private const int IS_FINISHING = 0x08; private const int INIT_STATE = 0x00; private const int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private const int BUSY_STATE = 0x10; private const int FLUSHING_STATE = 0x14; private const int FINISHING_STATE = 0x1c; private const int FINISHED_STATE = 0x1e; private const int CLOSED_STATE = 0x7f; #endregion #region Constructors /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level) : this(level, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noZlibHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noZlibHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } #endregion /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public long TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= (IS_FLUSHING | IS_FINISHING); } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return (state == FINISHED_STATE) && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="offset"> /// the start of the data. /// </param> /// <param name="count"> /// the number of data bytes of input. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was Finish()ed or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int offset, int count) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("Finish() already called"); } engine.SetInput(input, offset, count); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="level"> /// the new compression level. /// </param> public void SetLevel(int level) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } if (this.level != level) { this.level = level; engine.SetLevel(level); } } /// <summary> /// Get current compression level /// </summary> /// <returns>Returns the current compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// SetLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// IsNeedingInput() or IsFinished returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If Finish() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { // output header int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { // Dictionary was set header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (;;) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { if (state == BUSY_STATE) { // We need more input now return origLength - length; } else if (state == FLUSHING_STATE) { if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; } else if (state == FINISHING_STATE) { pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noZlibHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dictionary"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if SetInput () or Deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary) { SetDictionary(dictionary, 0, dictionary.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dictionary"> /// The dictionary data /// </param> /// <param name="index"> /// The index where dictionary information commences. /// </param> /// <param name="count"> /// The number of bytes in the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// If SetInput () or Deflate() were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dictionary, int index, int count) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dictionary, index, count); } #region Instance Fields /// <summary> /// Compression level. /// </summary> int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> bool noZlibHeaderOrFooter; /// <summary> /// The current state. /// </summary> int state; /// <summary> /// The total bytes of output written. /// </summary> long totalOut; /// <summary> /// The pending output. /// </summary> DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> DeflaterEngine engine; #endregion } }
/// <summary>************************************************************************** /// /// $Id: ColorSpaceMapper.java,v 1.2 2002/07/25 16:30:55 grosbois Exp $ /// /// Copyright Eastman Kodak Company, 343 State Street, Rochester, NY 14650 /// $Date $ /// *************************************************************************** /// </summary> using System; using CSJ2K.j2k.image; using CSJ2K.j2k.util; using CSJ2K.Icc; namespace CSJ2K.Color { /// <summary> This is the base class for all modules in the colorspace and icc /// profiling steps of the decoding chain. It is responsible for the /// allocation and iniitialization of all working storage. It provides /// several utilities which are of generic use in preparing DataBlks /// for use and provides default implementations for the getCompData /// and getInternCompData methods. /// /// </summary> /// <seealso cref="jj2000.j2k.colorspace.ColorSpace"> /// </seealso> /// <version> 1.0 /// </version> /// <author> Bruce A. Kern /// </author> public abstract class ColorSpaceMapper:ImgDataAdapter, BlkImgDataSrc { private void InitBlock() { computed = new ComputedComponents(this); } /// <summary> Returns the parameters that are used in this class and implementing /// classes. It returns a 2D String array. Each of the 1D arrays is for a /// different option, and they have 3 elements. The first element is the /// option name, the second one is the synopsis and the third one is a long /// description of what the parameter is. The synopsis or description may /// be 'null', in which case it is assumed that there is no synopsis or /// description of the option, respectively. Null may be returned if no /// options are supported. /// /// </summary> /// <returns> the options name, their synopsis and their explanation, or null /// if no options are supported. /// /// </returns> public static System.String[][] ParameterInfo { get { return pinfo; } } /// <summary> Arrange for the input DataBlk to receive an /// appropriately sized and typed data buffer /// </summary> /// <param name="db">input DataBlk /// </param> /// <seealso cref="jj2000.j2k.image.DataBlk"> /// </seealso> protected internal static DataBlk InternalBuffer { set { switch (value.DataType) { case DataBlk.TYPE_INT: if (value.Data == null || ((int[]) value.Data).Length < value.w * value.h) value.Data = new int[value.w * value.h]; break; case DataBlk.TYPE_FLOAT: if (value.Data == null || ((float[]) value.Data).Length < value.w * value.h) { value.Data = new float[value.w * value.h]; } break; default: throw new System.ArgumentException("Invalid output datablock" + " type"); } } } /// <summary>The prefix for ICC Profiler options </summary> public const char OPT_PREFIX = 'I'; /// <summary>Platform dependant end of line String. </summary> //UPGRADE_NOTE: Final was removed from the declaration of 'eol '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" protected internal static readonly System.String eol = System.Environment.NewLine; // Temporary data buffers needed during profiling. protected internal DataBlkInt[] inInt; // Integer input data. protected internal DataBlkFloat[] inFloat; // Floating point input data. protected internal DataBlkInt[] workInt; // Input data shifted to zero-offset protected internal DataBlkFloat[] workFloat; // Input data shifted to zero-offset. protected internal int[][] dataInt; // Points to input data. protected internal float[][] dataFloat; // Points to input data. protected internal float[][] workDataFloat; // References working data pixels. protected internal int[][] workDataInt; // References working data pixels. /* input data parameters by component */ protected internal int[] shiftValueArray = null; protected internal int[] maxValueArray = null; protected internal int[] fixedPtBitsArray = null; /// <summary>The list of parameters that are accepted for ICC profiling.</summary> //UPGRADE_NOTE: Final was removed from the declaration of 'pinfo'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" private static readonly System.String[][] pinfo = new System.String[][]{new System.String[]{"IcolorSpacedebug", null, "Print debugging messages during colorspace mapping.", "off"}}; /// <summary>Parameter Specs </summary> protected internal ParameterList pl = null; /// <summary>ColorSpace info </summary> protected internal ColorSpace csMap = null; /// <summary>Number of image components </summary> protected internal int ncomps = 0; /// <summary>The image source. </summary> protected internal BlkImgDataSrc src = null; /// <summary>The image source data per component. </summary> protected internal DataBlk[] srcBlk = null; //UPGRADE_NOTE: Field 'EnclosingInstance' was added to class 'ComputedComponents' to access its enclosing instance. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1019'" protected internal class ComputedComponents { private void InitBlock(ColorSpaceMapper enclosingInstance) { this.enclosingInstance = enclosingInstance; } private ColorSpaceMapper enclosingInstance; public ColorSpaceMapper Enclosing_Instance { get { return enclosingInstance; } } //private int tIdx = - 1; private int h = - 1; private int w = - 1; private int ulx = - 1; private int uly = - 1; private int offset = - 1; private int scanw = - 1; public ComputedComponents(ColorSpaceMapper enclosingInstance) { InitBlock(enclosingInstance); clear(); } public ComputedComponents(ColorSpaceMapper enclosingInstance, DataBlk db) { InitBlock(enclosingInstance); set_Renamed(db); } public virtual void set_Renamed(DataBlk db) { h = db.h; w = db.w; ulx = db.ulx; uly = db.uly; offset = db.offset; scanw = db.scanw; } public virtual void clear() { h = w = ulx = uly = offset = scanw = - 1; } public bool Equals(ComputedComponents cc) { return (h == cc.h && w == cc.w && ulx == cc.ulx && uly == cc.uly && offset == cc.offset && scanw == cc.scanw); } /* end class ComputedComponents */ } //UPGRADE_NOTE: The initialization of 'computed' was moved to method 'InitBlock'. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1005'" protected internal ComputedComponents computed; /// <summary> Copy the DataBlk geometry from source to target /// DataBlk and assure that the target has an appropriate /// data buffer. /// </summary> /// <param name="tgt">has its geometry set. /// </param> /// <param name="src">used to get the new geometric parameters. /// </param> protected internal static void copyGeometry(DataBlk tgt, DataBlk src) { tgt.offset = 0; tgt.h = src.h; tgt.w = src.w; tgt.ulx = src.ulx; tgt.uly = src.uly; tgt.scanw = src.w; // Create data array if necessary InternalBuffer = tgt; } /// <summary> Factory method for creating instances of this class.</summary> /// <param name="src">-- source of image data /// </param> /// <param name="csMap">-- provides colorspace info /// </param> /// <returns> ColorSpaceMapper instance /// </returns> /// <exception cref="IOException">profile access exception /// </exception> public static BlkImgDataSrc createInstance(BlkImgDataSrc src, ColorSpace csMap) { // Check parameters csMap.pl.checkList(OPT_PREFIX, CSJ2K.j2k.util.ParameterList.toNameArray(pinfo)); // Perform ICCProfiling or ColorSpace tranfsormation. if (csMap.Method == ColorSpace.MethodEnum.ICC_PROFILED) { return ICCProfiler.createInstance(src, csMap); } else { ColorSpace.CSEnum colorspace = csMap.getColorSpace(); if (colorspace == ColorSpace.CSEnum.sRGB) { return EnumeratedColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.GreyScale) { return EnumeratedColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.sYCC) { return SYccColorSpaceMapper.createInstance(src, csMap); } if (colorspace == ColorSpace.CSEnum.esRGB) { return EsRgbColorSpaceMapper.createInstance(src, csMap); } else if (colorspace == ColorSpace.CSEnum.Unknown) { return null; } else { throw new ColorSpaceException("Bad color space specification in image"); } } } /// <summary> Ctor which creates an ICCProfile for the image and initializes /// all data objects (input, working, and output). /// /// </summary> /// <param name="src">-- Source of image data /// </param> /// <param name="csm">-- provides colorspace info /// /// </param> protected internal ColorSpaceMapper(BlkImgDataSrc src, ColorSpace csMap):base(src) { InitBlock(); this.src = src; this.csMap = csMap; initialize(); /* end ColorSpaceMapper ctor */ } /// <summary>General utility used by ctors </summary> private void initialize() { this.pl = csMap.pl; this.ncomps = src.NumComps; shiftValueArray = new int[ncomps]; maxValueArray = new int[ncomps]; fixedPtBitsArray = new int[ncomps]; srcBlk = new DataBlk[ncomps]; inInt = new DataBlkInt[ncomps]; inFloat = new DataBlkFloat[ncomps]; workInt = new DataBlkInt[ncomps]; workFloat = new DataBlkFloat[ncomps]; dataInt = new int[ncomps][]; dataFloat = new float[ncomps][]; workDataInt = new int[ncomps][]; workDataFloat = new float[ncomps][]; dataInt = new int[ncomps][]; dataFloat = new float[ncomps][]; /* For each component, get a reference to the pixel data and * set up working DataBlks for both integer and float output. */ for (int i = 0; i < ncomps; ++i) { shiftValueArray[i] = 1 << (src.getNomRangeBits(i) - 1); maxValueArray[i] = (1 << src.getNomRangeBits(i)) - 1; fixedPtBitsArray[i] = src.getFixedPoint(i); inInt[i] = new DataBlkInt(); inFloat[i] = new DataBlkFloat(); workInt[i] = new DataBlkInt(); workInt[i].progressive = inInt[i].progressive; workFloat[i] = new DataBlkFloat(); workFloat[i].progressive = inFloat[i].progressive; } } /// <summary> Returns the number of bits, referred to as the "range bits", /// corresponding to the nominal range of the data in the specified /// component. If this number is <i>b</b> then for unsigned data the /// nominal range is between 0 and 2^b-1, and for signed data it is between /// -2^(b-1) and 2^(b-1)-1. For floating point data this value is not /// applicable. /// /// </summary> /// <param name="c">The index of the component. /// /// </param> /// <returns> The number of bits corresponding to the nominal range of the /// data. Fro floating-point data this value is not applicable and the /// return value is undefined. /// </returns> public virtual int getFixedPoint(int c) { return src.getFixedPoint(c); } /// <summary> Returns, in the blk argument, a block of image data containing the /// specifed rectangular area, in the specified component. The data is /// returned, as a copy of the internal data, therefore the returned data /// can be modified "in place". /// /// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w' /// and 'h' members of the 'blk' argument, relative to the current /// tile. These members are not modified by this method. The 'offset' of /// the returned data is 0, and the 'scanw' is the same as the block's /// width. See the 'DataBlk' class. /// /// <P>This method, in general, is less efficient than the /// 'getInternCompData()' method since, in general, it copies the /// data. However if the array of returned data is to be modified by the /// caller then this method is preferable. /// /// <P>If the data array in 'blk' is 'null', then a new one is created. If /// the data array is not 'null' then it is reused, and it must be large /// enough to contain the block's data. Otherwise an 'ArrayStoreException' /// or an 'IndexOutOfBoundsException' is thrown by the Java system. /// /// <P>The returned data may have its 'progressive' attribute set. In this /// case the returned data is only an approximation of the "final" data. /// /// </summary> /// <param name="blk">Its coordinates and dimensions specify the area to return, /// relative to the current tile. If it contains a non-null data array, /// then it must be large enough. If it contains a null data array a new /// one is created. Some fields in this object are modified to return the /// data. /// /// </param> /// <param name="c">The index of the component from which to get the data. /// /// </param> /// <seealso cref="getInternCompData"> /// /// </seealso> public virtual DataBlk getCompData(DataBlk out_Renamed, int c) { return src.getCompData(out_Renamed, c); } /// <summary> Returns, in the blk argument, a block of image data containing the /// specifed rectangular area, in the specified component. The data is /// returned, as a reference to the internal data, if any, instead of as a /// copy, therefore the returned data should not be modified. /// /// <P>The rectangular area to return is specified by the 'ulx', 'uly', 'w' /// and 'h' members of the 'blk' argument, relative to the current /// tile. These members are not modified by this method. The 'offset' and /// 'scanw' of the returned data can be arbitrary. See the 'DataBlk' class. /// /// <P>This method, in general, is more efficient than the 'getCompData()' /// method since it may not copy the data. However if the array of returned /// data is to be modified by the caller then the other method is probably /// preferable. /// /// <P>If possible, the data in the returned 'DataBlk' should be the /// internal data itself, instead of a copy, in order to increase the data /// transfer efficiency. However, this depends on the particular /// implementation (it may be more convenient to just return a copy of the /// data). This is the reason why the returned data should not be modified. /// /// <P>If the data array in <tt>blk</tt> is <tt>null</tt>, then a new one /// is created if necessary. The implementation of this interface may /// choose to return the same array or a new one, depending on what is more /// efficient. Therefore, the data array in <tt>blk</tt> prior to the /// method call should not be considered to contain the returned data, a /// new array may have been created. Instead, get the array from /// <tt>blk</tt> after the method has returned. /// /// <P>The returned data may have its 'progressive' attribute set. In this /// case the returned data is only an approximation of the "final" data. /// /// </summary> /// <param name="blk">Its coordinates and dimensions specify the area to return, /// relative to the current tile. Some fields in this object are modified /// to return the data. /// /// </param> /// <param name="c">The index of the component from which to get the data. /// /// </param> /// <returns> The requested DataBlk /// /// </returns> /// <seealso cref="getCompData"> /// /// </seealso> public virtual DataBlk getInternCompData(DataBlk out_Renamed, int c) { return src.getInternCompData(out_Renamed, c); } /* end class ColorSpaceMapper */ } }
/* * 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.IO; using System.Reflection; using System.Text; using System.Timers; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Statistics; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim { /// <summary> /// Interactive OpenSim region server /// </summary> public class OpenSim : OpenSimBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected string m_startupCommandsFile; protected string m_shutdownCommandsFile; protected bool m_gui = false; protected string m_consoleType = "local"; protected uint m_consolePort = 0; private string m_timedScript = "disabled"; private Timer m_scriptTimer; public OpenSim(IConfigSource configSource) : base(configSource) { } protected override void ReadExtraConfigSettings() { base.ReadExtraConfigSettings(); IConfig startupConfig = m_config.Source.Configs["Startup"]; IConfig networkConfig = m_config.Source.Configs["Network"]; int stpMaxThreads = 15; if (startupConfig != null) { m_startupCommandsFile = startupConfig.GetString("startup_console_commands_file", "startup_commands.txt"); m_shutdownCommandsFile = startupConfig.GetString("shutdown_console_commands_file", "shutdown_commands.txt"); if (startupConfig.GetString("console", String.Empty) == String.Empty) m_gui = startupConfig.GetBoolean("gui", false); else m_consoleType= startupConfig.GetString("console", String.Empty); if (networkConfig != null) m_consolePort = (uint)networkConfig.GetInt("console_port", 0); m_timedScript = startupConfig.GetString("timer_Script", "disabled"); if (m_logFileAppender != null) { if (m_logFileAppender is log4net.Appender.FileAppender) { log4net.Appender.FileAppender appender = (log4net.Appender.FileAppender)m_logFileAppender; string fileName = startupConfig.GetString("LogFile", String.Empty); if (fileName != String.Empty) { appender.File = fileName; appender.ActivateOptions(); } m_log.InfoFormat("[LOGGING]: Logging started to file {0}", appender.File); } } string asyncCallMethodStr = startupConfig.GetString("async_call_method", String.Empty); FireAndForgetMethod asyncCallMethod; if (!String.IsNullOrEmpty(asyncCallMethodStr) && Utils.EnumTryParse<FireAndForgetMethod>(asyncCallMethodStr, out asyncCallMethod)) Util.FireAndForgetMethod = asyncCallMethod; stpMaxThreads = startupConfig.GetInt("MaxPoolThreads", 15); } if (Util.FireAndForgetMethod == FireAndForgetMethod.SmartThreadPool) Util.InitThreadPool(stpMaxThreads); m_log.Info("[OPENSIM MAIN]: Using async_call_method " + Util.FireAndForgetMethod); } /// <summary> /// Performs initialisation of the scene, such as loading configuration from disk. /// </summary> protected override void StartupSpecific() { m_log.Info("===================================================================="); m_log.Info("========================= STARTING OPENSIM ========================="); m_log.Info("===================================================================="); //m_log.InfoFormat("[OPENSIM MAIN]: GC Is Server GC: {0}", GCSettings.IsServerGC.ToString()); // http://msdn.microsoft.com/en-us/library/bb384202.aspx //GCSettings.LatencyMode = GCLatencyMode.Batch; //m_log.InfoFormat("[OPENSIM MAIN]: GC Latency Mode: {0}", GCSettings.LatencyMode.ToString()); if (m_gui) // Driven by external GUI m_console = new CommandConsole("Region"); else { switch (m_consoleType) { case "basic": m_console = new CommandConsole("Region"); break; case "rest": m_console = new RemoteConsole("Region"); ((RemoteConsole)m_console).ReadConfig(m_config.Source); break; default: m_console = new LocalConsole("Region"); break; } } MainConsole.Instance = m_console; RegisterConsoleCommands(); base.StartupSpecific(); MainServer.Instance.AddStreamHandler(new OpenSim.SimStatusHandler()); MainServer.Instance.AddStreamHandler(new OpenSim.XSimStatusHandler(this)); if (userStatsURI != String.Empty) MainServer.Instance.AddStreamHandler(new OpenSim.UXSimStatusHandler(this)); if (m_console is RemoteConsole) { if (m_consolePort == 0) { ((RemoteConsole)m_console).SetServer(m_httpServer); } else { ((RemoteConsole)m_console).SetServer(MainServer.GetHttpServer(m_consolePort)); } } //Run Startup Commands if (String.IsNullOrEmpty(m_startupCommandsFile)) { m_log.Info("[STARTUP]: No startup command script specified. Moving on..."); } else { RunCommandScript(m_startupCommandsFile); } // Start timer script (run a script every xx seconds) if (m_timedScript != "disabled") { m_scriptTimer = new Timer(); m_scriptTimer.Enabled = true; m_scriptTimer.Interval = 1200*1000; m_scriptTimer.Elapsed += RunAutoTimerScript; } // Hook up to the watchdog timer Watchdog.OnWatchdogTimeout += WatchdogTimeoutHandler; PrintFileToConsole("startuplogo.txt"); // For now, start at the 'root' level by default if (m_sceneManager.Scenes.Count == 1) // If there is only one region, select it ChangeSelectedRegion("region", new string[] {"change", "region", m_sceneManager.Scenes[0].RegionInfo.RegionName}); else ChangeSelectedRegion("region", new string[] {"change", "region", "root"}); } /// <summary> /// Register standard set of region console commands /// </summary> private void RegisterConsoleCommands() { m_console.Commands.AddCommand("region", false, "clear assets", "clear assets", "Clear the asset cache", HandleClearAssets); m_console.Commands.AddCommand("region", false, "force update", "force update", "Force the update of all objects on clients", HandleForceUpdate); m_console.Commands.AddCommand("region", false, "debug packet", "debug packet <level>", "Turn on packet debugging", "If level > 255 then all incoming and outgoing packets are logged.\n" + "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n" + "If level <= 200 then incoming RequestImage and outgoing ImagePacket, ImageData, LayerData and CoarseLocationUpdate packets are not logged.\n" + "If level <= 100 then incoming ViewerEffect and AgentAnimation and outgoing ViewerEffect and AvatarAnimation packets are not logged.\n" + "If level <= 50 then outgoing ImprovedTerseObjectUpdate packets are not logged.\n" + "If level <= 0 then no packets are logged.", Debug); m_console.Commands.AddCommand("region", false, "debug scene", "debug scene <cripting> <collisions> <physics>", "Turn on scene debugging", Debug); m_console.Commands.AddCommand("region", false, "change region", "change region <region name>", "Change current console region", ChangeSelectedRegion); m_console.Commands.AddCommand("region", false, "save xml", "save xml", "Save a region's data in XML format", SaveXml); m_console.Commands.AddCommand("region", false, "save xml2", "save xml2", "Save a region's data in XML2 format", SaveXml2); m_console.Commands.AddCommand("region", false, "load xml", "load xml [-newIDs [<x> <y> <z>]]", "Load a region's data from XML format", LoadXml); m_console.Commands.AddCommand("region", false, "load xml2", "load xml2", "Load a region's data from XML2 format", LoadXml2); m_console.Commands.AddCommand("region", false, "save prims xml2", "save prims xml2 [<prim name> <file name>]", "Save named prim to XML2", SavePrimsXml2); m_console.Commands.AddCommand("region", false, "load oar", "load oar [--merge] [--skip-assets] [<OAR path>]", "Load a region's data from an OAR archive.", "--merge will merge the OAR with the existing scene." + Environment.NewLine + "--skip-assets will load the OAR but ignore the assets it contains." + Environment.NewLine + "The path can be either a filesystem location or a URI." + " If this is not given then the command looks for an OAR named region.oar in the current directory.", LoadOar); m_console.Commands.AddCommand("region", false, "save oar", //"save oar [-v|--version=<N>] [-p|--profile=<url>] [<OAR path>]", "save oar [-p|--profile=<url>] [<OAR path>]", "Save a region's data to an OAR archive.", // "-v|--version=<N> generates scene objects as per older versions of the serialization (e.g. -v=0)" + Environment.NewLine "-p|--profile=<url> adds the url of the profile service to the saved user information" + Environment.NewLine + "The OAR path must be a filesystem path." + " If this is not given then the oar is saved to region.oar in the current directory.", SaveOar); m_console.Commands.AddCommand("region", false, "edit scale", "edit scale <name> <x> <y> <z>", "Change the scale of a named prim", HandleEditScale); m_console.Commands.AddCommand("region", false, "kick user", "kick user <first> <last> [message]", "Kick a user off the simulator", KickUserCommand); m_console.Commands.AddCommand("region", false, "show users", "show users [full]", "Show user data for users currently on the region", "Without the 'full' option, only users actually on the region are shown." + " With the 'full' option child agents of users in neighbouring regions are also shown.", HandleShow); m_console.Commands.AddCommand("region", false, "show connections", "show connections", "Show connection data", HandleShow); m_console.Commands.AddCommand("region", false, "show circuits", "show circuits", "Show agent circuit data", HandleShow); m_console.Commands.AddCommand("region", false, "show http-handlers", "show http-handlers", "Show all registered http handlers", HandleShow); m_console.Commands.AddCommand("region", false, "show pending-objects", "show pending-objects", "Show # of objects on the pending queues of all scene viewers", HandleShow); m_console.Commands.AddCommand("region", false, "show modules", "show modules", "Show module data", HandleShow); m_console.Commands.AddCommand("region", false, "show regions", "show regions", "Show region data", HandleShow); m_console.Commands.AddCommand("region", false, "show ratings", "show ratings", "Show rating data", HandleShow); m_console.Commands.AddCommand("region", false, "backup", "backup", "Persist objects to the database now", RunCommand); m_console.Commands.AddCommand("region", false, "create region", "create region [\"region name\"] <region_file.ini>", "Create a new region.", "The settings for \"region name\" are read from <region_file.ini>. Paths specified with <region_file.ini> are relative to your Regions directory, unless an absolute path is given." + " If \"region name\" does not exist in <region_file.ini>, it will be added." + Environment.NewLine + "Without \"region name\", the first region found in <region_file.ini> will be created." + Environment.NewLine + "If <region_file.ini> does not exist, it will be created.", HandleCreateRegion); m_console.Commands.AddCommand("region", false, "restart", "restart", "Restart all sims in this instance", RunCommand); m_console.Commands.AddCommand("region", false, "config set", "config set <section> <key> <value>", "Set a config option. In most cases this is not useful since changed parameters are not dynamically reloaded. Neither do changed parameters persist - you will have to change a config file manually and restart.", HandleConfig); m_console.Commands.AddCommand("region", false, "config get", "config get [<section>] [<key>]", "Synonym for config show", HandleConfig); m_console.Commands.AddCommand("region", false, "config show", "config show [<section>] [<key>]", "Show config information", "If neither section nor field are specified, then the whole current configuration is printed." + Environment.NewLine + "If a section is given but not a field, then all fields in that section are printed.", HandleConfig); m_console.Commands.AddCommand("region", false, "config save", "config save <path>", "Save current configuration to a file at the given path", HandleConfig); m_console.Commands.AddCommand("region", false, "command-script", "command-script <script>", "Run a command script from file", RunCommand); m_console.Commands.AddCommand("region", false, "remove-region", "remove-region <name>", "Remove a region from this simulator", RunCommand); m_console.Commands.AddCommand("region", false, "delete-region", "delete-region <name>", "Delete a region from disk", RunCommand); m_console.Commands.AddCommand("region", false, "modules list", "modules list", "List modules", HandleModules); m_console.Commands.AddCommand("region", false, "modules load", "modules load <name>", "Load a module", HandleModules); m_console.Commands.AddCommand("region", false, "modules unload", "modules unload <name>", "Unload a module", HandleModules); m_console.Commands.AddCommand("region", false, "Add-InventoryHost", "Add-InventoryHost <host>", String.Empty, RunCommand); m_console.Commands.AddCommand("region", false, "kill uuid", "kill uuid <UUID>", "Kill an object by UUID", KillUUID); } public override void ShutdownSpecific() { if (m_shutdownCommandsFile != String.Empty) { RunCommandScript(m_shutdownCommandsFile); } base.ShutdownSpecific(); } /// <summary> /// Timer to run a specific text file as console commands. Configured in in the main ini file /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RunAutoTimerScript(object sender, EventArgs e) { if (m_timedScript != "disabled") { RunCommandScript(m_timedScript); } } private void WatchdogTimeoutHandler(System.Threading.Thread thread, int lastTick) { int now = Environment.TickCount & Int32.MaxValue; m_log.ErrorFormat("[WATCHDOG]: Timeout detected for thread \"{0}\". ThreadState={1}. Last tick was {2}ms ago", thread.Name, thread.ThreadState, now - lastTick); } #region Console Commands /// <summary> /// Kicks users off the region /// </summary> /// <param name="module"></param> /// <param name="cmdparams">name of avatar to kick</param> private void KickUserCommand(string module, string[] cmdparams) { if (cmdparams.Length < 4) return; string alert = null; if (cmdparams.Length > 4) alert = String.Format("\n{0}\n", String.Join(" ", cmdparams, 4, cmdparams.Length - 4)); IList agents = m_sceneManager.GetCurrentSceneAvatars(); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; if (presence.Firstname.ToLower().Contains(cmdparams[2].ToLower()) && presence.Lastname.ToLower().Contains(cmdparams[3].ToLower())) { MainConsole.Instance.Output( String.Format( "Kicking user: {0,-16} {1,-16} {2,-37} in region: {3,-16}", presence.Firstname, presence.Lastname, presence.UUID, regionInfo.RegionName)); // kick client... if (alert != null) presence.ControllingClient.Kick(alert); else presence.ControllingClient.Kick("\nThe OpenSim manager kicked you out.\n"); // ...and close on our side presence.Scene.IncomingCloseAgent(presence.UUID); } } MainConsole.Instance.Output(""); } /// <summary> /// Run an optional startup list of commands /// </summary> /// <param name="fileName"></param> private void RunCommandScript(string fileName) { if (File.Exists(fileName)) { m_log.Info("[COMMANDFILE]: Running " + fileName); using (StreamReader readFile = File.OpenText(fileName)) { string currentCommand; while ((currentCommand = readFile.ReadLine()) != null) { if (currentCommand != String.Empty) { m_log.Info("[COMMANDFILE]: Running '" + currentCommand + "'"); m_console.RunCommand(currentCommand); } } } } } /// <summary> /// Opens a file and uses it as input to the console command parser. /// </summary> /// <param name="fileName">name of file to use as input to the console</param> private static void PrintFileToConsole(string fileName) { if (File.Exists(fileName)) { StreamReader readFile = File.OpenText(fileName); string currentLine; while ((currentLine = readFile.ReadLine()) != null) { m_log.Info("[!]" + currentLine); } } } private void HandleClearAssets(string module, string[] args) { MainConsole.Instance.Output("Not implemented."); } /// <summary> /// Force resending of all updates to all clients in active region(s) /// </summary> /// <param name="module"></param> /// <param name="args"></param> private void HandleForceUpdate(string module, string[] args) { MainConsole.Instance.Output("Updating all clients"); m_sceneManager.ForceCurrentSceneClientUpdate(); } /// <summary> /// Edits the scale of a primative with the name specified /// </summary> /// <param name="module"></param> /// <param name="args">0,1, name, x, y, z</param> private void HandleEditScale(string module, string[] args) { if (args.Length == 6) { m_sceneManager.HandleEditCommandOnCurrentScene(args); } else { MainConsole.Instance.Output("Argument error: edit scale <prim name> <x> <y> <z>"); } } /// <summary> /// Creates a new region based on the parameters specified. This will ask the user questions on the console /// </summary> /// <param name="module"></param> /// <param name="cmd">0,1,region name, region ini or XML file</param> private void HandleCreateRegion(string module, string[] cmd) { string regionName = string.Empty; string regionFile = string.Empty; if (cmd.Length == 3) { regionFile = cmd[2]; } else if (cmd.Length > 3) { regionName = cmd[2]; regionFile = cmd[3]; } string extension = Path.GetExtension(regionFile).ToLower(); bool isXml = extension.Equals(".xml"); bool isIni = extension.Equals(".ini"); if (!isXml && !isIni) { MainConsole.Instance.Output("Usage: create region [\"region name\"] <region_file.ini>"); return; } if (!Path.IsPathRooted(regionFile)) { string regionsDir = ConfigSource.Source.Configs["Startup"].GetString("regionload_regionsdir", "Regions").Trim(); regionFile = Path.Combine(regionsDir, regionFile); } RegionInfo regInfo; if (isXml) { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source); } else { regInfo = new RegionInfo(regionName, regionFile, false, ConfigSource.Source, regionName); } IScene scene; PopulateRegionEstateInfo(regInfo); CreateRegion(regInfo, true, out scene); regInfo.EstateSettings.Save(); } /// <summary> /// Change and load configuration file data. /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleConfig(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); if (cmdparams.Length > 0) { string firstParam = cmdparams[0].ToLower(); switch (firstParam) { case "set": if (cmdparams.Length < 4) { Notice("Syntax: config set <section> <key> <value>"); Notice("Example: config set ScriptEngine.DotNetEngine NumberOfScriptThreads 5"); } else { IConfig c; IConfigSource source = new IniConfigSource(); c = source.AddConfig(cmdparams[1]); if (c != null) { string _value = String.Join(" ", cmdparams, 3, cmdparams.Length - 3); c.Set(cmdparams[2], _value); m_config.Source.Merge(source); Notice("In section [{0}], set {1} = {2}", c.Name, cmdparams[2], _value); } } break; case "get": case "show": if (cmdparams.Length == 1) { foreach (IConfig config in m_config.Source.Configs) { Notice("[{0}]", config.Name); string[] keys = config.GetKeys(); foreach (string key in keys) Notice(" {0} = {1}", key, config.GetString(key)); } } else if (cmdparams.Length == 2 || cmdparams.Length == 3) { IConfig config = m_config.Source.Configs[cmdparams[1]]; if (config == null) { Notice("Section \"{0}\" does not exist.",cmdparams[1]); break; } else { if (cmdparams.Length == 2) { Notice("[{0}]", config.Name); foreach (string key in config.GetKeys()) Notice(" {0} = {1}", key, config.GetString(key)); } else { Notice( "config get {0} {1} : {2}", cmdparams[1], cmdparams[2], config.GetString(cmdparams[2])); } } } else { Notice("Syntax: config {0} [<section>] [<key>]", firstParam); Notice("Example: config {0} ScriptEngine.DotNetEngine NumberOfScriptThreads", firstParam); } break; case "save": if (cmdparams.Length < 2) { Notice("Syntax: config save <path>"); return; } if (Application.iniFilePath == cmdparams[1]) { Notice("Path can not be " + Application.iniFilePath); return; } Notice("Saving configuration file: " + cmdparams[1]); m_config.Save(cmdparams[1]); break; } } } /// <summary> /// Load, Unload, and list Region modules in use /// </summary> /// <param name="module"></param> /// <param name="cmd"></param> private void HandleModules(string module, string[] cmd) { List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] cmdparams = args.ToArray(); if (cmdparams.Length > 0) { switch (cmdparams[0].ToLower()) { case "list": foreach (IRegionModule irm in m_moduleLoader.GetLoadedSharedModules) { MainConsole.Instance.Output(String.Format("Shared region module: {0}", irm.Name)); } break; case "unload": if (cmdparams.Length > 1) { foreach (IRegionModule rm in new ArrayList(m_moduleLoader.GetLoadedSharedModules)) { if (rm.Name.ToLower() == cmdparams[1].ToLower()) { MainConsole.Instance.Output(String.Format("Unloading module: {0}", rm.Name)); m_moduleLoader.UnloadModule(rm); } } } break; case "load": if (cmdparams.Length > 1) { foreach (Scene s in new ArrayList(m_sceneManager.Scenes)) { MainConsole.Instance.Output(String.Format("Loading module: {0}", cmdparams[1])); m_moduleLoader.LoadRegionModules(cmdparams[1], s); } } break; } } } /// <summary> /// Runs commands issued by the server console from the operator /// </summary> /// <param name="command">The first argument of the parameter (the command)</param> /// <param name="cmdparams">Additional arguments passed to the command</param> public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); switch (command) { case "command-script": if (cmdparams.Length > 0) { RunCommandScript(cmdparams[0]); } break; case "backup": m_sceneManager.BackupCurrentScene(); break; case "remove-region": string regRemoveName = CombineParams(cmdparams, 0); Scene removeScene; if (m_sceneManager.TryGetScene(regRemoveName, out removeScene)) RemoveRegion(removeScene, false); else MainConsole.Instance.Output("no region with that name"); break; case "delete-region": string regDeleteName = CombineParams(cmdparams, 0); Scene killScene; if (m_sceneManager.TryGetScene(regDeleteName, out killScene)) RemoveRegion(killScene, true); else MainConsole.Instance.Output("no region with that name"); break; case "restart": m_sceneManager.RestartCurrentScene(); break; case "Add-InventoryHost": if (cmdparams.Length > 0) { MainConsole.Instance.Output("Not implemented."); } break; } } /// <summary> /// Change the currently selected region. The selected region is that operated upon by single region commands. /// </summary> /// <param name="cmdParams"></param> protected void ChangeSelectedRegion(string module, string[] cmdparams) { if (cmdparams.Length > 2) { string newRegionName = CombineParams(cmdparams, 2); if (!m_sceneManager.TrySetCurrentScene(newRegionName)) MainConsole.Instance.Output(String.Format("Couldn't select region {0}", newRegionName)); } else { MainConsole.Instance.Output("Usage: change region <region name>"); } string regionName = (m_sceneManager.CurrentScene == null ? "root" : m_sceneManager.CurrentScene.RegionInfo.RegionName); MainConsole.Instance.Output(String.Format("Currently selected region is {0}", regionName)); m_console.DefaultPrompt = String.Format("Region ({0}) ", regionName); m_console.ConsoleScene = m_sceneManager.CurrentScene; } /// <summary> /// Turn on some debugging values for OpenSim. /// </summary> /// <param name="args"></param> protected void Debug(string module, string[] args) { if (args.Length == 1) return; switch (args[1]) { case "packet": if (args.Length > 2) { int newDebug; if (int.TryParse(args[2], out newDebug)) { m_sceneManager.SetDebugPacketLevelOnCurrentScene(newDebug); } else { MainConsole.Instance.Output("packet debug should be 0..255"); } MainConsole.Instance.Output(String.Format("New packet debug: {0}", newDebug)); } break; case "scene": if (args.Length == 5) { if (m_sceneManager.CurrentScene == null) { MainConsole.Instance.Output("Please use 'change region <regioname>' first"); } else { bool scriptingOn = !Convert.ToBoolean(args[2]); bool collisionsOn = !Convert.ToBoolean(args[3]); bool physicsOn = !Convert.ToBoolean(args[4]); m_sceneManager.CurrentScene.SetSceneCoreDebug(scriptingOn, collisionsOn, physicsOn); MainConsole.Instance.Output( String.Format( "Set debug scene scripting = {0}, collisions = {1}, physics = {2}", !scriptingOn, !collisionsOn, !physicsOn)); } } else { MainConsole.Instance.Output("debug scene <scripting> <collisions> <physics> (where inside <> is true/false)"); } break; default: MainConsole.Instance.Output("Unknown debug"); break; } } // see BaseOpenSimServer /// <summary> /// Many commands list objects for debugging. Some of the types are listed here /// </summary> /// <param name="mod"></param> /// <param name="cmd"></param> public override void HandleShow(string mod, string[] cmd) { base.HandleShow(mod, cmd); List<string> args = new List<string>(cmd); args.RemoveAt(0); string[] showParams = args.ToArray(); switch (showParams[0]) { case "users": IList agents; if (showParams.Length > 1 && showParams[1] == "full") { agents = m_sceneManager.GetCurrentScenePresences(); } else { agents = m_sceneManager.GetCurrentSceneAvatars(); } MainConsole.Instance.Output(String.Format("\nAgents connected: {0}\n", agents.Count)); MainConsole.Instance.Output( String.Format("{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", "Firstname", "Lastname", "Agent ID", "Root/Child", "Region", "Position")); foreach (ScenePresence presence in agents) { RegionInfo regionInfo = presence.Scene.RegionInfo; string regionName; if (regionInfo == null) { regionName = "Unresolvable"; } else { regionName = regionInfo.RegionName; } MainConsole.Instance.Output( String.Format( "{0,-16} {1,-16} {2,-37} {3,-11} {4,-16} {5,-30}", presence.Firstname, presence.Lastname, presence.UUID, presence.IsChildAgent ? "Child" : "Root", regionName, presence.AbsolutePosition.ToString())); } MainConsole.Instance.Output(String.Empty); break; case "connections": System.Text.StringBuilder connections = new System.Text.StringBuilder("Connections:\n"); m_sceneManager.ForEachScene( delegate(Scene scene) { scene.ForEachClient( delegate(IClientAPI client) { connections.AppendFormat("{0}: {1} ({2}) from {3} on circuit {4}\n", scene.RegionInfo.RegionName, client.Name, client.AgentId, client.RemoteEndPoint, client.CircuitCode); } ); } ); MainConsole.Instance.Output(connections.ToString()); break; case "circuits": System.Text.StringBuilder acd = new System.Text.StringBuilder("Agent Circuits:\n"); m_sceneManager.ForEachScene( delegate(Scene scene) { //this.HttpServer. acd.AppendFormat("{0}:\n", scene.RegionInfo.RegionName); foreach (AgentCircuitData aCircuit in scene.AuthenticateHandler.AgentCircuits.Values) acd.AppendFormat("\t{0} {1} ({2})\n", aCircuit.firstname, aCircuit.lastname, (aCircuit.child ? "Child" : "Root")); } ); MainConsole.Instance.Output(acd.ToString()); break; case "http-handlers": System.Text.StringBuilder handlers = new System.Text.StringBuilder("Registered HTTP Handlers:\n"); handlers.AppendFormat("* XMLRPC:\n"); foreach (String s in HttpServer.GetXmlRpcHandlerKeys()) handlers.AppendFormat("\t{0}\n", s); handlers.AppendFormat("* HTTP:\n"); List<String> poll = HttpServer.GetPollServiceHandlerKeys(); foreach (String s in HttpServer.GetHTTPHandlerKeys()) handlers.AppendFormat("\t{0} {1}\n", s, (poll.Contains(s) ? "(poll service)" : string.Empty)); 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); MainConsole.Instance.Output(handlers.ToString()); break; case "pending-objects": System.Text.StringBuilder pending = new System.Text.StringBuilder("Pending objects:\n"); m_sceneManager.ForEachScene( delegate(Scene scene) { scene.ForEachScenePresence( delegate(ScenePresence sp) { pending.AppendFormat("{0}: {1} {2} pending\n", scene.RegionInfo.RegionName, sp.Name, sp.SceneViewer.GetPendingObjectsCount()); } ); } ); MainConsole.Instance.Output(pending.ToString()); break; case "modules": MainConsole.Instance.Output("The currently loaded shared modules are:"); foreach (IRegionModule module in m_moduleLoader.GetLoadedSharedModules) { MainConsole.Instance.Output("Shared Module: " + module.Name); } MainConsole.Instance.Output(""); break; case "regions": m_sceneManager.ForEachScene( delegate(Scene scene) { MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region XLoc: {1}, Region YLoc: {2}, Region Port: {3}, Estate Name: {4}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionLocX, scene.RegionInfo.RegionLocY, scene.RegionInfo.InternalEndPoint.Port, scene.RegionInfo.EstateSettings.EstateName)); }); break; case "ratings": m_sceneManager.ForEachScene( delegate(Scene scene) { string rating = ""; if (scene.RegionInfo.RegionSettings.Maturity == 1) { rating = "MATURE"; } else if (scene.RegionInfo.RegionSettings.Maturity == 2) { rating = "ADULT"; } else { rating = "PG"; } MainConsole.Instance.Output(String.Format( "Region Name: {0}, Region Rating {1}", scene.RegionInfo.RegionName, rating)); }); break; } } /// <summary> /// Use XML2 format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SavePrimsXml2(string module, string[] cmdparams) { if (cmdparams.Length > 5) { m_sceneManager.SaveNamedPrimsToXml2(cmdparams[3], cmdparams[4]); } else { m_sceneManager.SaveNamedPrimsToXml2("Primitive", DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Use XML format to serialize data to a file /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, save-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use save-xml2, please file a mantis detailing the reason."); if (cmdparams.Length > 0) { m_sceneManager.SaveCurrentSceneToXml(cmdparams[2]); } else { m_sceneManager.SaveCurrentSceneToXml(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Loads data and region objects from XML format. /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml(string module, string[] cmdparams) { MainConsole.Instance.Output("PLEASE NOTE, load-xml is DEPRECATED and may be REMOVED soon. If you are using this and there is some reason you can't use load-xml2, please file a mantis detailing the reason."); Vector3 loadOffset = new Vector3(0, 0, 0); if (cmdparams.Length > 2) { bool generateNewIDS = false; if (cmdparams.Length > 3) { if (cmdparams[3] == "-newUID") { generateNewIDS = true; } if (cmdparams.Length > 4) { loadOffset.X = (float)Convert.ToDecimal(cmdparams[4], Culture.NumberFormatInfo); if (cmdparams.Length > 5) { loadOffset.Y = (float)Convert.ToDecimal(cmdparams[5], Culture.NumberFormatInfo); } if (cmdparams.Length > 6) { loadOffset.Z = (float)Convert.ToDecimal(cmdparams[6], Culture.NumberFormatInfo); } MainConsole.Instance.Output(String.Format("loadOffsets <X,Y,Z> = <{0},{1},{2}>",loadOffset.X,loadOffset.Y,loadOffset.Z)); } } m_sceneManager.LoadCurrentSceneFromXml(cmdparams[2], generateNewIDS, loadOffset); } else { try { m_sceneManager.LoadCurrentSceneFromXml(DEFAULT_PRIM_BACKUP_FILENAME, false, loadOffset); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load-xml <filename>"); } } } /// <summary> /// Serialize region data to XML2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void SaveXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { m_sceneManager.SaveCurrentSceneToXml2(cmdparams[2]); } else { m_sceneManager.SaveCurrentSceneToXml2(DEFAULT_PRIM_BACKUP_FILENAME); } } /// <summary> /// Load region data from Xml2Format /// </summary> /// <param name="module"></param> /// <param name="cmdparams"></param> protected void LoadXml2(string module, string[] cmdparams) { if (cmdparams.Length > 2) { try { m_sceneManager.LoadCurrentSceneFromXml2(cmdparams[2]); } catch (FileNotFoundException) { MainConsole.Instance.Output("Specified xml not found. Usage: load xml2 <filename>"); } } else { try { m_sceneManager.LoadCurrentSceneFromXml2(DEFAULT_PRIM_BACKUP_FILENAME); } catch (FileNotFoundException) { MainConsole.Instance.Output("Default xml not found. Usage: load xml2 <filename>"); } } } /// <summary> /// Load a whole region from an opensimulator archive. /// </summary> /// <param name="cmdparams"></param> protected void LoadOar(string module, string[] cmdparams) { try { m_sceneManager.LoadArchiveToCurrentScene(cmdparams); } catch (Exception e) { MainConsole.Instance.Output(e.Message); } } /// <summary> /// Save a region to a file, including all the assets needed to restore it. /// </summary> /// <param name="cmdparams"></param> protected void SaveOar(string module, string[] cmdparams) { m_sceneManager.SaveCurrentSceneToArchive(cmdparams); } private static string CombineParams(string[] commandParams, int pos) { string result = String.Empty; for (int i = pos; i < commandParams.Length; i++) { result += commandParams[i] + " "; } result = result.TrimEnd(' '); return result; } /// <summary> /// Kill an object given its UUID. /// </summary> /// <param name="cmdparams"></param> protected void KillUUID(string module, string[] cmdparams) { if (cmdparams.Length > 2) { UUID id = UUID.Zero; SceneObjectGroup grp = null; Scene sc = null; if (!UUID.TryParse(cmdparams[2], out id)) { MainConsole.Instance.Output("[KillUUID]: Error bad UUID format!"); return; } m_sceneManager.ForEachScene( delegate(Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(id); if (part == null) return; grp = part.ParentGroup; sc = scene; }); if (grp == null) { MainConsole.Instance.Output(String.Format("[KillUUID]: Given UUID {0} not found!", id)); } else { MainConsole.Instance.Output(String.Format("[KillUUID]: Found UUID {0} in scene {1}", id, sc.RegionInfo.RegionName)); try { sc.DeleteSceneObject(grp, false); } catch (Exception e) { m_log.ErrorFormat("[KillUUID]: Error while removing objects from scene: " + e); } } } else { MainConsole.Instance.Output("[KillUUID]: Usage: kill uuid <UUID>"); } } #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 Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NuGet; using NuGet.Frameworks; using NuGet.Packaging.Core; using NuGet.Packaging; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Text; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class GenerateNuSpec : Task { private const string NuSpecXmlNamespace = @"http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"; public string InputFileName { get; set; } [Required] public string OutputFileName { get; set; } public string MinClientVersion { get; set; } [Required] public string Id { get; set; } [Required] public string Version { get; set; } [Required] public string Title { get; set; } [Required] public string Authors { get; set; } [Required] public string Owners { get; set; } [Required] public string Description { get; set; } public string ReleaseNotes { get; set; } public string Summary { get; set; } public string Language { get; set; } public string ProjectUrl { get; set; } public string IconUrl { get; set; } public string LicenseUrl { get; set; } public string Copyright { get; set; } public bool RequireLicenseAcceptance { get; set; } public bool DevelopmentDependency { get; set; } public bool Serviceable { get; set; } public string Tags { get; set; } public ITaskItem[] Dependencies { get; set; } public ITaskItem[] References { get; set; } public ITaskItem[] FrameworkReferences { get; set; } public ITaskItem[] Files { get; set; } public override bool Execute() { try { WriteNuSpecFile(); } catch (Exception ex) { Log.LogError(ex.ToString()); Log.LogErrorFromException(ex); } return !Log.HasLoggedErrors; } private void WriteNuSpecFile() { var manifest = CreateManifest(); if (!IsDifferent(manifest)) { Log.LogMessage("Skipping generation of .nuspec because contents are identical."); return; } var directory = Path.GetDirectoryName(OutputFileName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (var file = File.Create(OutputFileName)) { manifest.Save(file, false); } } private bool IsDifferent(Manifest newManifest) { if (!File.Exists(OutputFileName)) return true; var oldSource = File.ReadAllText(OutputFileName); var newSource = ""; using (var stream = new MemoryStream()) { newManifest.Save(stream); stream.Seek(0, SeekOrigin.Begin); newSource = Encoding.UTF8.GetString(stream.ToArray()); } return oldSource != newSource; } private Manifest CreateManifest() { Manifest manifest; ManifestMetadata manifestMetadata; if (!string.IsNullOrEmpty(InputFileName)) { using (var stream = File.OpenRead(InputFileName)) { manifest = Manifest.ReadFrom(stream, false); } if (manifest.Metadata == null) { manifest = new Manifest(new ManifestMetadata(), manifest.Files); } } else { manifest = new Manifest(new ManifestMetadata()); } manifestMetadata = manifest.Metadata; manifestMetadata.UpdateMember(x => x.Authors, Authors?.Split(';')); manifestMetadata.UpdateMember(x => x.Copyright, Copyright); manifestMetadata.UpdateMember(x => x.DependencyGroups, GetDependencySets()); manifestMetadata.UpdateMember(x => x.Description, Description); manifestMetadata.DevelopmentDependency |= DevelopmentDependency; manifestMetadata.UpdateMember(x => x.FrameworkReferences, GetFrameworkAssemblies()); if (IconUrl != null) { manifestMetadata.SetIconUrl(IconUrl); } manifestMetadata.UpdateMember(x => x.Id, Id); manifestMetadata.UpdateMember(x => x.Language, Language); if (LicenseUrl != null) { manifestMetadata.SetLicenseUrl(LicenseUrl); } manifestMetadata.UpdateMember(x => x.MinClientVersionString, MinClientVersion); manifestMetadata.UpdateMember(x => x.Owners, Owners?.Split(';')); if (ProjectUrl != null) { manifestMetadata.SetProjectUrl(ProjectUrl); } manifestMetadata.UpdateMember(x => x.PackageAssemblyReferences, GetReferenceSets()); manifestMetadata.UpdateMember(x => x.ReleaseNotes, ReleaseNotes); manifestMetadata.RequireLicenseAcceptance |= RequireLicenseAcceptance; manifestMetadata.UpdateMember(x => x.Summary, Summary); manifestMetadata.UpdateMember(x => x.Tags, Tags); manifestMetadata.UpdateMember(x => x.Title, Title); manifestMetadata.UpdateMember(x => x.Version, Version != null ? new NuGetVersion(Version) : null); manifestMetadata.Serviceable |= Serviceable; manifest.AddRangeToMember(x => x.Files, GetManifestFiles()); return manifest; } private List<ManifestFile> GetManifestFiles() { return (from f in Files.NullAsEmpty() where !f.GetMetadata(Metadata.FileTarget).StartsWith("$none$", StringComparison.OrdinalIgnoreCase) select new ManifestFile() { Source = f.GetMetadata(Metadata.FileSource), Target = f.GetMetadata(Metadata.FileTarget), Exclude = f.GetMetadata(Metadata.FileExclude) }).OrderBy(f => f.Target, StringComparer.OrdinalIgnoreCase).ToList(); } static FrameworkAssemblyReferenceComparer frameworkAssemblyReferenceComparer = new FrameworkAssemblyReferenceComparer(); private List<FrameworkAssemblyReference> GetFrameworkAssemblies() { return (from fr in FrameworkReferences.NullAsEmpty() orderby fr.ItemSpec, StringComparer.Ordinal select new FrameworkAssemblyReference(fr.ItemSpec, new[] { fr.GetTargetFramework() }) ).Distinct(frameworkAssemblyReferenceComparer).ToList(); } private class FrameworkAssemblyReferenceComparer : EqualityComparer<FrameworkAssemblyReference> { public override bool Equals(FrameworkAssemblyReference x, FrameworkAssemblyReference y) { return Object.Equals(x, y) || ( x != null && y != null && x.AssemblyName.Equals(y.AssemblyName) && x.SupportedFrameworks.SequenceEqual(y.SupportedFrameworks, NuGetFramework.Comparer) ); } public override int GetHashCode(FrameworkAssemblyReference obj) { return obj.AssemblyName.GetHashCode(); } } private List<PackageDependencyGroup> GetDependencySets() { var dependencies = from d in Dependencies.NullAsEmpty() select new Dependency { Id = d.ItemSpec, Version = d.GetVersion(), TargetFramework = d.GetTargetFramework() ?? NuGetFramework.AnyFramework, Include = d.GetValueList("Include"), Exclude = d.GetValueList("Exclude") }; return (from dependency in dependencies group dependency by dependency.TargetFramework into dependenciesByFramework select new PackageDependencyGroup( dependenciesByFramework.Key, from dependency in dependenciesByFramework where dependency.Id != "_._" orderby dependency.Id, StringComparer.Ordinal group dependency by dependency.Id into dependenciesById select new PackageDependency( dependenciesById.Key, VersionRange.Parse( dependenciesById.Select(x => x.Version) .Aggregate(AggregateVersions) .ToStringSafe()), dependenciesById.Select(x => x.Include).Aggregate(AggregateInclude), dependenciesById.Select(x => x.Exclude).Aggregate(AggregateExclude) ))).OrderBy(s => s?.TargetFramework?.GetShortFolderName(), StringComparer.Ordinal) .ToList(); } private IEnumerable<PackageReferenceSet> GetReferenceSets() { var references = from r in References.NullAsEmpty() select new { File = r.ItemSpec, TargetFramework = r.GetTargetFramework(), }; return (from reference in references group reference by reference.TargetFramework into referencesByFramework select new PackageReferenceSet( referencesByFramework.Key, from reference in referencesByFramework orderby reference.File, StringComparer.Ordinal select reference.File ) ).ToList(); } private static VersionRange AggregateVersions(VersionRange aggregate, VersionRange next) { var versionRange = new VersionRange(); SetMinVersion(ref versionRange, aggregate); SetMinVersion(ref versionRange, next); SetMaxVersion(ref versionRange, aggregate); SetMaxVersion(ref versionRange, next); if (versionRange.MinVersion == null && versionRange.MaxVersion == null) { versionRange = null; } return versionRange; } private static IReadOnlyList<string> AggregateInclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next) { // include is a union if (aggregate == null) { return next; } if (next == null) { return aggregate; } return aggregate.Union(next).ToArray(); } private static IReadOnlyList<string> AggregateExclude(IReadOnlyList<string> aggregate, IReadOnlyList<string> next) { // exclude is an intersection if (aggregate == null || next == null) { return null; } return aggregate.Intersect(next).ToArray(); } private static void SetMinVersion(ref VersionRange target, VersionRange source) { if (source == null || source.MinVersion == null) { return; } bool update = false; NuGetVersion minVersion = target.MinVersion; bool includeMinVersion = target.IsMinInclusive; if (target.MinVersion == null) { update = true; minVersion = source.MinVersion; includeMinVersion = source.IsMinInclusive; } if (target.MinVersion < source.MinVersion) { update = true; minVersion = source.MinVersion; includeMinVersion = source.IsMinInclusive; } if (target.MinVersion == source.MinVersion) { update = true; includeMinVersion = target.IsMinInclusive && source.IsMinInclusive; } if (update) { target = new VersionRange(minVersion, includeMinVersion, target.MaxVersion, target.IsMaxInclusive, target.Float, target.OriginalString); } } private static void SetMaxVersion(ref VersionRange target, VersionRange source) { if (source == null || source.MaxVersion == null) { return; } bool update = false; NuGetVersion maxVersion = target.MaxVersion; bool includeMaxVersion = target.IsMaxInclusive; if (target.MaxVersion == null) { update = true; maxVersion = source.MaxVersion; includeMaxVersion = source.IsMaxInclusive; } if (target.MaxVersion > source.MaxVersion) { update = true; maxVersion = source.MaxVersion; includeMaxVersion = source.IsMaxInclusive; } if (target.MaxVersion == source.MaxVersion) { update = true; includeMaxVersion = target.IsMaxInclusive && source.IsMaxInclusive; } if (update) { target = new VersionRange(target.MinVersion, target.IsMinInclusive, maxVersion, includeMaxVersion, target.Float, target.OriginalString); } } private class Dependency { public string Id { get; set; } public NuGetFramework TargetFramework { get; set; } public VersionRange Version { get; set; } public IReadOnlyList<string> Exclude { get; set; } public IReadOnlyList<string> Include { get; set; } } } }
using System; using System.Collections; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Text; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; using FeedBuilder.Properties; namespace FeedBuilder { public class FeedBuilderSettingsProvider : SettingsProvider { //XML Root Node private const string SETTINGSROOT = "Settings"; public void SaveAs(string filename) { try { Settings.Default.Save(); string source = Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()); File.Copy(source, filename, true); } catch (Exception ex) { string msg = string.Format("An error occurred while saving the file: {0}{0}{1}", Environment.NewLine, ex.Message); MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void LoadFrom(string filename) { try { string dest = Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename()); if (File.Exists(dest)) { FileInfo destInfo = new FileInfo(dest); FileInfo fileNameInfo = new FileInfo(filename); if (filename == dest && destInfo.Length == fileNameInfo.Length && destInfo.CreationTime.Equals(fileNameInfo.CreationTime)) return; } File.Copy(filename, dest, true); Settings.Default.Reload(); } catch (Exception ex) { string msg = string.Format("An error occurred while loading the file: {0}{0}{1}", Environment.NewLine, ex.Message); MessageBox.Show(msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public override void Initialize(string name, NameValueCollection col) { base.Initialize(ApplicationName, col); if (!Directory.Exists(GetAppSettingsPath())) { try { Directory.CreateDirectory(GetAppSettingsPath()); } catch (IOException) { } } } public override string ApplicationName { get { return "FeedBuilder"; } //Do nothing set { } } public virtual string GetAppSettingsPath() { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ApplicationName); } public virtual string GetAppSettingsFilename() { return "Settings.xml"; } public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals) { //Iterate through the settings to be stored //Only dirty settings are included in propvals, and only ones relevant to this provider foreach (SettingsPropertyValue propval in propvals) { SetValue(propval); } try { if (!Directory.Exists(GetAppSettingsPath())) Directory.CreateDirectory(GetAppSettingsPath()); SettingsXML.Save(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename())); } catch (Exception) { //Ignore if cant save, device been ejected } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection props) { //Create new collection of values SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); //Iterate through the settings to be retrieved foreach (SettingsProperty setting in props) { SettingsPropertyValue value = new SettingsPropertyValue(setting) { IsDirty = false, SerializedValue = GetValue(setting) }; values.Add(value); } return values; } private XmlDocument m_SettingsXML; private XmlDocument SettingsXML { get { //If we dont hold an xml document, try opening one. //If it doesnt exist then create a new one ready. if (m_SettingsXML == null) { m_SettingsXML = new XmlDocument(); try { m_SettingsXML.Load(Path.Combine(GetAppSettingsPath(), GetAppSettingsFilename())); } catch (Exception) { //Create new document XmlDeclaration dec = m_SettingsXML.CreateXmlDeclaration("1.0", "utf-8", string.Empty); m_SettingsXML.AppendChild(dec); XmlNode nodeRoot = m_SettingsXML.CreateNode(XmlNodeType.Element, SETTINGSROOT, ""); m_SettingsXML.AppendChild(nodeRoot); } } return m_SettingsXML; } } private string GetValue(SettingsProperty setting) { string ret = null; try { string path = IsRoaming(setting) ? string.Format("{0}/{1}", SETTINGSROOT, setting.Name) : string.Format("{0}/{1}/{2}", SETTINGSROOT, Environment.MachineName, setting.Name); if (setting.PropertyType.BaseType != null && setting.PropertyType.BaseType.Name == "CollectionBase") { XmlNode selectSingleNode = SettingsXML.SelectSingleNode(path); if (selectSingleNode != null) ret = selectSingleNode.InnerXml; } else { XmlNode singleNode = SettingsXML.SelectSingleNode(path); if (singleNode != null) ret = singleNode.InnerText; } } catch (Exception) { ret = (setting.DefaultValue != null) ? setting.DefaultValue.ToString() : string.Empty; } return ret; } private void SetValue(SettingsPropertyValue propVal) { XmlElement SettingNode; //Determine if the setting is roaming. //If roaming then the value is stored as an element under the root //Otherwise it is stored under a machine name node try { if (IsRoaming(propVal.Property)) { SettingNode = (XmlElement)SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + propVal.Name); } else { SettingNode = (XmlElement)SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName + "/" + propVal.Name); } } catch (Exception) { SettingNode = null; } //Check to see if the node exists, if so then set its new value if ((SettingNode != null)) { //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); } else { if (IsRoaming(propVal.Property)) { //Store the value as an element of the Settings Root Node SettingNode = SettingsXML.CreateElement(propVal.Name); //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(SettingNode); } else { //Its machine specific, store as an element of the machine name node, //creating a new machine name node if one doesnt exist. XmlElement MachineNode; try { MachineNode = (XmlElement)SettingsXML.SelectSingleNode(SETTINGSROOT + "/" + Environment.MachineName); } catch (Exception) { MachineNode = SettingsXML.CreateElement(Environment.MachineName); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(MachineNode); } if (MachineNode == null) { MachineNode = SettingsXML.CreateElement(Environment.MachineName); XmlNode selectSingleNode = SettingsXML.SelectSingleNode(SETTINGSROOT); if (selectSingleNode != null) selectSingleNode.AppendChild(MachineNode); } SettingNode = SettingsXML.CreateElement(propVal.Name); //SettingNode.InnerText = propVal.SerializedValue.ToString SetSerializedValue(SettingNode, propVal); MachineNode.AppendChild(SettingNode); } } } private void SetSerializedValue(XmlElement node, SettingsPropertyValue propVal) { if (propVal.Property.PropertyType.BaseType != null && propVal.Property.PropertyType.BaseType.Name == "CollectionBase") { StringBuilder builder = new StringBuilder(); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); XmlWriterSettings xsettings = new XmlWriterSettings(); ns.Add("", ""); xsettings.OmitXmlDeclaration = true; XmlWriter xmlWriter = XmlWriter.Create(builder, xsettings); XmlSerializer s = new XmlSerializer(propVal.Property.PropertyType); s.Serialize(xmlWriter, propVal.PropertyValue, ns); xmlWriter.Close(); node.InnerXml = builder.ToString(); } else node.InnerText = propVal.SerializedValue.ToString(); } private bool IsRoaming(SettingsProperty prop) { //Determine if the setting is marked as Roaming foreach (DictionaryEntry d in prop.Attributes) { Attribute a = (Attribute)d.Value; if (a is SettingsManageabilityAttribute) return true; } return false; } } }
// Copyright (C) 2014 dot42 // // Original filename: String.cs // // 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.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; using Dot42; using Dot42.Internal; using Java.Lang; using Java.Util; namespace System { partial class String : IEnumerable<char> { public const string Empty = ""; /// <summary> /// Creates a string with the specified character repeated 'count' times. /// </summary> public String(char c, int count) : this(Constuct(c, count)) { } /// <summary> /// Returns the char at index. /// </summary> [global::System.Runtime.CompilerServices.IndexerName("Chars")] public char this[int index] { [Dot42.DexImport("charAt", "(I)C", AccessFlags = 257)] get { return default(char); } } /// <summary> /// Returns the number of chars in this string. /// </summary> public int Length { [Dot42.DexImport("length", "()I", AccessFlags = 257)] get { return default(int); } } private static char[] Constuct(char c, int count) { var result = new char[count]; Arrays.Fill(result, c); return result; } /// <summary> /// Compare strings /// </summary> [Inline] public static int Compare(string strA, string strB) { return Compare(strA, strB, false); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, string strB, bool ignoreCase) { if (ReferenceEquals(strA, null) && ReferenceEquals(strB, null)) return 0; if (ReferenceEquals(strA, null)) return 1; if (ReferenceEquals(strB, null)) return -1; if (ignoreCase) return strA.CompareToIgnoreCase(strB); return strA.CompareTo(strB); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, string strB, bool ignoreCase, CultureInfo cutureInfo) { if (ReferenceEquals(strA, null) && ReferenceEquals(strB, null)) return 0; if (ReferenceEquals(strA, null)) return 1; if (ReferenceEquals(strB, null)) return -1; if (ignoreCase) return strA.CompareToIgnoreCase(strB); return strA.CompareTo(strB); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, string strB, StringComparison comparisonType) { var ignoreCase = (comparisonType == StringComparison.InvariantCultureIgnoreCase) || (comparisonType == StringComparison.CurrentCultureIgnoreCase) || (comparisonType == StringComparison.OrdinalIgnoreCase); return Compare(strA, strB, ignoreCase); } /// <summary> /// Compare strings /// </summary> public static int Compare(string strA, int indexA, string strB, int indexB, int length, bool ignoreCase, CultureInfo cultureInfo) { var a = strA.JavaSubstring(indexA, indexA + length); var b = strB.JavaSubstring(indexB, indexB + length); if (ignoreCase) return a.CompareToIgnoreCase(b); else return a.CompareTo(b); } /// <summary> /// Compare strings /// </summary> [Inline] public static int CompareOrdinal(string strA, string strB) { return Compare(strA, strB, StringComparison.Ordinal); } /// <summary> /// Compare strings /// </summary> public bool StartsWith(string other, StringComparison comparisonType) { if (Length < other.Length) return false; var ignoreCase = (comparisonType == StringComparison.InvariantCultureIgnoreCase) || (comparisonType == StringComparison.CurrentCultureIgnoreCase) || (comparisonType == StringComparison.OrdinalIgnoreCase); if (!ignoreCase) return StartsWith(other); var _this = this.JavaSubstring(0, other.Length); return Compare(_this, other, ignoreCase) == 0; } /// <summary> /// Compare strings /// </summary> public bool EndsWith(string other, StringComparison comparisonType) { if (Length < other.Length) return false; var ignoreCase = (comparisonType == StringComparison.InvariantCultureIgnoreCase) || (comparisonType == StringComparison.CurrentCultureIgnoreCase) || (comparisonType == StringComparison.OrdinalIgnoreCase); if (!ignoreCase) return EndsWith(other); var _this = this.JavaSubstring(Length-other.Length, Length); return Compare(_this, other, ignoreCase) == 0; } /// <summary> /// Does this string contain the given sub string? /// </summary> [Inline] public bool Contains(string value) { return Contains((ICharSequence) value); } /// <summary> /// Copy a specified numbers of characters from this string to the given array. /// </summary> public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException("destination"); if (sourceIndex < 0) throw new ArgumentOutOfRangeException("sourceIndex"); if (destinationIndex < 0) throw new ArgumentOutOfRangeException("destinationIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (sourceIndex + count > Length) throw new ArgumentOutOfRangeException("count"); if (destinationIndex + count > destination.Length) throw new ArgumentOutOfRangeException("count"); while (count > 0) { destination[destinationIndex++] = this[sourceIndex++]; count--; } } /// <summary> /// Replaces format items in the given string with a string representation of the given argument. /// </summary> public static string Format(string format, object arg0) { var helper = new FormatHelper(null, null, format, arg0); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(string format, object arg0, object arg1) { var helper = new FormatHelper(null, null, format, arg0, arg1); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(string format, object arg0, object arg1, object arg2) { var helper = new FormatHelper(null, null, format, arg0, arg1, arg2); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(string format, params object[] args) { var helper = new FormatHelper(null, null, format, args); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representation of the given argument. /// </summary> public static string Format(IFormatProvider provider, string format, object arg0) { var helper = new FormatHelper(null, provider, format, arg0); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(IFormatProvider provider, string format, object arg0, object arg1) { var helper = new FormatHelper(null, provider, format, arg0, arg1); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(IFormatProvider provider, string format, object arg0, object arg1, object arg2) { var helper = new FormatHelper(null, provider, format, arg0, arg1, arg2); return helper.Format().ToString(); } /// <summary> /// Replaces format items in the given string with a string representations of the given arguments. /// </summary> public static string Format(IFormatProvider provider, string format, params object[] args) { var helper = new FormatHelper(null, provider, format, args); return helper.Format().ToString(); } /// <summary> /// Gets the index of the first use of the given character in this string. /// </summary> /// <returns>The index of the first use of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOf(char ch) { return IndexOf((int) ch); } /// <summary> /// Gets the index of the first use of the given character in this string. /// The search starts at the given index. /// </summary> /// <returns>The index of the first use of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOf(char ch, int startIndex) { return IndexOf((int)ch, startIndex); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOfAny(char[] array) { return IndexOfAny(array, 0, Length); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> [Inline] public int IndexOfAny(char[] array, int startIndex) { return IndexOfAny(array, startIndex, Length - startIndex); } /// <summary> /// Gets the index of the first use of any of the given characters in this string. /// </summary> /// <returns>The index of the first use of any of the given character or -1 if the given character is not used.</returns> public int IndexOfAny(char[] array, int startIndex, int count) { if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex"); if (count < 0) throw new ArgumentOutOfRangeException("count"); var length = Length; if (startIndex + count > length) throw new ArgumentOutOfRangeException(); var arrayLen = array.Length; var endIndex = startIndex + count; for (var i = startIndex; i < endIndex; i++) { var ch = this[i]; for (var j = 0; j < arrayLen; j++) { if (array[j] == ch) return i; } } return -1; } /// <summary> /// Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions. /// </summary> public int IndexOf(string value, int startIndex, int count) { if ((count < 0) || (count > (Length - startIndex))) throw new ArgumentOutOfRangeException("count"); if ((startIndex < 0) || (startIndex > Length)) throw new ArgumentOutOfRangeException("startIndex"); var subString = JavaSubstring(startIndex, startIndex + count); var index = subString.IndexOf(value); return (index < 0) ? index : index + startIndex; } /// <summary> /// Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position and examines a specified number of character positions. /// </summary> public int IndexOf(string value, int startIndex, StringComparison comparison) { bool isCultureSpecific = comparison == StringComparison.CurrentCulture || comparison == StringComparison.CurrentCultureIgnoreCase; bool isNormal = comparison == StringComparison.Ordinal || comparison == StringComparison.InvariantCulture || comparison == StringComparison.CurrentCulture; if (isNormal) return IndexOf(value, startIndex); if(isCultureSpecific) throw new NotImplementedException("IndexOf with local culture not supported"); return ToUpperInvariant().IndexOf(value.ToUpperInvariant(), startIndex); } /// <summary> /// Returns a new string that right-aligns the characters in this string by padding them with spaces on the left, for a specified total length. /// </summary> [Inline] public string PadLeft(int totalWidth) { return PadLeft(totalWidth, ' '); } /// <summary> /// Returns a new string that right-aligns the characters in this string by padding them given character on the left, for a specified total length. /// </summary> public string PadLeft(int totalWidth, char paddingChar) { var length = Length; if (totalWidth <= length) return this; var builder = new StringBuilder(totalWidth); builder.Append(paddingChar, totalWidth - length); builder.Append(this); return builder.ToString(); } /// <summary> /// Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length. /// </summary> [Inline] public string PadRight(int totalWidth) { return PadRight(totalWidth, ' '); } /// <summary> /// Returns a new string that left-aligns the characters in this string by padding them given character on the right, for a specified total length. /// </summary> public string PadRight(int totalWidth, char paddingChar) { var length = Length; if (totalWidth <= length) return this; var builder = new StringBuilder(totalWidth); builder.Append(this); builder.Append(paddingChar, totalWidth - length); return builder.ToString(); } /// <summary> /// Return a new instance which is this string with all characters from the given index on removed. /// </summary> public string Remove(int startIndex) { if ((startIndex < 0) || (startIndex >= Length)) throw new ArgumentOutOfRangeException("startIndex"); return JavaSubstring(0, startIndex); } /// <summary> /// Return a new instance which is this string with count characters from the given index on removed. /// </summary> public string Remove(int startIndex, int count) { var len = Length; if ((startIndex < 0) || (startIndex >= len)) throw new ArgumentOutOfRangeException("startIndex"); if ((count < 0) || (startIndex + count >= len)) throw new ArgumentOutOfRangeException("count"); if (count == 0) return this; if (startIndex == 0) return JavaSubstring(count, (len - count + 1)); var sb = new StringBuilder(); sb.Append(this, 0, startIndex); sb.Append(this, startIndex + count, len - (startIndex + count)); return sb.ToString(); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(params char[] separator) { return Split(separator, int.MaxValue, StringSplitOptions.None); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(char[] separator, int count) { return Split(separator, count, StringSplitOptions.None); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> [Inline] public string[] Split(char[] separator, StringSplitOptions options) { return Split(separator, int.MaxValue, options); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> public string[] Split(string[] separator, StringSplitOptions options) { // TODO: check if this a correct implementation. if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries)) throw new ArgumentException("Illegal enum value: " + options + "."); string splitPattern = string.Join("|", separator.Select(Java.Util.Regex.Pattern.Quote)); if(options == StringSplitOptions.None) return Split(splitPattern); else return Split(splitPattern).Where(s=>s.Length != 0); } /// <summary> /// Split this string into parts delimited by the given separators. /// </summary> public string[] Split(char[] separator, int count, StringSplitOptions options) { if (count < 0) throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero."); if ((options != StringSplitOptions.None) && (options != StringSplitOptions.RemoveEmptyEntries)) throw new ArgumentException("Illegal enum value: " + options + "."); var removeEmptyEntries = (options & StringSplitOptions.RemoveEmptyEntries) != 0; var length = Length; if ((length == 0) && removeEmptyEntries) return new string[0]; if (count <= 1) { return count == 0 ? new string[0] : new[] { this }; } var list = new ArrayList<string>(); var start = 0; var index = 0; while (index < length) { if (Contains(separator, this[index])) { // Split here if ((!removeEmptyEntries) || (start != index)) { list.Add(JavaSubstring(start, index)); } index++; start = index; if (list.Count + 1 >= count) { index = length; break; } } else { index++; } } // Add last part (if needed) if (start <= index) { if ((!removeEmptyEntries) || (start != index)) { list.Add(JavaSubstring(start, index)); } } return list.ToArray<string>(new string[list.Count]); } /// <summary> /// Does the given array contain the given character? /// </summary> private static bool Contains(char[] array, char value) { var length = array.Length; for (var i = 0; i < length; i++) if (array[i] == value) return true; return false; } /// <summary> /// Return a substring of this instance. /// </summary> [Dot42.DexImport("substring", "(I)Ljava/lang/String;")] public string Substring(int start) { return default(string); } /// <summary> /// Return a substring of this instance. /// </summary> public string Substring(int startIndex, int length) { if (length < 0) throw new ArgumentOutOfRangeException("length"); return JavaSubstring(startIndex, startIndex + length); } /// <summary> /// Is the given string null or zero length. /// </summary> [Inline] public static bool IsNullOrEmpty(string value) { return (value == null) || (value.Length == 0); } /// <summary> /// Is the given string null or consists only of whitespace characters. /// </summary> public static bool IsNullOrWhiteSpace(string value) { if (value == null) return true; int len = value.Length; for (int i = 0; i < len; ++i) { if (!char.IsWhiteSpace(value[i])) return false; } return true; } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, params string[] array) { if (array.Length == 0) return ""; var sb = new StringBuilder(); var first = true; foreach (var element in array) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, params object[] array) { if ((array.Length == 0) || (array[0] == null)) return ""; var sb = new StringBuilder(); var first = true; foreach (var element in array) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all strings in the array with the given separator between each array element. /// </summary> public static string Join(string separator, IEnumerable<string> strings) { var sb = new StringBuilder(); var first = true; foreach (var element in strings) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Create a concatenation of all objects in the enumerable with the given separator between each element. /// </summary> public static string Join<T>(string separator, IEnumerable<T> objects) { var sb = new StringBuilder(); var first = true; foreach (var element in objects) { if (first) { first = false; } else if (separator != null) { sb.Append(separator); } if (element != null) { sb.Append(element); } } return sb.ToString(); } /// <summary> /// Gets a string representation of the given value. /// </summary> public static string Concat(object value) { return (value == null) ? string.Empty : value.ToString(); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2) { var s1 = v1 == null ? null : v1.ToString(); var s2 = v2 == null ? null : v2.ToString(); return Concat(s1, s2); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2, object v3) { var s1 = v1 == null ? null : v1.ToString(); var s2 = v2 == null ? null : v2.ToString(); var s3 = v3 == null ? null : v3.ToString(); return Concat(s1, s2, s3); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(object v1, object v2, object v3, object v4) { var s1 = v1 == null ? null : v1.ToString(); var s2 = v2 == null ? null : v2.ToString(); var s3 = v3 == null ? null : v3.ToString(); var s4 = v4 == null ? null : v4.ToString(); return Concat(s1, s2, s3, s4); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(params object[] args) { if (args == null) throw new ArgumentNullException("args"); var length = args.Length; var sb = new StringBuilder(); for (var i = 0; i < length; i++) { var arg = args[i]; if (arg != null) sb.Append(arg); } return sb.ToString(); } /// <summary> /// Concatenate v1 and v2. /// </summary> public static string Concat(string v1, string v2) { if (string.IsNullOrEmpty(v1)) { if (string.IsNullOrEmpty(v2)) return string.Empty; return v2; } if (string.IsNullOrEmpty(v2)) return v1; return v1.Concat(v2); } /// <summary> /// Concatenate v1, v2 and v3. /// </summary> public static string Concat(string v1, string v2, string v3) { var s1 = v1 ?? string.Empty; var s2 = v2 ?? string.Empty; var s3 = v3 ?? string.Empty; StringBuilder b = new StringBuilder(s1.Length + s2.Length + s3.Length); b.Append(s1); b.Append(s2); b.Append(s3); return b.ToString(); } /// <summary> /// Concatenate v1, v2, v3 and v4. /// </summary> public static string Concat(string v1, string v2, string v3, string v4) { var s1 = v1 ?? string.Empty; var s2 = v2 ?? string.Empty; var s3 = v3 ?? string.Empty; var s4 = v4 ?? string.Empty; StringBuilder b = new StringBuilder(s1.Length + s2.Length + s3.Length + s4.Length); b.Append(s1); b.Append(s2); b.Append(s3); b.Append(s4); return b.ToString(); } /// <summary> /// Gets a concatenation of the string representation of the given values. /// </summary> public static string Concat(params string[] args) { if (args == null) throw new ArgumentNullException("args"); var sb = new StringBuilder(); var length = args.Length; for (var i = 0; i < length; i++) { var arg = args[i]; if (arg != null) sb.Append(arg); } return sb.ToString(); } /// <summary> /// Is this string equal to the given string? /// </summary> [Inline] public bool Equals(string other) { return Equals((object) other); } /// <summary> /// Is string a equal to string b? /// </summary> [Inline] public static bool Equals(string a, string b) { if (ReferenceEquals(a, b)) return true; if (a == null) return b == null; return a.Equals((object)b); } [Inline] public static bool Equals(string a, string b, StringComparison comparisonType) { if (a == null) return b == null; return Compare(a, b, comparisonType) == 0; } /// <summary> /// Return a new string in which all occurrences of the given old value have been replaced with the given new value. /// </summary> [Inline] public string Replace(string oldValue, string newValue) { return Replace((ICharSequence) oldValue, (ICharSequence) newValue); } [Inline] public string ToUpper(CultureInfo culture) { return ToUpper(culture.Locale); } [Inline] public string ToUpperInvariant() { return ToUpper(CultureInfo.InvariantCulture); } [Inline] public string ToLower(CultureInfo culture) { return ToLower(culture.Locale); } [Inline] public string ToLowerInvariant() { return ToLower(CultureInfo.InvariantCulture); } /// <summary> /// Removes all leading and trailing occurrences of a set of characters specified in an array from the current object. /// </summary> public string Trim(params char[] trimChars) { if (Length == 0) return Empty; int start = 0; if (trimChars != null && trimChars.Length != 0) start = FindNotInTable(0, Length, 1, trimChars); int end = 0; if (trimChars != null && trimChars.Length != 0) end = FindNotInTable(Length - 1, -1, -1, trimChars); end++; if (start == 0 && end == Length) return this; return JavaSubstring(start, end); } /// <summary> /// Removes all leading occurrences of a set of characters specified in an array from the current object. /// </summary> public string TrimStart(params char[] trimChars) { if (Length == 0) return Empty; int start = 0; if (trimChars != null && trimChars.Length != 0) start = FindNotInTable(0, Length, 1, trimChars); if (start == 0) return this; return JavaSubstring(start, Length); } /// <summary> /// Removes all trailing occurrences of a set of characters specified in an array from the current object. /// </summary> public String TrimEnd(params char[] trimChars) { if (Length == 0) return Empty; int end = 0; if (trimChars != null && trimChars.Length != 0) end = FindNotInTable(Length - 1, -1, -1, trimChars); end++; if (end == Length) return this; return JavaSubstring(0, end); } private int FindNotInTable(int pos, int target, int change, char[] table) { while (pos != target) { char c = this[pos]; int x = 0; while (x < table.Length) { if (c == table[x]) break; x++; } if (x == table.Length) return pos; pos += change; } return pos; } /// <summary> /// Is string a equal to string b? /// </summary> public static bool operator ==(string a, string b) { return Equals(a, b); } /// <summary> /// Is string a not equal to string b? /// </summary> public static bool operator !=(string a, string b) { if (ReferenceEquals(a, b)) return false; return !Equals(a, b); } IEnumerator<char> IEnumerable<char>.GetEnumerator() { // The C# compiler will actually not call this method // when using a string in foreach, but instead generate // optimized code. return new StringEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<char>)this).GetEnumerator(); } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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. #endregion // License using System.Linq; namespace Bam.Core { /// <summary> /// Static utility class with useful package related methods. /// </summary> public static class PackageUtilities { /// <summary> /// Central definition of what the Bam sub-folder is called. /// </summary> public static readonly string BamSubFolder = "bam"; /// <summary> /// Central definition of what the scripts sub-folder is called. /// </summary> public static readonly string ScriptsSubFolder = "Scripts"; /// <summary> /// Utility method to create a new package. /// </summary> public static void MakePackage() { var packageDir = Graph.Instance.ProcessState.WorkingDirectory; var bamDir = System.IO.Path.Combine(packageDir, BamSubFolder); if (System.IO.Directory.Exists(bamDir)) { throw new Exception($"Cannot create new package: A Bam package already exists at {packageDir}"); } var packageNameArgument = new Options.PackageName(); var packageName = CommandLineProcessor.Evaluate(packageNameArgument); if (null == packageName) { throw new Exception($"Cannot create new package: No name was defined. Use {(packageNameArgument as ICommandLineArgument).LongName} on the command line to specify it."); } var packageVersion = CommandLineProcessor.Evaluate(new Options.PackageVersion()); Graph.Instance.SkipPackageSourceDownloads = true; var definition = new PackageDefinition(bamDir, packageName, packageVersion); IOWrapper.CreateDirectory(bamDir); definition.Write(); var scriptsDir = System.IO.Path.Combine(bamDir, ScriptsSubFolder); IOWrapper.CreateDirectory(scriptsDir); var initialScriptFile = System.IO.Path.Combine(scriptsDir, packageName) + ".cs"; using (System.IO.TextWriter writer = new System.IO.StreamWriter(initialScriptFile)) { writer.NewLine = "\n"; writer.WriteLine("using Bam.Core;"); writer.WriteLine($"namespace {packageName}"); writer.WriteLine("{"); writer.WriteLine(" // write modules here ..."); writer.WriteLine("}"); } Log.Info($"Package {definition.FullName} was successfully created at {packageDir}"); } /// <summary> /// Utility method for adding a dependent package to the master package. /// </summary> public static void AddDependentPackage() { var packageNameArgument = new Options.PackageName(); var packageName = CommandLineProcessor.Evaluate(packageNameArgument); if (null == packageName) { throw new Exception($"No name was defined. Use {(packageNameArgument as ICommandLineArgument).LongName} on the command line to specify it."); } var packageVersion = CommandLineProcessor.Evaluate(new Options.PackageVersion()); Graph.Instance.SkipPackageSourceDownloads = true; var masterPackage = GetMasterPackage(); if (!default((string name, string version, bool? isDefault)).Equals(masterPackage.Dependents.FirstOrDefault(item => item.name.Equals(packageName, System.StringComparison.Ordinal) && item.version.Equals(packageVersion, System.StringComparison.Ordinal)))) { if (null != packageVersion) { throw new Exception($"Package dependency {packageName}, version {packageVersion}, is already present"); } else { throw new Exception($"Package dependency {packageName} is already present"); } } (string name, string version, bool? isDefault) newDepTuple = (packageName, packageVersion, null); masterPackage.Dependents.Add(newDepTuple); // TODO: this is unfortunate having to write the file in order to use it with IdentifyAllPackages masterPackage.Write(); // validate that the addition is ok try { PackageUtilities.IdentifyAllPackages(false); } catch (Exception exception) { masterPackage.Dependents.Remove(newDepTuple); masterPackage.Write(); throw new Exception(exception, "Failed to add dependent. Are all necessary package repositories specified?"); } } /// <summary> /// Utility method for setting the default version of a dependent package in the master package. /// </summary> public static void SetDependentDefaultVersion() { var packageNameArgument = new Options.PackageName(); var packageName = CommandLineProcessor.Evaluate(packageNameArgument); if (null == packageName) { throw new Exception($"No name was defined. Use {(packageNameArgument as ICommandLineArgument).LongName} on the command line to specify it."); } Graph.Instance.SkipPackageSourceDownloads = true; var masterPackage = GetMasterPackage(); if (!masterPackage.Dependents.Any(item => item.name.Equals(packageName, System.StringComparison.Ordinal))) { throw new Exception($"Package dependency {packageName} is not present"); } var packageVersionArgument = new Options.PackageVersion(); var packageVersion = CommandLineProcessor.Evaluate(packageVersionArgument); if (null == packageVersion) { throw new Exception($"No version was defined. Use {(packageVersionArgument as ICommandLineArgument).LongName} on the command line to specify it."); } // set the new default version var newDefaultVersion = masterPackage.Dependents.FirstOrDefault(item => item.name.Equals(packageName, System.StringComparison.Ordinal) && item.version.Equals(packageVersion, System.StringComparison.Ordinal)); if (default((string name, string version, bool? isDefault)).Equals(newDefaultVersion)) { throw new Exception($"Package dependency {packageName}-{packageVersion} is not present"); } masterPackage.Dependents.Remove(newDefaultVersion); masterPackage.Dependents.Add((packageName, packageVersion, true)); // all other versions are not default var nonDefaultVersions = masterPackage.Dependents.Where(item => item.name.Equals(packageName, System.StringComparison.Ordinal) && !item.version.Equals(packageVersion, System.StringComparison.Ordinal)).ToList(); foreach (var dep in nonDefaultVersions) { masterPackage.Dependents.Remove(dep); masterPackage.Dependents.Add((dep.name, dep.version, null)); } masterPackage.Write(); } /// <summary> /// Get the preprocessor define specifying the Bam Core version. /// </summary> /// <value>The version define for compiler.</value> public static string VersionDefineForCompiler { get { var coreVersion = Graph.Instance.ProcessState.Version; var coreVersionDefine = $"BAM_CORE_VERSION_{coreVersion.Major}_{coreVersion.Minor}_{coreVersion.Revision}"; return coreVersionDefine; } } /// <summary> /// Get the preprocessor define specifying the host OS. /// </summary> /// <value>The host platform define for compiler.</value> public static string HostPlatformDefineForCompiler => Platform.ToString(OSUtilities.CurrentPlatform, '\0', "BAM_HOST_", true); /// <summary> /// Determine if a path is configured as a package. /// </summary> /// <returns><c>true</c> if is package directory the specified packagePath; otherwise, <c>false</c>.</returns> /// <param name="packagePath">Package path.</param> public static bool IsPackageDirectory( string packagePath) { var bamDir = System.IO.Path.Combine(packagePath, BamSubFolder); if (!System.IO.Directory.Exists(bamDir)) { throw new Exception($"Path {packagePath} does not form a BAM! package: missing '{BamSubFolder}' subdirectory"); } return true; } /// <summary> /// Get the XML pathname for the package. /// </summary> /// <returns>The package definition pathname.</returns> /// <param name="packagePath">Package path.</param> public static string GetPackageDefinitionPathname( string packagePath) { var bamDir = System.IO.Path.Combine(packagePath, BamSubFolder); var xmlFiles = System.IO.Directory.GetFiles(bamDir, "*.xml", System.IO.SearchOption.AllDirectories); if (0 == xmlFiles.Length) { throw new Exception($"No package definition .xml files found under {bamDir}"); } if (xmlFiles.Length > 1) { var message = new System.Text.StringBuilder(); message.AppendLine($"Too many .xml files found under {bamDir}"); foreach (var file in xmlFiles) { message.AppendLine($"\t{file}"); } throw new Exception(message.ToString()); } return xmlFiles[0]; } /// <summary> /// Get the package in which Bam is executed. /// </summary> /// <returns>The master package.</returns> public static PackageDefinition GetMasterPackage() { var workingDir = Graph.Instance.ProcessState.WorkingDirectory; var isWorkingPackageWellDefined = IsPackageDirectory(workingDir); if (!isWorkingPackageWellDefined) { throw new Exception("Working directory package is not well defined"); } var parentDir = System.IO.Path.GetDirectoryName(workingDir); var repository = Graph.Instance.AddPackageRepository(parentDir); var masterDefinitionFile = repository.FindPackage(GetPackageDefinitionPathname(workingDir)); if (null == masterDefinitionFile) { // could not find the master package in either an unstructured, or structured (packages) repository // try in the tests folder if this is part of a structured repository if (repository.HasTests) { repository.ScanTestPackages(); masterDefinitionFile = repository.FindPackage(GetPackageDefinitionPathname(workingDir)); } if (null == masterDefinitionFile) { throw new Exception("Unable to locate master package in any repository"); } } // the package will have been read already, so re-read it in the context of a master package masterDefinitionFile.ReReadAsMaster(); return masterDefinitionFile; } private static void ProcessPackagesIntoTree( System.Collections.Generic.Queue<(string name, string version, Array<PackageTreeNode> parents)> queue, System.Collections.Generic.Dictionary<(string name, string version), PackageTreeNode> packageMap) { while (queue.Any()) { var defn = queue.Dequeue(); var defnKey = (defn.name, defn.version); Log.DebugMessage($"Considering package {defn.name}-{defn.version} and its dependents"); PackageDefinition defFile; PackageTreeNode packageNode; if (packageMap.ContainsKey(defnKey) && packageMap[defnKey].Definition != null) { packageNode = packageMap[defnKey]; defFile = packageNode.Definition; } else { PackageDefinition findPackageInRepositories( (string name, string version) packageDesc) { foreach (var repo in Graph.Instance.PackageRepositories) { var definition = repo.FindPackage(packageDesc); if (null != definition) { Log.DebugMessage($"\tFound {packageDesc.name}-{packageDesc.version} in repo {repo.RootPath}"); return definition; } } return null; } defFile = findPackageInRepositories(defnKey); if (null != defFile) { packageNode = new PackageTreeNode(defFile); } else { packageNode = new PackageTreeNode(defnKey.name, defnKey.version); } if (packageMap.ContainsKey(defnKey)) { // since a placeholder is being replaced System.Diagnostics.Debug.Assert(null == packageMap[defnKey].Definition); packageMap[defnKey].RemoveFromParents(); packageMap.Remove(defnKey); } packageMap.Add(defnKey, packageNode); if (defn.parents != null) { foreach (var parent in defn.parents) { parent.AddChild(packageNode); } } } if (null == defFile) { // package not found, defer this for later continue; } foreach (var (name, version, isDefault) in defFile.Dependents) { var key = (name, version); if (!packageMap.ContainsKey(key)) { var match = queue.FirstOrDefault(item => item.name == key.name && item.version == key.version); if (default((string name, string version, Array<PackageTreeNode> parents)).Equals(match)) { Log.DebugMessage($"\tQueuing up {name}-{version}..."); queue.Enqueue((key.name, key.version, new Array<PackageTreeNode>(packageNode))); } else { match.parents.Add(packageNode); } continue; } Log.DebugMessage($"\tPackage {name}-{version} already encountered"); var depNode = packageMap[key]; packageNode.AddChild(depNode); } } } // this is breadth-first traversal, so that the details of packages are explored // at the highest level, not on the first encounter in a depth-first search private static void DumpTreeInternal( PackageTreeNode node, int depth, System.Collections.Generic.Dictionary<PackageTreeNode, int> encountered, Array<PackageTreeNode> displayed) { if (!encountered.ContainsKey(node)) { encountered.Add(node, depth); } foreach (var child in node.Children) { if (!encountered.ContainsKey(child)) { encountered.Add(child, depth + 1); } } var indent = new string('\t', depth); if (null != node.Definition) { Log.DebugMessage($"{indent}{node.Definition.FullName}"); } else { Log.DebugMessage($"{indent}{node.Name}-{node.Version} ***** undiscovered *****"); } if (encountered[node] < depth) { return; } if (displayed.Contains(node)) { return; } else { displayed.Add(node); } foreach (var child in node.Children) { DumpTreeInternal(child, depth + 1, encountered, displayed); } } private static void DumpTree( PackageTreeNode node) { Log.DebugMessage("-- Dumping the package tree"); var encountered = new System.Collections.Generic.Dictionary<PackageTreeNode, int>(); var displayed = new Array<PackageTreeNode>(); DumpTreeInternal(node, 0, encountered, displayed); Log.DebugMessage("-- Dumping the package tree - DONE"); } private static void ValidatePackageSpecifiers( PackageTreeNode rootNode, Array<StringArray> packageVersionSpecifiers) { foreach (var specifier in packageVersionSpecifiers) { var matches = rootNode.MatchingPackages(specifier.First()); var matchingVersions = matches.Select(item => item.Version); if (!matchingVersions.Any()) { Log.Info($"Warning: Command line version specifier --{specifier.First()}.version={specifier.Last()} is redundant. Ignoring."); continue; } if (!matchingVersions.Contains(specifier.Last())) { var message = new System.Text.StringBuilder(); message.AppendLine($"Command line version specifier --{specifier.First()}.version={specifier.Last()} does not match any packages in the definition file:"); foreach (var match in matches) { message.AppendLine($"\t{match.Name}-{match.Version}"); } throw new Exception(message.ToString()); } } } private static void ResolveDuplicatePackages( PackageTreeNode rootNode, PackageDefinition masterDefinitionFile, Array<StringArray> packageVersionSpecifiers) { var duplicatePackageNames = rootNode.DuplicatePackageNames; if (duplicatePackageNames.Any()) { Log.DebugMessage("Duplicate packages found"); foreach (var name in duplicatePackageNames) { Log.DebugMessage($"\tResolving duplicates for {name}..."); var duplicates = rootNode.DuplicatePackages(name); // package version specifiers take precedence var specifierMatch = packageVersionSpecifiers.FirstOrDefault(item => item.First().Equals(name)); System.Collections.Generic.IEnumerable<PackageTreeNode> duplicatesToRemove = null; if (null != specifierMatch) { Log.DebugMessage($"\t\tCommand line package specifier wants version {specifierMatch.Last()}"); duplicatesToRemove = duplicates.Where(item => item.Version != specifierMatch.Last() ); foreach (var toRemove in duplicatesToRemove) { toRemove.RemoveFromParents(); } } else { // does the master package specify a default for this package? var masterPackageMatch = masterDefinitionFile.Dependents.FirstOrDefault(item => item.name == name && item.isDefault.HasValue && item.isDefault.Value); if (!default((string name, string version, bool? isDefault)).Equals(masterPackageMatch)) { Log.DebugMessage($"\t\tMaster package specifies version {masterPackageMatch.version} is default"); duplicatesToRemove = duplicates.Where(item => item.Version != masterPackageMatch.version ); foreach (var toRemove in duplicatesToRemove.ToList()) { toRemove.RemoveFromParents(); } } } // and if that has reduced the duplicates for this package down to a single version, we're good to carry on duplicates = rootNode.DuplicatePackages(name); var numDuplicates = duplicates.Count(); if (1 == numDuplicates) { continue; } // otherwise, error var resolveErrorMessage = new System.Text.StringBuilder(); if (numDuplicates > 0) { resolveErrorMessage.AppendLine($"Unable to resolve to a single version of package {name}. Use --{name}.version=<version> to resolve."); resolveErrorMessage.AppendLine("Available versions of the package are:"); foreach (var dup in duplicates) { resolveErrorMessage.AppendLine($"\t{dup.Version}"); } } else { resolveErrorMessage.AppendLine($"No version of package {name} has been determined to be available."); if (duplicatesToRemove != null && duplicatesToRemove.Any()) { resolveErrorMessage.AppendLine($"If there were any references to {name}, they may have been removed from consideration by the following packages being discarded:"); foreach (var removed in duplicatesToRemove) { resolveErrorMessage.AppendLine($"\t{removed.Definition.FullName}"); } } resolveErrorMessage.AppendLine($"Please add an explicit dependency to (a version of) the {name} package either in your master package or one of its dependencies."); } throw new Exception(resolveErrorMessage.ToString()); } } } private static void InjectExtraModules( PackageDefinition intoPackage) { var injectPackages = CommandLineProcessor.Evaluate(new Options.InjectDefaultPackage()); if (null != injectPackages) { foreach (var injected in injectPackages) { var name = injected[0]; string version = null; if (injected.Count > 1) { version = injected[1].TrimStart(new[] { '-' }); // see regex in InjectDefaultPackage } var is_default = true; intoPackage.Dependents.AddUnique((name, version, is_default)); } } } /// <summary> /// Scan though all package repositories for all package dependencies, and resolve any duplicate package names /// by either data in the package definition file, or on the command line, by specifying a particular version to /// use. The master package definition file is the source of disambiguation for package versions. /// </summary> /// <param name="allowDuplicates">If set to <c>true</c> allow duplicates. Used to show the full extent of the definition file.</param> /// <param name="enforceBamAssemblyVersions">If set to <c>true</c> enforce bam assembly versions.</param> /// <param name="noThrow">If set to <c>true</c> do not throw under exceptional circumstances. Used to show the full extent of the definition file.</param> public static PackageTreeNode IdentifyAllPackages( bool allowDuplicates = false, bool enforceBamAssemblyVersions = true, bool noThrow = false) { var masterDefinitionFile = GetMasterPackage(); // inject any packages from the command line into the master definition file // and these will be defaults InjectExtraModules(masterDefinitionFile); System.Collections.Generic.Dictionary<(string name, string version), PackageTreeNode> packageMap = new System.Collections.Generic.Dictionary<(string name, string version), PackageTreeNode>(); (string name, string version) masterDefn = (masterDefinitionFile.Name, masterDefinitionFile.Version); System.Collections.Generic.Queue<(string name, string version, Array<PackageTreeNode> parents)> queue = new System.Collections.Generic.Queue<(string name, string version, Array<PackageTreeNode> parents)>(); queue.Enqueue((masterDefn.name, masterDefn.version, null)); Log.DebugMessage("-- Starting package dependency evaluation... --"); var firstCount = 0; ProcessPackagesIntoTree(queue, packageMap); var secondCount = packageMap.Count; var rootNode = packageMap.First(item => item.Key == masterDefn).Value; var packageVersionSpecifiers = CommandLineProcessor.Evaluate(new Options.PackageDefaultVersion()); ValidatePackageSpecifiers(rootNode, packageVersionSpecifiers); DumpTree(rootNode); if (!allowDuplicates) { // resolve duplicates before trying to find packages that weren't found // otherwise you may use package roots for packages that will be discarded ResolveDuplicatePackages(rootNode, masterDefinitionFile, packageVersionSpecifiers); } DumpTree(rootNode); var undiscovered = rootNode.UndiscoveredPackages; while (undiscovered.Any() && (firstCount != secondCount)) { Log.DebugMessage($"{undiscovered.Count()} packages not found:"); foreach (var package in undiscovered) { Log.DebugMessage($"\t{package.Name}-{package.Version}"); } var repoPaths = rootNode.PackageRepositoryPaths; Log.DebugMessage($"Implicit repo paths to add:"); foreach (var path in repoPaths) { Log.DebugMessage($"\t{path}"); Graph.Instance.AddPackageRepository(path, masterDefinitionFile); } foreach (var package in undiscovered) { queue.Enqueue((package.Name, package.Version, new Array<PackageTreeNode>(package.Parents))); } firstCount = secondCount; ProcessPackagesIntoTree(queue, packageMap); secondCount = packageMap.Count; if (!allowDuplicates) { ResolveDuplicatePackages(rootNode, masterDefinitionFile, packageVersionSpecifiers); } DumpTree(rootNode); undiscovered = rootNode.UndiscoveredPackages; } if (undiscovered.Any() && !noThrow) { var message = new System.Text.StringBuilder(); message.AppendLine("Some packages were not found in any repository:"); foreach (var package in undiscovered) { if (null != package.Version) { message.AppendLine($"\t{package.Name}-{package.Version}"); } else { message.AppendLine($"\t{package.Name}"); } } message.AppendLine("Searched for in the following repositories:"); foreach (var repo in Graph.Instance.PackageRepositories) { message.AppendLine($"\t{repo.ToString()}"); } throw new Exception(message.ToString()); } Log.DebugMessage("-- Completed package dependency evaluation --"); var packageDefinitions = rootNode.UniquePackageDefinitions; if (enforceBamAssemblyVersions) { // for all packages that make up this assembly, ensure that their requirements on the version of the Bam // assemblies are upheld, prior to compiling the code foreach (var pkgDefn in packageDefinitions) { pkgDefn.ValidateBamAssemblyRequirements(); } } Graph.Instance.SetPackageDefinitions(packageDefinitions); return rootNode; } /// <summary> /// Compile the package assembly, using all the source files from the dependent packages. /// Throws Bam.Core.Exceptions if package compilation fails. /// </summary> /// <param name="enforceBamAssemblyVersions">If set to <c>true</c> enforce bam assembly versions. Default is true.</param> /// <param name="enableClean">If set to <c>true</c> cleaning the build root is allowed. Default is true.</param> public static void CompilePackageAssembly( bool enforceBamAssemblyVersions = true, bool enableClean = true) { // validate build root if (null == Graph.Instance.BuildRoot) { throw new Exception("Build root has not been specified"); } var gatherSourceProfile = new TimeProfile(ETimingProfiles.GatherSource); gatherSourceProfile.StartProfile(); IdentifyAllPackages( enforceBamAssemblyVersions: enforceBamAssemblyVersions ); var cleanFirst = CommandLineProcessor.Evaluate(new Options.CleanFirst()); if (enableClean && cleanFirst && System.IO.Directory.Exists(Graph.Instance.BuildRoot)) { Log.Info($"Deleting build root '{Graph.Instance.BuildRoot}'"); try { // make sure no files are read-only, which may have happened as part of collation preserving file attributes var dirInfo = new System.IO.DirectoryInfo(Graph.Instance.BuildRoot); foreach (var file in dirInfo.EnumerateFiles("*", System.IO.SearchOption.AllDirectories)) { file.Attributes &= ~System.IO.FileAttributes.ReadOnly; } System.IO.Directory.Delete(Graph.Instance.BuildRoot, true); } catch (System.IO.IOException ex) { Log.Info($"Failed to delete build root, because {ex.Message}. Continuing"); } } BuildModeUtilities.ValidateBuildModePackage(); gatherSourceProfile.StopProfile(); var assemblyCompileProfile = new TimeProfile(ETimingProfiles.AssemblyCompilation); assemblyCompileProfile.StartProfile(); // assembly is written to the build root var cachedAssemblyPathname = System.IO.Path.Combine(Graph.Instance.BuildRoot, ".CachedPackageAssembly"); cachedAssemblyPathname = System.IO.Path.Combine(cachedAssemblyPathname, Graph.Instance.MasterPackage.Name) + ".dll"; var hashPathName = System.IO.Path.ChangeExtension(cachedAssemblyPathname, "hash"); var cacheAssembly = !CommandLineProcessor.Evaluate(new Options.DisableCacheAssembly()); string compileReason = null; if (Graph.Instance.CompileWithDebugSymbols) { compileReason = "debug symbols were enabled"; } else { if (cacheAssembly) { // gather source files var filenames = new StringArray(); var strings = new System.Collections.Generic.SortedSet<string>(); foreach (var package in Graph.Instance.Packages) { foreach (var scriptFile in package.GetScriptFiles(true)) { filenames.Add(scriptFile); } foreach (var define in package.Definitions) { strings.Add(define); } } // add/remove other definitions strings.Add(VersionDefineForCompiler); strings.Add(HostPlatformDefineForCompiler); foreach (var feature in Features.PreprocessorDefines) { strings.Add(feature); } // TODO: what if other packages need more assemblies? foreach (var assembly in Graph.Instance.MasterPackage.BamAssemblies) { var assemblyPath = System.IO.Path.Combine(Graph.Instance.ProcessState.ExecutableDirectory, assembly.Name) + ".dll"; var lastModifiedDate = System.IO.File.GetLastWriteTime(assemblyPath); strings.Add(lastModifiedDate.ToString()); } var compareResult = Hash.CompareAndUpdateHashFile( hashPathName, filenames, strings ); switch (compareResult) { case Hash.EHashCompareResult.HashFileDoesNotExist: compileReason = "no previously compiled package assembly exists"; break; case Hash.EHashCompareResult.HashesAreDifferent: compileReason = "package source has changed since the last compile"; break; case Hash.EHashCompareResult.HashesAreIdentical: Graph.Instance.ScriptAssemblyPathname = cachedAssemblyPathname; assemblyCompileProfile.StopProfile(); return; } } else { compileReason = "user has disabled package assembly caching"; // will not throw if the file doesn't exist System.IO.File.Delete(hashPathName); } } // use the compiler in the current runtime version to build the assembly of packages var clrVersion = System.Environment.Version.ToString(); var targetFramework = Graph.Instance.ProcessState.TargetFrameworkVersion != null ? (", targetting " + Graph.Instance.ProcessState.TargetFrameworkVersion) : string.Empty; Log.Detail($"Compiling package assembly, CLR {clrVersion}{targetFramework}, because {compileReason}."); var outputAssemblyPath = cachedAssemblyPathname; // this will create the build root directory as necessary IOWrapper.CreateDirectory(System.IO.Path.GetDirectoryName(outputAssemblyPath)); var projectPath = System.IO.Path.ChangeExtension(outputAssemblyPath, ".csproj"); var project = new ProjectFile(false, projectPath); project.Write(); try { var args = new System.Text.StringBuilder(); args.Append($"build {projectPath} "); if (Graph.Instance.CompileWithDebugSymbols) { args.Append("-c Debug "); } else { args.Append("-c Release "); } args.Append($"-o {System.IO.Path.GetDirectoryName(outputAssemblyPath)} "); args.Append("-v quiet "); var dotNetResult = OSUtilities.RunExecutable( "dotnet", args.ToString() ); Log.Info(dotNetResult.StandardOutput); } catch (RunExecutableException exception) { var escapedCompilerOutput = exception.Result.StandardOutput.Replace("{", "{{}").Replace("}", "}}"); throw new Exception( exception, $"Failed to build the packages:{System.Environment.NewLine}{escapedCompilerOutput}" ); } Log.DebugMessage($"Written assembly to '{outputAssemblyPath}'"); Graph.Instance.ScriptAssemblyPathname = outputAssemblyPath; assemblyCompileProfile.StopProfile(); } /// <summary> /// Load the compiled package assembly. /// </summary> public static void LoadPackageAssembly() { var assemblyLoadProfile = new TimeProfile(ETimingProfiles.LoadAssembly); assemblyLoadProfile.StartProfile(); System.Reflection.Assembly scriptAssembly = null; // don't scope the resolver with using, or resolving will fail! var resolver = new AssemblyResolver(Graph.Instance.ScriptAssemblyPathname); scriptAssembly = resolver.Assembly; Graph.Instance.ScriptAssembly = scriptAssembly; assemblyLoadProfile.StopProfile(); } } // https://samcragg.wordpress.com/2017/06/30/resolving-assemblies-in-net-core/ internal sealed class AssemblyResolver : System.IDisposable { private readonly Microsoft.Extensions.DependencyModel.Resolution.ICompilationAssemblyResolver assemblyResolver; private readonly Microsoft.Extensions.DependencyModel.DependencyContext dependencyContext; private readonly System.Runtime.Loader.AssemblyLoadContext loadContext; public AssemblyResolver(string path) { this.Assembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(path); this.dependencyContext = Microsoft.Extensions.DependencyModel.DependencyContext.Load(this.Assembly); this.assemblyResolver = new Microsoft.Extensions.DependencyModel.Resolution.CompositeCompilationAssemblyResolver (new Microsoft.Extensions.DependencyModel.Resolution.ICompilationAssemblyResolver[] { new Microsoft.Extensions.DependencyModel.Resolution.AppBaseCompilationAssemblyResolver(System.IO.Path.GetDirectoryName(path)), new Microsoft.Extensions.DependencyModel.Resolution.ReferenceAssemblyPathResolver(), new Microsoft.Extensions.DependencyModel.Resolution.PackageCompilationAssemblyResolver() }); this.loadContext = System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(this.Assembly); this.loadContext.Resolving += OnResolving; } public System.Reflection.Assembly Assembly { get; } public void Dispose() { this.loadContext.Resolving -= this.OnResolving; } private System.Reflection.Assembly OnResolving( System.Runtime.Loader.AssemblyLoadContext context, System.Reflection.AssemblyName name) { Log.DebugMessage($"Resolving: {name.FullName}"); bool NamesMatch(Microsoft.Extensions.DependencyModel.RuntimeLibrary runtime) { return runtime.Name.Equals(name.Name, System.StringComparison.OrdinalIgnoreCase); } Microsoft.Extensions.DependencyModel.RuntimeLibrary library = this.dependencyContext.RuntimeLibraries.FirstOrDefault(NamesMatch); if (library != null) { var wrapper = new Microsoft.Extensions.DependencyModel.CompilationLibrary( library.Type, library.Name, library.Version, library.Hash, library.RuntimeAssemblyGroups.SelectMany(g => g.AssetPaths), library.Dependencies, library.Serviceable); // note that for NuGet packages with multiple platform specific assemblies // there will be more than one library.RuntimeAssemblyGroups // if there are native dependencies on these, and the native dynamic libraries // are not beside the managed assembly (they won't be if read from the NuGet cache, but will // be if published and targeted for a runtime), then loading will fail var assemblies = new System.Collections.Generic.List<string>(); var result = this.assemblyResolver.TryResolveAssemblyPaths(wrapper, assemblies); if (assemblies.Any()) { return this.loadContext.LoadFromAssemblyPath(assemblies[0]); } // note that this can silently fail } return null; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 ASC.Api.Attributes; using ASC.Api.Exceptions; using ASC.Api.Projects.Wrappers; using ASC.Api.Utils; using ASC.Core; using ASC.Core.Tenants; using ASC.Core.Users; using ASC.MessagingSystem; using ASC.Projects.Core.Domain; using ASC.Projects.Engine; using ASC.Web.Core.Users; using ASC.Web.Studio.UserControls.Common.Comments; using ASC.Web.Studio.Utility.HtmlUtility; namespace ASC.Api.Projects { public partial class ProjectApi { #region comments ///<summary> ///Returns the information about the comment with the ID specified in the request ///</summary> ///<short> ///Get comment ///</short> ///<category>Comments</category> ///<param name="commentid">Comment ID</param> ///<returns>Comment</returns> ///<exception cref="ItemNotFoundException"></exception> [Read(@"comment/{commentid}")] public CommentWrapper GetComment(Guid commentid) { var comment = EngineFactory.CommentEngine.GetByID(commentid).NotFoundIfNull(); var entity = EngineFactory.CommentEngine.GetEntityByTargetUniqId(comment).NotFoundIfNull(); return new CommentWrapper(this, comment, entity); } /////<summary> /////Updates the seleted comment using the comment text specified in the request /////</summary> /////<short> /////Update comment /////</short> /////<category>Comments</category> /////<param name="commentid">comment ID</param> /////<param name="content">comment text</param> /////<returns>Comment</returns> /////<exception cref="ItemNotFoundException"></exception> /////<example> /////<![CDATA[ /////Sending data in application/json: ///// /////{ ///// text:"My comment text", ///// /////} ///// /////Sending data in application/x-www-form-urlencoded /////content=My%20comment%20text /////]]> /////</example> //[Update(@"comment/{commentid}")] //public CommentWrapper UpdateComments(Guid commentid, string content) //{ // var comment = EngineFactory.CommentEngine.GetByID(commentid).NotFoundIfNull(); // comment.Content = Update.IfNotEquals(comment.Content, content); // string type; // comment = SaveComment(comment, out type); // return new CommentWrapper(comment); //} ///<summary> ///Get preview ///</summary> ///<short> ///Get preview ///</short> ///<category>Comments</category> ///<param name="htmltext">html to create preview</param> ///<param name="commentid">guid of editing comment or empty string if comment is new</param> [Create(@"comment/preview")] public CommentInfo GetProjectCommentPreview(string htmltext, string commentid) { ProjectSecurity.DemandAuthentication(); var commentEngine = EngineFactory.CommentEngine; Comment comment; if (!string.IsNullOrEmpty(commentid)) { comment = commentEngine.GetByID(new Guid(commentid)); comment.Content = htmltext; } else { comment = new Comment { Content = htmltext, CreateOn = TenantUtil.DateTimeNow(), CreateBy = SecurityContext.CurrentAccount.ID }; } var creator = EngineFactory.ParticipantEngine.GetByID(comment.CreateBy).UserInfo; var info = new CommentInfo { CommentID = comment.OldGuidId.ToString(), UserID = comment.CreateBy, TimeStamp = comment.CreateOn, TimeStampStr = comment.CreateOn.Ago(), UserPost = creator.Title, Inactive = comment.Inactive, CommentBody = HtmlUtility.GetFull(comment.Content), UserFullName = DisplayUserSettings.GetFullUserName(creator), UserProfileLink = creator.GetUserProfilePageURL(), UserAvatarPath = creator.GetBigPhotoURL() }; return info; } ///<summary> ///Remove comment with the id specified in the request ///</summary> ///<short>Remove comment</short> ///<section>Comments</section> ///<param name="commentid">Comment ID</param> ///<returns>Comment id</returns> ///<category>Comments</category> [Delete("comment/{commentid}")] public string RemoveProjectComment(string commentid) { var commentEngine = EngineFactory.CommentEngine; var comment = commentEngine.GetByID(new Guid(commentid)).NotFoundIfNull(); comment.Inactive = true; var entity = commentEngine.GetEntityByTargetUniqId(comment); if (entity == null) return ""; ProjectSecurity.DemandEditComment(entity.Project, comment); commentEngine.SaveOrUpdate(comment); MessageService.Send(Request, MessageAction.TaskCommentDeleted, MessageTarget.Create(comment.ID), entity.Project.Title, entity.Title); return commentid; } /// <summary> /// /// </summary> /// <param name="parentcommentid"></param> /// <param name="entityid"></param> /// <param name="content"></param> /// <param name="type"></param> /// <category>Comments</category> /// <returns></returns> [Create("comment")] public CommentInfo AddProjectComment(string parentcommentid, int entityid, string content, string type) { if (string.IsNullOrEmpty(type) || !(new List<string> { "message", "task" }).Contains(type.ToLower())) throw new ArgumentException(); var isMessageComment = type.ToLower().Equals("message"); var comment = isMessageComment ? new Comment { Content = content, TargetUniqID = ProjectEntity.BuildUniqId<Message>(entityid) } : new Comment { Content = content, TargetUniqID = ProjectEntity.BuildUniqId<Task>(entityid) }; if (!string.IsNullOrEmpty(parentcommentid)) comment.Parent = new Guid(parentcommentid); var commentEngine = EngineFactory.CommentEngine; var entity = commentEngine.GetEntityByTargetUniqId(comment).NotFoundIfNull(); comment = commentEngine.SaveOrUpdateComment(entity, comment); MessageService.Send(Request, isMessageComment ? MessageAction.DiscussionCommentCreated : MessageAction.TaskCommentCreated, MessageTarget.Create(comment.ID), entity.Project.Title, entity.Title); return GetCommentInfo(null, comment, entity); } /// <summary> /// /// </summary> /// <param name="commentid"></param> /// <param name="content"></param> ///<category>Comments</category> /// <returns></returns> [Update("comment/{commentid}")] public string UpdateComment(string commentid, string content) { var commentEngine = EngineFactory.CommentEngine; var comment = commentEngine.GetByID(new Guid(commentid)); comment.Content = content; var entity = commentEngine.GetEntityByTargetUniqId(comment); if (entity == null) throw new Exception("Access denied."); commentEngine.SaveOrUpdateComment(entity, comment); MessageService.Send(Request, MessageAction.TaskCommentUpdated, MessageTarget.Create(comment.ID), entity.Project.Title, entity.Title); return HtmlUtility.GetFull(content); } internal CommentInfo GetCommentInfo(IEnumerable<Comment> allComments, Comment comment, ProjectEntity entity) { var creator = EngineFactory.ParticipantEngine.GetByID(comment.CreateBy).UserInfo; var oCommentInfo = new CommentInfo { TimeStamp = comment.CreateOn, TimeStampStr = comment.CreateOn.Ago(), CommentBody = HtmlUtility.GetFull(comment.Content), CommentID = comment.OldGuidId.ToString(), UserID = comment.CreateBy, UserFullName = creator.DisplayUserName(), UserProfileLink = creator.GetUserProfilePageURL(), Inactive = comment.Inactive, IsEditPermissions = ProjectSecurity.CanEditComment(entity, comment), IsResponsePermissions = ProjectSecurity.CanCreateComment(entity), IsRead = true, UserAvatarPath = creator.GetBigPhotoURL(), UserPost = creator.Title, CommentList = new List<CommentInfo>() }; if (allComments != null) foreach (var com in allComments.Where(com => com.Parent == comment.OldGuidId)) { oCommentInfo.CommentList.Add(GetCommentInfo(allComments, com, entity)); } return oCommentInfo; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.DataProtection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Identity.Test { /// <summary> /// Common functionality tests that all verifies user manager functionality regardless of store implementation /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> public abstract class IdentitySpecificationTestBase<TUser, TRole> : IdentitySpecificationTestBase<TUser, TRole, string> where TUser : class where TRole : class { } /// <summary> /// Base class for tests that exercise basic identity functionality that all stores should support. /// </summary> /// <typeparam name="TUser">The type of the user.</typeparam> /// <typeparam name="TRole">The type of the role.</typeparam> /// <typeparam name="TKey">The primary key type.</typeparam> public abstract class IdentitySpecificationTestBase<TUser, TRole, TKey> : UserManagerSpecificationTestBase<TUser, TKey> where TUser : class where TRole : class where TKey : IEquatable<TKey> { /// <summary> /// Configure the service collection used for tests. /// </summary> /// <param name="services"></param> /// <param name="context"></param> protected override void SetupIdentityServices(IServiceCollection services, object context) { services.AddHttpContextAccessor(); services.AddSingleton<IDataProtectionProvider, EphemeralDataProtectionProvider>(); services.AddIdentity<TUser, TRole>(options => { options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.User.AllowedUserNameCharacters = null; }).AddDefaultTokenProviders(); AddUserStore(services, context); AddRoleStore(services, context); services.AddLogging(); services.AddSingleton<ILogger<UserManager<TUser>>>(new TestLogger<UserManager<TUser>>()); services.AddSingleton<ILogger<RoleManager<TRole>>>(new TestLogger<RoleManager<TRole>>()); } /// <summary> /// Setup the IdentityBuilder /// </summary> /// <param name="services"></param> /// <param name="context"></param> /// <returns></returns> protected override IdentityBuilder SetupBuilder(IServiceCollection services, object context) { var builder = base.SetupBuilder(services, context); builder.AddRoles<TRole>(); AddRoleStore(services, context); services.AddSingleton<ILogger<RoleManager<TRole>>>(new TestLogger<RoleManager<TRole>>()); return builder; } /// <summary> /// Creates the role manager for tests. /// </summary> /// <param name="context">The context that will be passed into the store, typically a db context.</param> /// <param name="services">The service collection to use, optional.</param> /// <returns></returns> protected virtual RoleManager<TRole> CreateRoleManager(object context = null, IServiceCollection services = null) { if (services == null) { services = new ServiceCollection(); } if (context == null) { context = CreateTestContext(); } SetupIdentityServices(services, context); return services.BuildServiceProvider().GetService<RoleManager<TRole>>(); } /// <summary> /// Adds an IRoleStore to services for the test. /// </summary> /// <param name="services">The service collection to add to.</param> /// <param name="context">The context for the store to use, optional.</param> protected abstract void AddRoleStore(IServiceCollection services, object context = null); /// <summary> /// Creates a new test role instance. /// </summary> /// <param name="roleNamePrefix">Optional name prefix, name will be randomized.</param> /// <param name="useRoleNamePrefixAsRoleName">If true, the prefix should be used as the rolename without a random pad.</param> /// <returns></returns> protected abstract TRole CreateTestRole(string roleNamePrefix = "", bool useRoleNamePrefixAsRoleName = false); /// <summary> /// Query used to do name equality checks. /// </summary> /// <param name="roleName">The role name to match.</param> /// <returns>The query to use.</returns> protected abstract Expression<Func<TRole, bool>> RoleNameEqualsPredicate(string roleName); /// <summary> /// Query used to do user name prefix matching. /// </summary> /// <param name="roleName">The role name to match.</param> /// <returns>The query to use.</returns> protected abstract Expression<Func<TRole, bool>> RoleNameStartsWithPredicate(string roleName); /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanCreateRoleTest() { var manager = CreateRoleManager(); var roleName = "create" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); } private class AlwaysBadValidator : IUserValidator<TUser>, IRoleValidator<TRole>, IPasswordValidator<TUser> { public static readonly IdentityError ErrorMessage = new IdentityError { Description = "I'm Bad.", Code = "BadValidator" }; public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user, string password) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } public Task<IdentityResult> ValidateAsync(RoleManager<TRole> manager, TRole role) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } public Task<IdentityResult> ValidateAsync(UserManager<TUser> manager, TUser user) { return Task.FromResult(IdentityResult.Failed(ErrorMessage)); } } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task BadValidatorBlocksCreateRole() { var manager = CreateRoleManager(); manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); var role = CreateTestRole("blocked"); IdentityResultAssert.IsFailure(await manager.CreateAsync(role), AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanChainRoleValidators() { var manager = CreateRoleManager(); manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); manager.RoleValidators.Add(new AlwaysBadValidator()); var role = CreateTestRole("blocked"); var result = await manager.CreateAsync(role); IdentityResultAssert.IsFailure(result, AlwaysBadValidator.ErrorMessage); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code};{AlwaysBadValidator.ErrorMessage.Code}."); Assert.Equal(2, result.Errors.Count()); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task BadValidatorBlocksRoleUpdate() { var manager = CreateRoleManager(); var role = CreateTestRole("poorguy"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); var error = AlwaysBadValidator.ErrorMessage; manager.RoleValidators.Clear(); manager.RoleValidators.Add(new AlwaysBadValidator()); IdentityResultAssert.IsFailure(await manager.UpdateAsync(role), error); IdentityResultAssert.VerifyLogMessage(manager.Logger, $"Role {await manager.GetRoleIdAsync(role) ?? NullValue} validation failed: {AlwaysBadValidator.ErrorMessage.Code}."); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanDeleteRole() { var manager = CreateRoleManager(); var roleName = "delete" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.DeleteAsync(role)); Assert.False(await manager.RoleExistsAsync(roleName)); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanAddRemoveRoleClaim() { var manager = CreateRoleManager(); var role = CreateTestRole("ClaimsAddRemove"); var roleSafe = CreateTestRole("ClaimsAdd"); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(roleSafe)); Claim[] claims = { new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3") }; foreach (Claim c in claims) { IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(role, c)); IdentityResultAssert.IsSuccess(await manager.AddClaimAsync(roleSafe, c)); } var roleClaims = await manager.GetClaimsAsync(role); var safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(3, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[0])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(2, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[1])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(1, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); IdentityResultAssert.IsSuccess(await manager.RemoveClaimAsync(role, claims[2])); roleClaims = await manager.GetClaimsAsync(role); safeRoleClaims = await manager.GetClaimsAsync(roleSafe); Assert.Equal(0, roleClaims.Count); Assert.Equal(3, safeRoleClaims.Count); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanRoleFindById() { var manager = CreateRoleManager(); var role = CreateTestRole("FindByIdAsync"); Assert.Null(await manager.FindByIdAsync(await manager.GetRoleIdAsync(role))); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.Equal(role, await manager.FindByIdAsync(await manager.GetRoleIdAsync(role))); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanRoleFindByName() { var manager = CreateRoleManager(); var roleName = "FindByNameAsync" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); Assert.Null(await manager.FindByNameAsync(roleName)); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.Equal(role, await manager.FindByNameAsync(roleName)); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanUpdateRoleName() { var manager = CreateRoleManager(); var roleName = "update" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.SetRoleNameAsync(role, "Changed")); IdentityResultAssert.IsSuccess(await manager.UpdateAsync(role)); Assert.False(await manager.RoleExistsAsync("update")); Assert.Equal(role, await manager.FindByNameAsync("Changed")); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanQueryableRoles() { var manager = CreateRoleManager(); if (manager.SupportsQueryableRoles) { var roles = GenerateRoles("CanQuerableRolesTest", 4); foreach (var r in roles) { IdentityResultAssert.IsSuccess(await manager.CreateAsync(r)); } Expression<Func<TRole, bool>> func = RoleNameStartsWithPredicate("CanQuerableRolesTest"); Assert.Equal(roles.Count, manager.Roles.Count(func)); func = RoleNameEqualsPredicate("bogus"); Assert.Null(manager.Roles.FirstOrDefault(func)); } } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CreateRoleFailsIfExists() { var manager = CreateRoleManager(); var roleName = "dupeRole" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); Assert.False(await manager.RoleExistsAsync(roleName)); IdentityResultAssert.IsSuccess(await manager.CreateAsync(role)); Assert.True(await manager.RoleExistsAsync(roleName)); var role2 = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); IdentityResultAssert.IsFailure(await manager.CreateAsync(role2)); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanAddUsersToRole() { var context = CreateTestContext(); var manager = CreateManager(context); var roleManager = CreateRoleManager(context); var roleName = "AddUserTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role)); TUser[] users = { CreateTestUser("1"),CreateTestUser("2"),CreateTestUser("3"),CreateTestUser("4"), }; foreach (var u in users) { IdentityResultAssert.IsSuccess(await manager.CreateAsync(u)); IdentityResultAssert.IsSuccess(await manager.AddToRoleAsync(u, roleName)); Assert.True(await manager.IsInRoleAsync(u, roleName)); } } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanGetRolesForUser() { var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var users = GenerateUsers("CanGetRolesForUser", 4); var roles = GenerateRoles("CanGetRolesForUserRole", 4); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u)); } foreach (var r in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, await roleManager.GetRoleNameAsync(r))); Assert.True(await userManager.IsInRoleAsync(u, await roleManager.GetRoleNameAsync(r))); } } foreach (var u in users) { var rs = await userManager.GetRolesAsync(u); Assert.Equal(roles.Count, rs.Count); foreach (var r in roles) { var expectedRoleName = await roleManager.GetRoleNameAsync(r); Assert.Contains(rs, role => role == expectedRoleName); } } } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task RemoveUserFromRoleWithMultipleRoles() { var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userManager.CreateAsync(user)); var roles = GenerateRoles("RemoveUserFromRoleWithMultipleRoles", 4); foreach (var r in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(user, await roleManager.GetRoleNameAsync(r))); Assert.True(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(r))); } IdentityResultAssert.IsSuccess(await userManager.RemoveFromRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2]))); Assert.False(await userManager.IsInRoleAsync(user, await roleManager.GetRoleNameAsync(roles[2]))); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanRemoveUsersFromRole() { var context = CreateTestContext(); var userManager = CreateManager(context); var roleManager = CreateRoleManager(context); var users = GenerateUsers("CanRemoveUsersFromRole", 4); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.CreateAsync(u)); } var r = CreateTestRole("r1"); var roleName = await roleManager.GetRoleNameAsync(r); IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(r)); foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.AddToRoleAsync(u, roleName)); Assert.True(await userManager.IsInRoleAsync(u, roleName)); } foreach (var u in users) { IdentityResultAssert.IsSuccess(await userManager.RemoveFromRoleAsync(u, roleName)); Assert.False(await userManager.IsInRoleAsync(u, roleName)); } } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task RemoveUserNotInRoleFails() { var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); var result = await userMgr.RemoveFromRoleAsync(user, roleName); IdentityResultAssert.IsFailure(result, _errorDescriber.UserNotInRole(roleName)); IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User is not in role {roleName}."); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task AddUserToRoleFailsIfAlreadyInRole() { var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); IdentityResultAssert.IsSuccess(await userMgr.AddToRoleAsync(user, roleName)); Assert.True(await userMgr.IsInRoleAsync(user, roleName)); IdentityResultAssert.IsFailure(await userMgr.AddToRoleAsync(user, roleName), _errorDescriber.UserAlreadyInRole(roleName)); IdentityResultAssert.VerifyLogMessage(userMgr.Logger, $"User is already in role {roleName}."); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task AddUserToRolesIgnoresDuplicates() { var context = CreateTestContext(); var userMgr = CreateManager(context); var roleMgr = CreateRoleManager(context); var roleName = "addUserDupeTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await userMgr.CreateAsync(user)); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.False(await userMgr.IsInRoleAsync(user, roleName)); IdentityResultAssert.IsSuccess(await userMgr.AddToRolesAsync(user, new[] { roleName, roleName })); Assert.True(await userMgr.IsInRoleAsync(user, roleName)); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanFindRoleByNameWithManager() { var roleMgr = CreateRoleManager(); var roleName = "findRoleByNameTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.NotNull(await roleMgr.FindByNameAsync(roleName)); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanFindRoleWithManager() { var roleMgr = CreateRoleManager(); var roleName = "findRoleTest" + Guid.NewGuid().ToString(); var role = CreateTestRole(roleName, useRoleNamePrefixAsRoleName: true); IdentityResultAssert.IsSuccess(await roleMgr.CreateAsync(role)); Assert.Equal(roleName, await roleMgr.GetRoleNameAsync(await roleMgr.FindByNameAsync(roleName))); } /// <summary> /// Test. /// </summary> /// <returns>Task</returns> [Fact] public async Task CanGetUsersInRole() { var context = CreateTestContext(); var manager = CreateManager(context); var roleManager = CreateRoleManager(context); var roles = GenerateRoles("UsersInRole", 4); var roleNameList = new List<string>(); foreach (var role in roles) { IdentityResultAssert.IsSuccess(await roleManager.CreateAsync(role)); roleNameList.Add(await roleManager.GetRoleNameAsync(role)); } for (int i = 0; i < 6; i++) { var user = CreateTestUser(); IdentityResultAssert.IsSuccess(await manager.CreateAsync(user)); if ((i % 2) == 0) { IdentityResultAssert.IsSuccess(await manager.AddToRolesAsync(user, roleNameList)); } } foreach (var role in roles) { Assert.Equal(3, (await manager.GetUsersInRoleAsync(await roleManager.GetRoleNameAsync(role))).Count); } Assert.Equal(0, (await manager.GetUsersInRoleAsync("123456")).Count); } private List<TRole> GenerateRoles(string namePrefix, int count) { var roles = new List<TRole>(count); for (var i = 0; i < count; i++) { roles.Add(CreateTestRole(namePrefix + i)); } return roles; } } }
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Collections.Generic; using DwarfCMD; using DwarfTree; using Isis; namespace DwarfServer { //TODO: Add logging of some sort to servers - Hook into Isis logging? public class DwarfServer : DwarfCMD.DwarfCMD { const int DEFAULT_PORT_NUM = 9845; //!< Default port number (Isis' default + 2) private IPHostEntry iphost; //!< IP entry point for this host private TcpListener tcpServer; //!< TCP server listener private TcpClient tcpClient; //!< TCP client connection private NetworkStream networkStream; //!< Network stream for message passing private DwarfTree.DwarfTree nodeSys; //!< Underlying node file system /** Initializes a server with a given/default port number. * * @param portnum Default port number or user override. * */ public DwarfServer(int portnum = DEFAULT_PORT_NUM) { // Set this to our actual IP (according to DNS) this.iphost = Dns.GetHostEntry(Dns.GetHostName()); // Set the server to listen for connections on the Isis default port num + 2 this.tcpServer = new TcpListener(new IPEndPoint(iphost.AddressList[0], portnum)); this.tcpClient = null; this.networkStream = null; // Initialize command parsing/handling from DwarfCMD base.dwarfCmds = new Dictionary<string, dwarfCmd>(); base.dwarfCmds["create"] = this.create; base.dwarfCmds["rmr"] = this.delete; base.dwarfCmds["get"] = this.getNode; base.dwarfCmds["set"] = this.setNode; base.dwarfCmds["stat"] = this.stat; base.dwarfCmds["ls"] = this.getChildren; base.dwarfCmds["sync"] = this.sync; //TODO: Eventually implement (maybe) // Start a new DwarfTree instance for this server instance nodeSys = DwarfTree.DwarfTree.CreateTree(); } /** Create the node at path - CLI command is "create". */ private void create(string args) { string[] argslst = args.Split(); if(argslst.Length < 2) { return; } //TODO support ACL inputs //TODO support error messages on bad node adds bool success = nodeSys.addNode(argslst[0], argslst[1]); throw new NotImplementedException("create is not implemented."); } private void delete(string args) { string[] argslst = args.Split(); if(argslst.Length < 1) { return; } //TODO: Enable Logging & user feedback bool success = nodeSys.removeNode(argslst[0]); throw new NotImplementedException("rmr is not implemented."); } private void getNode(string args) { //TODO Support watches string[] argslst = args.Split(); if(argslst.Length < 1) { return; } Dictionary<string, string> stat = nodeSys.getNode(argslst[0]); throw new NotImplementedException("get is not implemented."); } private void setNode(string args) { string[] argslst = args.Split(); if(argslst.Length < 2) { return; } bool success = nodeSys.setData(argslst[0], argslst[1]); throw new NotImplementedException("set is not implemented."); } private void stat(string args) { //TODO Support watches string[] argslst = args.Split(); if(argslst.Length < 1) { return; } Dictionary<string, string> stats = nodeSys.getNodeInfo(argslst[0]); throw new NotImplementedException("stat is not implemented."); } private void getChildren(string args) { //TODO Support watches string[] argslst = args.Split(); if(argslst.Length < 1) { return; } Dictionary<string, string> stats = nodeSys.getChildList(argslst[0]); throw new NotImplementedException("ls is not implemented."); } private void sync(string args) { throw new NotImplementedException("Sync is not implemented."); } /** Starts the TCP server on localhost with port number. * */ public void serverStart() { Console.WriteLine("Starting Server on " + this.tcpServer.ToString()); //TODO: What to do server is still active. No-op? this.tcpServer.Start(); } /** Wait for the client to connect with given timeout. * * Note that this initializes the network stream after connecting. * * @param timeout Timeout for waiting for client. * */ public void waitForClient(int timeout = 0) { if (timeout == 0 || this.tcpServer.Pending()) { // Attempt to get the connection immediately if // 1) We don't care about timeouts (will block) // 2) We have a client already trying to connect this.tcpClient = this.tcpServer.AcceptTcpClient(); } else { //TODO: Implement waitForClient() timeout throw new NotImplementedException(); } this.networkStream = this.tcpClient.GetStream(); } /**************************************** *####################################### * Connection/Messaging code *####################################### * **************************************/ /** Gets message sent from client. * * @return String message sent by client. */ public string getMessage() { byte[] inbuffer = new byte[256]; byte[] header = new byte[4]; this.networkStream.Read (header, 0, header.Length); Int32 msglen = System.BitConverter.ToInt32(header, 0); inbuffer = new byte[msglen]; this.networkStream.Read(inbuffer, 0, inbuffer.Length); string msg = System.Text.Encoding.Unicode.GetString(inbuffer); return msg; } /** Gets connection status. * * @return Connection status as a bool. */ public bool getConnectionStatus() { if (this.tcpClient != null) { return this.tcpClient.Connected; } else { return false; } } /** Sends a string message to the client. * * Message contents are sent through unmolested. * If we fail to write to the socket we assume that the * client has disconnected and close the connection. * * @param msg Message to send to client */ public void sendMessage(string msg) { if (!this.getConnectionStatus()) { Console.WriteLine("Cannot send message: disconnected"); return; } byte[] msgbuffer = Encoding.Unicode.GetBytes(msg); // Use UTF-8 try { this.networkStream.Write(BitConverter.GetBytes((Int32)msgbuffer.Length), 0, sizeof(Int32)); this.networkStream.Write(msgbuffer, 0, msgbuffer.Length); } catch (System.IO.IOException socketExcpt) { //TODO: Try to force client connectin closed? Console.WriteLine("Failed to send message to server. Closing connection... "); } } static void Main(string[] args) { DwarfServer dwarfServer = new DwarfServer(); dwarfServer.serverStart(); Console.WriteLine ("Waiting for client connection..."); dwarfServer.waitForClient(); while (true) { dwarfServer.parseCmd(dwarfServer.getMessage()); // dwarf_server.wait_for_client(); } } } }
using System; using System.Linq; using System.Messaging; using System.Threading; using System.Transactions; using log4net; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Messages; using Rhino.ServiceBus.Msmq.TransportActions; namespace Rhino.ServiceBus.Msmq { public class MsmqTransport : IMsmqTrasport { [ThreadStatic] private static MsmqCurrentMessageInformation currentMessageInformation; private readonly Uri endpoint; private readonly ILog logger = LogManager.GetLogger(typeof(MsmqTransport)); private readonly IMessageSerializer serializer; private readonly int threadCount; private readonly WaitHandle[] waitHandles; private IInitializeSubQueues subQueueInitializer; private bool haveStarted; private MessageQueue queue; private readonly IMessageAction[] messageActions; public MsmqTransport( IMessageSerializer serializer, Uri endpoint, int threadCount, IMessageAction[] messageActions) { this.serializer = serializer; this.messageActions = messageActions; this.endpoint = endpoint; this.threadCount = threadCount; waitHandles = new WaitHandle[threadCount]; } public IInitializeSubQueues SubQueueInitializer { get { return subQueueInitializer; } set { this.subQueueInitializer = value;} } public volatile bool ShouldStop; #region ITransport Members public Uri Endpoint { get { return endpoint; } } public void Start() { if (haveStarted) return; logger.DebugFormat("Starting msmq transport on: {0}", Endpoint); queue = InitalizeQueue(endpoint); if(subQueueInitializer != null) { subQueueInitializer.InitializeSubQueues(Endpoint,queue.Transactional); } foreach (var messageAction in messageActions) { messageAction.Init(this); } for (var t = 0; t < threadCount; t++) { var waitHandle = new ManualResetEvent(true); waitHandles[t] = waitHandle; try { queue.BeginPeek(TimeOutForPeek, new QueueState { Queue = queue, WaitHandle = waitHandle }, OnPeekMessage); waitHandle.Reset(); } catch (Exception e) { throw new TransportException("Unable to start reading from queue: " + endpoint, e); } } haveStarted = true; } private static TimeSpan TimeOutForPeek { get { return TimeSpan.FromHours(1); } } public void Stop() { ShouldStop = true; queue.Send(new Message { Label = "Shutdown bus, if you please", AppSpecific = (int)MessageType.ShutDownMessageMarker }, queue.GetSingleMessageTransactionType()); WaitForProcessingToEnd(); if (queue != null) queue.Close(); haveStarted = false; } public void Reply(params object[] messages) { if (currentMessageInformation == null) throw new TransactionException("There is no message to reply to, sorry."); Send(currentMessageInformation.Source, messages); } public event Action<CurrentMessageInformation> MessageSent; public event Func<CurrentMessageInformation,bool> AdministrativeMessageArrived; public event Action<CurrentMessageInformation> MessageArrived; public event Action<CurrentMessageInformation, Exception> MessageProcessingFailure; public event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted; public event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted; public void Discard(object msg) { var message = GenerateMsmqMessageFromMessageBatch(new[] { msg }); message.AppSpecific = (int)MessageType.DiscardedMessageMarker; SendMessageToQueue(message, Endpoint); } public bool RaiseAdministrativeMessageArrived(CurrentMessageInformation information) { var copy = AdministrativeMessageArrived; if (copy != null) return copy(information); return false; } public MessageQueue Queue { get { return queue; } } public void RaiseAdministrativeMessageProcessingCompleted(CurrentMessageInformation information, Exception ex) { var copy = AdministrativeMessageProcessingCompleted; if (copy != null) copy(information, ex); } public void Send(Uri uri, DateTime processAgainAt, object[] msgs) { var message = GenerateMsmqMessageFromMessageBatch(msgs); message.Extension = BitConverter.GetBytes(processAgainAt.ToBinary()); message.AppSpecific = (int)MessageType.TimeoutMessageMarker; SendMessageToQueue(message, uri); } public void Send(Uri uri, params object[] msgs) { var message = GenerateMsmqMessageFromMessageBatch(msgs); SendMessageToQueue(message, uri); var copy = MessageSent; if (copy == null) return; copy(new CurrentMessageInformation { AllMessages = msgs, Source = endpoint, Destination = uri, CorrelationId = CorrelationId.Parse(message.CorrelationId), MessageId = CorrelationId.Parse(message.Id), }); } private Message GenerateMsmqMessageFromMessageBatch(object[] msgs) { var message = new Message(); serializer.Serialize(msgs, message.BodyStream); message.ResponseQueue = queue; SetCorrelationIdOnMessage(message); message.AppSpecific = msgs[0] is AdministrativeMessage ? (int)MessageType.AdministrativeMessageMarker : 0; message.Label = msgs .Where(msg => msg != null) .Select(msg => { string s = msg.ToString(); if (s.Length > 249) return s.Substring(0, 246) + "..."; return s; }) .FirstOrDefault(); return message; } public event Action<CurrentMessageInformation, Exception> MessageSerializationException; #endregion private void WaitForProcessingToEnd() { if (haveStarted == false) return; if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { WaitHandle.WaitAll(waitHandles); } else { foreach (WaitHandle handle in waitHandles) { if (handle != null) handle.WaitOne(); } } } private static MessageQueue InitalizeQueue(Uri endpoint) { try { var messageQueue = endpoint.CreateQueue(QueueAccessMode.SendAndReceive); var filter = new MessagePropertyFilter(); filter.SetAll(); messageQueue.MessageReadPropertyFilter = filter; return messageQueue; } catch (Exception e) { throw new TransportException( "Could not open queue: " + endpoint + Environment.NewLine + "Queue path: " + MsmqUtil.GetQueuePath(endpoint), e); } } private void OnPeekMessage(IAsyncResult ar) { Message message; bool? peek = TryEndingPeek(ar, out message); if (peek == false) // error return; var state = (QueueState)ar.AsyncState; if (ShouldStop) { state.WaitHandle.Set(); return; } try { if (peek == null)//nothing was found return; logger.DebugFormat("Got message {0} from {1}", message.Label, MsmqUtil.GetQueueUri(state.Queue)); foreach (var action in messageActions) { if (action.CanHandlePeekedMessage(message) == false) continue; if(action.HandlePeekedMessage(queue, message)) return; } ReceiveMessageInTransaction(state, message.Id); } finally { state.Queue.BeginPeek(TimeOutForPeek, state, OnPeekMessage); } } private void ReceiveMessageInTransaction(QueueState state, string messageId) { using (var tx = new TransactionScope()) { Message message = state.Queue.TryGetMessageFromQueue(messageId); if (message == null) return;// someone else got our message, better luck next time ProcessMessage(message, state.Queue, tx, MessageArrived, MessageProcessingCompleted); } } private void HandleMessageCompletion( Message message, TransactionScope tx, MessageQueue messageQueue, Exception exception) { if (exception == null) { try { if (tx != null) tx.Complete(); return; } catch (Exception e) { logger.Warn("Failed to complete transaction, moving to error mode", e); } } if (message == null) return; try { Action<CurrentMessageInformation, Exception> copy = MessageProcessingFailure; if (copy != null) copy(currentMessageInformation, exception); } catch (Exception moduleException) { string exMsg = ""; if (exception != null) exMsg = exception.Message; logger.Error("Module failed to process message failure: " + exMsg, moduleException); } if (messageQueue.Transactional == false)// put the item back in the queue { messageQueue.Send(message, MessageQueueTransactionType.None); } } private bool? TryEndingPeek(IAsyncResult ar, out Message message) { var state = (QueueState)ar.AsyncState; try { message = state.Queue.EndPeek(ar); } catch (MessageQueueException e) { message = null; if (e.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout) { logger.Error("Could not peek message from queue", e); return false; } return null; // nothing found } return true; } public void ProcessMessage(Message message, MessageQueue messageQueue, TransactionScope tx, Action<CurrentMessageInformation> messageRecieved, Action<CurrentMessageInformation, Exception> messageCompleted) { Exception ex = null; currentMessageInformation = CreateMessageInformation(message, null, null); try { //deserialization errors do not count for module events object[] messages = DeserializeMessages(messageQueue, message); try { foreach (object msg in messages) { currentMessageInformation = CreateMessageInformation(message, messages, msg); if (messageRecieved != null) messageRecieved(currentMessageInformation); } } catch (Exception e) { ex = e; logger.Error("Failed to process message", e); } finally { if (messageCompleted != null) messageCompleted(currentMessageInformation, ex); } } catch (Exception e) { ex = e; logger.Error("Failed to deserialize message", e); } finally { HandleMessageCompletion(message, tx, messageQueue, ex); currentMessageInformation = null; } } private MsmqCurrentMessageInformation CreateMessageInformation(Message message, object[] messages, object msg) { return new MsmqCurrentMessageInformation { MessageId = CorrelationId.Parse(message.Id), AllMessages = messages, CorrelationId = CorrelationId.Parse(message.CorrelationId), Message = msg, Queue = queue, Destination = Endpoint, Source = MsmqUtil.GetQueueUri(message.ResponseQueue), MsmqMessage = message, TransactionType = queue.GetTransactionType() }; } private object[] DeserializeMessages(MessageQueue messageQueue, Message transportMessage) { object[] messages; try { messages = serializer.Deserialize(transportMessage.BodyStream); } catch (Exception e) { try { logger.Error("Error when serializing message", e); Action<CurrentMessageInformation, Exception> copy = MessageSerializationException; if (copy != null) { var information = new MsmqCurrentMessageInformation { MsmqMessage = transportMessage, Queue = messageQueue, CorrelationId = CorrelationId.Parse(transportMessage.CorrelationId), Message = transportMessage, Source = MsmqUtil.GetQueueUri(messageQueue), MessageId = CorrelationId.Parse(transportMessage.Id) }; copy(information, e); } } catch (Exception moduleEx) { logger.Error("Error when notifying about serialization exception", moduleEx); } throw; } return messages; } private static void SetCorrelationIdOnMessage(Message message) { if (currentMessageInformation == null) return; message.CorrelationId = currentMessageInformation .CorrelationId.Increment().ToString(); } private void SendMessageToQueue(Message message, Uri uri) { if (haveStarted == false) throw new TransportException("Cannot send message before transport is started"); string sendQueueDescription = MsmqUtil.GetQueuePath(uri); try { using (var sendQueue = new MessageQueue( sendQueueDescription, QueueAccessMode.Send)) { MessageQueueTransactionType transactionType = sendQueue.GetTransactionType(); sendQueue.Send(message, transactionType); logger.DebugFormat("Send message {0} to {1}", message.Label, uri); } } catch (Exception e) { throw new TransactionException("Failed to send message to " + uri, e); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace System.Management.Automation.Language { internal static class SpecialChars { // Uncommon whitespace internal const char NoBreakSpace = (char)0x00a0; internal const char NextLine = (char)0x0085; // Special dashes internal const char EnDash = (char)0x2013; internal const char EmDash = (char)0x2014; internal const char HorizontalBar = (char)0x2015; // Special quotes internal const char QuoteSingleLeft = (char)0x2018; // left single quotation mark internal const char QuoteSingleRight = (char)0x2019; // right single quotation mark internal const char QuoteSingleBase = (char)0x201a; // single low-9 quotation mark internal const char QuoteReversed = (char)0x201b; // single high-reversed-9 quotation mark internal const char QuoteDoubleLeft = (char)0x201c; // left double quotation mark internal const char QuoteDoubleRight = (char)0x201d; // right double quotation mark internal const char QuoteLowDoubleLeft = (char)0x201E; // low double left quote used in german. } [Flags] internal enum CharTraits { /// <summary> /// No specific character traits. /// </summary> None = 0x0000, /// <summary> /// For identifiers, the first character must be a letter or underscore. /// </summary> IdentifierStart = 0x0002, /// <summary> /// The character is a valid first character of a multiplier. /// </summary> MultiplierStart = 0x0004, /// <summary> /// The character is a valid type suffix for numeric literals. /// </summary> TypeSuffix = 0x0008, /// <summary> /// The character is a whitespace character. /// </summary> Whitespace = 0x0010, /// <summary> /// The character terminates a line. /// </summary> Newline = 0x0020, /// <summary> /// The character is a hexadecimal digit. /// </summary> HexDigit = 0x0040, /// <summary> /// The character is a decimal digit. /// </summary> Digit = 0x0080, /// <summary> /// The character is allowed as the first character in an unbraced variable name. /// </summary> VarNameFirst = 0x0100, /// <summary> /// The character is not part of the token being scanned. /// </summary> ForceStartNewToken = 0x0200, /// <summary> /// The character is not part of the token being scanned, when the token is known to be part of an assembly name. /// </summary> ForceStartNewAssemblyNameSpecToken = 0x0400, /// <summary> /// The character is the first character of some operator (and hence is not part of a token that starts a number). /// </summary> ForceStartNewTokenAfterNumber = 0x0800, } internal static class CharExtensions { static CharExtensions() { Diagnostics.Assert(s_traits.Length == 128, "Extension methods rely on this table size."); } private static readonly CharTraits[] s_traits = new CharTraits[] { /* 0x0 */ CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0x1 */ CharTraits.None, /* 0x2 */ CharTraits.None, /* 0x3 */ CharTraits.None, /* 0x4 */ CharTraits.None, /* 0x5 */ CharTraits.None, /* 0x6 */ CharTraits.None, /* 0x7 */ CharTraits.None, /* 0x8 */ CharTraits.None, /* 0x9 */ CharTraits.Whitespace | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0xA */ CharTraits.Newline | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0xB */ CharTraits.Whitespace | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0xC */ CharTraits.Whitespace | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0xD */ CharTraits.Newline | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* 0xE */ CharTraits.None, /* 0xF */ CharTraits.None, /* 0x10 */ CharTraits.None, /* 0x11 */ CharTraits.None, /* 0x12 */ CharTraits.None, /* 0x13 */ CharTraits.None, /* 0x14 */ CharTraits.None, /* 0x15 */ CharTraits.None, /* 0x16 */ CharTraits.None, /* 0x17 */ CharTraits.None, /* 0x18 */ CharTraits.None, /* 0x19 */ CharTraits.None, /* 0x1A */ CharTraits.None, /* 0x1B */ CharTraits.None, /* 0x1C */ CharTraits.None, /* 0x1D */ CharTraits.None, /* 0x1E */ CharTraits.None, /* 0x1F */ CharTraits.None, /* */ CharTraits.Whitespace | CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* ! */ CharTraits.ForceStartNewTokenAfterNumber, /* " */ CharTraits.None, /* # */ CharTraits.ForceStartNewTokenAfterNumber, /* $ */ CharTraits.VarNameFirst, /* % */ CharTraits.ForceStartNewTokenAfterNumber, /* & */ CharTraits.ForceStartNewToken, /* ' */ CharTraits.None, /* ( */ CharTraits.ForceStartNewToken, /* ) */ CharTraits.ForceStartNewToken, /* * */ CharTraits.ForceStartNewTokenAfterNumber, /* + */ CharTraits.ForceStartNewTokenAfterNumber, /* , */ CharTraits.ForceStartNewToken | CharTraits.ForceStartNewAssemblyNameSpecToken, /* - */ CharTraits.ForceStartNewTokenAfterNumber, /* . */ CharTraits.ForceStartNewTokenAfterNumber, /* / */ CharTraits.ForceStartNewTokenAfterNumber, /* 0 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 1 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 2 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 3 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 4 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 5 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 6 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 7 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 8 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* 9 */ CharTraits.Digit | CharTraits.HexDigit | CharTraits.VarNameFirst, /* : */ CharTraits.VarNameFirst, /* ; */ CharTraits.ForceStartNewToken, /* < */ CharTraits.ForceStartNewTokenAfterNumber, /* = */ CharTraits.ForceStartNewAssemblyNameSpecToken | CharTraits.ForceStartNewTokenAfterNumber, /* > */ CharTraits.ForceStartNewTokenAfterNumber, /* ? */ CharTraits.VarNameFirst, /* @ */ CharTraits.None, /* A */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* B */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* C */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* D */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit | CharTraits.TypeSuffix, /* E */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* F */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* G */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* H */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* I */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* J */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* K */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* L */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* M */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* N */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* O */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* P */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* Q */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* R */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* S */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* T */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* U */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* V */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* W */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* X */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* Y */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* Z */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* [ */ CharTraits.None, /* \ */ CharTraits.None, /* ] */ CharTraits.ForceStartNewAssemblyNameSpecToken | CharTraits.ForceStartNewTokenAfterNumber, /* ^ */ CharTraits.VarNameFirst, /* _ */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* ` */ CharTraits.None, /* a */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* b */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* c */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* d */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit | CharTraits.TypeSuffix, /* e */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* f */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.HexDigit, /* g */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* h */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* i */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* j */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* k */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* l */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* m */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* n */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* o */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* p */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* q */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* r */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* s */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* t */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.MultiplierStart, /* u */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* v */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* w */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* x */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* y */ CharTraits.IdentifierStart | CharTraits.VarNameFirst | CharTraits.TypeSuffix, /* z */ CharTraits.IdentifierStart | CharTraits.VarNameFirst, /* { */ CharTraits.ForceStartNewToken, /* | */ CharTraits.ForceStartNewToken, /* } */ CharTraits.ForceStartNewToken, /* ~ */ CharTraits.None, /* 0x7F */ CharTraits.None, }; public static bool IsCurlyBracket(char c) { return (c == '{' || c == '}'); } // Return true if the character is a whitespace character. // Newlines are not whitespace. internal static bool IsWhitespace(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.Whitespace) != 0; } if (c <= 256) { return (c == SpecialChars.NoBreakSpace || c == SpecialChars.NextLine); } return char.IsSeparator(c); } // Return true if the character is any of the normal or special // dash characters. internal static bool IsDash(this char c) { return (c == '-' || c == SpecialChars.EnDash || c == SpecialChars.EmDash || c == SpecialChars.HorizontalBar); } // Return true if the character is any of the normal or special // single quote characters. internal static bool IsSingleQuote(this char c) { return (c == '\'' || c == SpecialChars.QuoteSingleLeft || c == SpecialChars.QuoteSingleRight || c == SpecialChars.QuoteSingleBase || c == SpecialChars.QuoteReversed); } // Return true if the character is any of the normal or special // double quote characters. internal static bool IsDoubleQuote(this char c) { return (c == '"' || c == SpecialChars.QuoteDoubleLeft || c == SpecialChars.QuoteDoubleRight || c == SpecialChars.QuoteLowDoubleLeft); } // Return true if the character can be the first character of // the variable name for unbraced variable tokens. internal static bool IsVariableStart(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.VarNameFirst) != 0; } return char.IsLetterOrDigit(c); } // Return true if the character can be the first character of // an identifier or label. internal static bool IsIdentifierStart(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.IdentifierStart) != 0; } return char.IsLetter(c); } // Return true if the character can follow the first character of // an identifier or label. internal static bool IsIdentifierFollow(this char c) { if (c < 128) { return (s_traits[c] & (CharTraits.IdentifierStart | CharTraits.Digit)) != 0; } return char.IsLetterOrDigit(c); } // Return true if the character is a hexadecimal digit. internal static bool IsHexDigit(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.HexDigit) != 0; } return false; } // Returns true if the character is a decimal digit. internal static bool IsDecimalDigit(this char c) => (uint)(c - '0') <= 9; // These decimal/binary checking methods are more performant than the alternatives due to requiring // less overall operations than a more readable check such as {(this char c) => c == 0 | c == 1}, // especially in the case of IsDecimalDigit(). // Returns true if the character is a binary digit. internal static bool IsBinaryDigit(this char c) => (uint)(c - '0') <= 1; // Returns true if the character is a type suffix character. internal static bool IsTypeSuffix(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.TypeSuffix) != 0; } return false; } // Return true if the character is the first character in a multiplier. internal static bool IsMultiplierStart(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.MultiplierStart) != 0; } return false; } // Return true if the character ends the current token while scanning // a token beginning with a letter or number, regardless of the tokenizing // mode. This helps ensure that we tokenize 'a#b' as a single token, but // 'a{' as 2 tokens. internal static bool ForceStartNewToken(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.ForceStartNewToken) != 0; } return c.IsWhitespace(); } /// <summary> /// Check if the current character forces to end scanning a number token. /// This allows the tokenizer to scan '7z' as a single token, but '7+' as 2 tokens. /// </summary> /// <param name="c">The character to check.</param> /// <param name="forceEndNumberOnTernaryOperatorChars"> /// In some cases, we want '?' and ':' to end a number token too, so they can be /// treated as the ternary operator tokens. /// </param> /// <returns>Return true if the character ends the current number token.</returns> internal static bool ForceStartNewTokenAfterNumber(this char c, bool forceEndNumberOnTernaryOperatorChars) { if (c < 128) { if ((s_traits[c] & CharTraits.ForceStartNewTokenAfterNumber) != 0) { return true; } return forceEndNumberOnTernaryOperatorChars && (c == '?' || c == ':'); } return c.IsDash(); } // Return true if the character ends the current token while scanning // a token in the assembly name spec. internal static bool ForceStartNewTokenInAssemblyNameSpec(this char c) { if (c < 128) { return (s_traits[c] & CharTraits.ForceStartNewAssemblyNameSpecToken) != 0; } return c.IsWhitespace(); } } }
//----------------------------------------------------------------------- // <copyright file="StreamLayoutSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; using Fuse = Akka.Streams.Implementation.Fusing.Fusing; namespace Akka.Streams.Tests.Implementation { public class StreamLayoutSpec : Akka.TestKit.Xunit2.TestKit { #region internal classes private class TestAtomicModule : AtomicModule { public TestAtomicModule(int inportCount, int outportCount) { var inports = Enumerable.Range(0, inportCount).Select(i => new Inlet<object>(".in" + i)).ToImmutableArray<Inlet>(); var outports = Enumerable.Range(0, outportCount).Select(i => new Outlet<object>(".out" + i)).ToImmutableArray<Outlet>(); Shape = new AmorphousShape(inports, outports); } public override Shape Shape { get; } public override IModule ReplaceShape(Shape shape) { throw new NotImplementedException(); } public override IModule CarbonCopy() { throw new NotImplementedException(); } public override Attributes Attributes => Attributes.None; public override IModule WithAttributes(Attributes attributes) { return this; } } private class TestPublisher : IPublisher<object>, ISubscription { internal readonly IModule Owner; internal readonly OutPort Port; internal IModule DownstreamModule; internal InPort DownstreamPort; public TestPublisher(IModule owner, OutPort port) { Owner = owner; Port = port; } public void Subscribe(ISubscriber<object> subscriber) { var sub = subscriber as TestSubscriber; if (sub != null) { DownstreamModule = sub.Owner; DownstreamPort = sub.Port; sub.OnSubscribe(this); } } public void Request(long n) { } public void Cancel() { } } private class TestSubscriber : ISubscriber<object> { internal readonly IModule Owner; internal readonly InPort Port; internal IModule UpstreamModule; internal OutPort UpstreamPort; public TestSubscriber(IModule owner, InPort port) { Owner = owner; Port = port; } public void OnSubscribe(ISubscription subscription) { var publisher = subscription as TestPublisher; if (publisher != null) { UpstreamModule = publisher.Owner; UpstreamPort = publisher.Port; } } public void OnError(Exception cause) { } public void OnComplete() { } void ISubscriber<object>.OnNext(object element) { } public void OnNext(object element) { } } private class FlatTestMaterializer : MaterializerSession { internal ImmutableList<TestPublisher> Publishers = ImmutableList<TestPublisher>.Empty; internal ImmutableList<TestSubscriber> Subscribers = ImmutableList<TestSubscriber>.Empty; public FlatTestMaterializer(IModule module) : base(module, Attributes.None) { } protected override object MaterializeAtomic(AtomicModule atomic, Attributes effectiveAttributes, IDictionary<IModule, object> materializedValues) { foreach (var inPort in atomic.InPorts) { var subscriber = new TestSubscriber(atomic, inPort); Subscribers = Subscribers.Add(subscriber); AssignPort(inPort, UntypedSubscriber.FromTyped(subscriber)); } foreach (var outPort in atomic.OutPorts) { var publisher = new TestPublisher(atomic, outPort); Publishers = Publishers.Add(publisher); AssignPort(outPort, UntypedPublisher.FromTyped(publisher)); } return NotUsed.Instance; } } #endregion private const int TooDeepForStack = 5000; // Seen tests run in 9-10 seconds, these test cases are heavy on the GC private static readonly TimeSpan VeryPatient = TimeSpan.FromSeconds(20); private readonly IMaterializer _materializer; private static TestAtomicModule TestStage() => new TestAtomicModule(1, 1); private static TestAtomicModule TestSource() => new TestAtomicModule(0, 1); private static TestAtomicModule TestSink() => new TestAtomicModule(1, 0); public StreamLayoutSpec(ITestOutputHelper output) : base(output: output) { Sys.Settings.InjectTopLevelFallback(ActorMaterializer.DefaultConfig()); _materializer = ActorMaterializer.Create(Sys, ActorMaterializerSettings.Create(Sys).WithAutoFusing(false)); } [Fact] public void StreamLayout_should_be_able_to_model_simple_linear_stages() { var stage1 = TestStage(); stage1.InPorts.Count.Should().Be(1); stage1.OutPorts.Count.Should().Be(1); stage1.IsRunnable.Should().Be(false); stage1.IsFlow.Should().Be(true); stage1.IsSink.Should().Be(false); stage1.IsSource.Should().Be(false); var stage2 = TestStage(); var flow12 = stage1.Compose<object, object, NotUsed>(stage2, Keep.None).Wire(stage1.OutPorts.First(), stage2.InPorts.First()); flow12.InPorts.Should().BeEquivalentTo(stage1.InPorts); flow12.OutPorts.Should().BeEquivalentTo(stage2.OutPorts); flow12.IsRunnable.Should().Be(false); flow12.IsFlow.Should().Be(true); flow12.IsSink.Should().Be(false); flow12.IsSource.Should().Be(false); var source0 = TestSource(); source0.InPorts.Count.Should().Be(0); source0.OutPorts.Count.Should().Be(1); source0.IsRunnable.Should().Be(false); source0.IsFlow.Should().Be(false); source0.IsSink.Should().Be(false); source0.IsSource.Should().Be(true); var sink3 = TestSink(); sink3.InPorts.Count.Should().Be(1); sink3.OutPorts.Count.Should().Be(0); sink3.IsRunnable.Should().Be(false); sink3.IsFlow.Should().Be(false); sink3.IsSink.Should().Be(true); sink3.IsSource.Should().Be(false); var source012 = source0.Compose<object, object, NotUsed>(flow12, Keep.None).Wire(source0.OutPorts.First(), flow12.InPorts.First()); source012.InPorts.Count.Should().Be(0); source012.OutPorts.Should().BeEquivalentTo(flow12.OutPorts); source012.IsRunnable.Should().Be(false); source012.IsFlow.Should().Be(false); source012.IsSink.Should().Be(false); source012.IsSource.Should().Be(true); var sink123 = flow12.Compose<object, object, NotUsed>(sink3, Keep.None).Wire(flow12.OutPorts.First(), sink3.InPorts.First()); sink123.InPorts.Should().BeEquivalentTo(flow12.InPorts); sink123.OutPorts.Count.Should().Be(0); sink123.IsRunnable.Should().Be(false); sink123.IsFlow.Should().Be(false); sink123.IsSink.Should().Be(true); sink123.IsSource.Should().Be(false); var runnable0123A = source0.Compose<object, object, NotUsed>(sink123, Keep.None).Wire(source0.OutPorts.First(), sink123.InPorts.First()); source012.Compose<object, object, NotUsed>(sink3, Keep.None).Wire(source012.OutPorts.First(), sink3.InPorts.First()); source0 .Compose<object, object, NotUsed>(flow12, Keep.None).Wire(source0.OutPorts.First(), flow12.InPorts.First()) .Compose<object, object, NotUsed>(sink3, Keep.None).Wire(flow12.OutPorts.First(), sink3.InPorts.First()); runnable0123A.InPorts.Count.Should().Be(0); runnable0123A.OutPorts.Count.Should().Be(0); runnable0123A.IsRunnable.Should().Be(true); runnable0123A.IsFlow.Should().Be(false); runnable0123A.IsSink.Should().Be(false); runnable0123A.IsSource.Should().Be(false); } [Fact] public void StreamLayout_should_be_able_to_materialize_linear_layouts() { var source = TestSource(); var stage1 = TestStage(); var stage2 = TestStage(); var sink = TestSink(); var runnable = source .Compose<object, object, object>(stage1, Keep.None).Wire(source.OutPorts.First(), stage1.InPorts.First()) .Compose<object, object, object>(stage2, Keep.None).Wire(stage1.OutPorts.First(), stage2.InPorts.First()) .Compose<object, object, object>(sink, Keep.None).Wire(stage2.OutPorts.First(), sink.InPorts.First()); CheckMaterialized(runnable); } [Fact(Skip = "We can't catch a StackOverflowException")] public void StreamLayout_should_fail_fusing_when_value_computation_is_too_complex() { // this tests that the canary in to coal mine actually works var g = Enumerable.Range(1, TooDeepForStack) .Aggregate(Flow.Create<int>().MapMaterializedValue(_ => 1), (flow, i) => flow.MapMaterializedValue(x => x + i)); g.Invoking(flow => Streams.Fusing.Aggressive(flow)).ShouldThrow<StackOverflowException>(); } [Fact] public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Source() { var g = Enumerable.Range(1, TooDeepForStack) .Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)); var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(_materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } [Fact] public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Flow() { var g = Enumerable.Range(1, TooDeepForStack) .Aggregate(Flow.Create<int>().MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)); var t = g.RunWith(Source.Single(42).MapMaterializedValue(_ => 1), Sink.Seq<int>(), _materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } [Fact] public void StreamLayout_should_not_fail_materialization_when_building_a_large_graph_with_simple_computation_when_using_Via() { var g = Enumerable.Range(1, TooDeepForStack) .Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)); var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(_materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } [Fact] public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Source() { var g = Source.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack) .Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)))); var m = g.ToMaterialized(Sink.Seq<int>(), Keep.Both); var t = m.Run(_materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } [Fact] public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_starting_from_a_Flow() { var g = Flow.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack) .Aggregate(Flow.Create<int>().MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)))); var t = g.RunWith(Source.Single(42).MapMaterializedValue(_ => 1), Sink.Seq<int>(), _materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } [Fact] public void StreamLayout_should_not_fail_fusing_and_materialization_when_building_a_large_graph_with_simple_computation_when_using_Via() { var g = Source.FromGraph(Fuse.Aggressive(Enumerable.Range(1, TooDeepForStack) .Aggregate(Source.Single(42).MapMaterializedValue(_ => 1), (source, i) => source.Select(x => x)))); var t = g.ToMaterialized(Sink.Seq<int>(), Keep.Both).Run(_materializer); var materialized = t.Item1; var result = t.Item2.AwaitResult(VeryPatient); materialized.Should().Be(1); result.Count.Should().Be(1); result.Should().Contain(42); } private void CheckMaterialized(IModule topLevel) { var materializer = new FlatTestMaterializer(topLevel); materializer.Materialize(); materializer.Publishers.IsEmpty.Should().Be(false); materializer.Subscribers.IsEmpty.Should().Be(false); materializer.Subscribers.Count.Should().Be(materializer.Publishers.Count); var inToSubscriber = materializer.Subscribers.ToImmutableDictionary(x => x.Port, x => x); var outToPublisher = materializer.Publishers.ToImmutableDictionary(x => x.Port, x => x); foreach (var publisher in materializer.Publishers) { publisher.Owner.IsAtomic.Should().Be(true); topLevel.Upstreams[publisher.DownstreamPort].Should().Be(publisher.Port); } foreach (var subscriber in materializer.Subscribers) { subscriber.Owner.IsAtomic.Should().Be(true); topLevel.Downstreams[subscriber.UpstreamPort].Should().Be(subscriber.Port); } var allAtomic = GetAllAtomic(topLevel); foreach (var atomic in allAtomic) { foreach (var inPort in atomic.InPorts) { TestSubscriber subscriber; if (inToSubscriber.TryGetValue(inPort, out subscriber)) { subscriber.Owner.Should().Be(atomic); subscriber.UpstreamPort.Should().Be(topLevel.Upstreams[inPort]); subscriber.UpstreamModule.OutPorts.Should().Contain(x => outToPublisher[x].DownstreamPort == inPort); } } foreach (var outPort in atomic.OutPorts) { TestPublisher publisher; if (outToPublisher.TryGetValue(outPort, out publisher)) { publisher.Owner.Should().Be(atomic); publisher.DownstreamPort.Should().Be(topLevel.Downstreams[outPort]); publisher.DownstreamModule.InPorts.Should().Contain(x => inToSubscriber[x].UpstreamPort == outPort); } } } materializer.Publishers.Distinct().Count().Should().Be(materializer.Publishers.Count); materializer.Subscribers.Distinct().Count().Should().Be(materializer.Subscribers.Count); // no need to return anything at the moment } private IImmutableSet<IModule> GetAllAtomic(IModule module) { var group = module.SubModules.GroupBy(x => x.IsAtomic).ToDictionary(x => x.Key, x => x.ToImmutableHashSet()); ImmutableHashSet<IModule> atomics, composites; if (!group.TryGetValue(true, out atomics)) atomics = ImmutableHashSet<IModule>.Empty; if (!group.TryGetValue(false, out composites)) composites = ImmutableHashSet<IModule>.Empty; return atomics.Union(composites.SelectMany(GetAllAtomic)); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ContainerRegistry { using Azure; using Management; using Rest; using Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<ContainerRegistryManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(ContainerRegistryManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ContainerRegistryManagementClient /// </summary> public ContainerRegistryManagementClient Client { get; private set; } /// <summary> /// Lists all of the available Azure Container Registry REST API operations. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<OperationDefinition>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.ContainerRegistry/operations").ToString(); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<OperationDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<OperationDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists all of the available Azure Container Registry REST API operations. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<OperationDefinition>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<OperationDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<OperationDefinition>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Generated from https://github.com/nuke-build/nuke/blob/master/source/Nuke.Common/Tools/Boots/Boots.json using JetBrains.Annotations; using Newtonsoft.Json; using Nuke.Common; using Nuke.Common.Execution; using Nuke.Common.Tooling; using Nuke.Common.Tools; using Nuke.Common.Utilities.Collections; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Text; namespace Nuke.Common.Tools.Boots { /// <summary> /// <p>boots is a .NET global tool for <c>bootstrapping</c> <c>vsix</c> and <c>pkg</c> files.</p> /// <p>For more details, visit the <a href="https://github.com/jonathanpeppers/boots">official website</a>.</p> /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class BootsTasks { /// <summary> /// Path to the Boots executable. /// </summary> public static string BootsPath => ToolPathResolver.TryGetEnvironmentExecutable("BOOTS_EXE") ?? ToolPathResolver.GetPackageExecutable("Boots", "Boots.exe"); public static Action<OutputType, string> BootsLogger { get; set; } = ProcessTasks.DefaultLogger; /// <summary> /// <p>boots is a .NET global tool for <c>bootstrapping</c> <c>vsix</c> and <c>pkg</c> files.</p> /// <p>For more details, visit the <a href="https://github.com/jonathanpeppers/boots">official website</a>.</p> /// </summary> public static IReadOnlyCollection<Output> Boots(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null) { using var process = ProcessTasks.StartProcess(BootsPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, BootsLogger, outputFilter); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>boots is a .NET global tool for <c>bootstrapping</c> <c>vsix</c> and <c>pkg</c> files.</p> /// <p>For more details, visit the <a href="https://github.com/jonathanpeppers/boots">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--file-type</c> via <see cref="BootsSettings.FileType"/></li> /// <li><c>--preview</c> via <see cref="BootsSettings.Preview"/></li> /// <li><c>--read-write-timeout</c> via <see cref="BootsSettings.ReadWriteTimeout"/></li> /// <li><c>--retries</c> via <see cref="BootsSettings.Retries"/></li> /// <li><c>--stable</c> via <see cref="BootsSettings.Stable"/></li> /// <li><c>--timeout</c> via <see cref="BootsSettings.Timeout"/></li> /// <li><c>--url</c> via <see cref="BootsSettings.Url"/></li> /// <li><c>--version</c> via <see cref="BootsSettings.Version"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Boots(BootsSettings toolSettings = null) { toolSettings = toolSettings ?? new BootsSettings(); using var process = ProcessTasks.StartProcess(toolSettings); process.AssertZeroExitCode(); return process.Output; } /// <summary> /// <p>boots is a .NET global tool for <c>bootstrapping</c> <c>vsix</c> and <c>pkg</c> files.</p> /// <p>For more details, visit the <a href="https://github.com/jonathanpeppers/boots">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--file-type</c> via <see cref="BootsSettings.FileType"/></li> /// <li><c>--preview</c> via <see cref="BootsSettings.Preview"/></li> /// <li><c>--read-write-timeout</c> via <see cref="BootsSettings.ReadWriteTimeout"/></li> /// <li><c>--retries</c> via <see cref="BootsSettings.Retries"/></li> /// <li><c>--stable</c> via <see cref="BootsSettings.Stable"/></li> /// <li><c>--timeout</c> via <see cref="BootsSettings.Timeout"/></li> /// <li><c>--url</c> via <see cref="BootsSettings.Url"/></li> /// <li><c>--version</c> via <see cref="BootsSettings.Version"/></li> /// </ul> /// </remarks> public static IReadOnlyCollection<Output> Boots(Configure<BootsSettings> configurator) { return Boots(configurator(new BootsSettings())); } /// <summary> /// <p>boots is a .NET global tool for <c>bootstrapping</c> <c>vsix</c> and <c>pkg</c> files.</p> /// <p>For more details, visit the <a href="https://github.com/jonathanpeppers/boots">official website</a>.</p> /// </summary> /// <remarks> /// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p> /// <ul> /// <li><c>--file-type</c> via <see cref="BootsSettings.FileType"/></li> /// <li><c>--preview</c> via <see cref="BootsSettings.Preview"/></li> /// <li><c>--read-write-timeout</c> via <see cref="BootsSettings.ReadWriteTimeout"/></li> /// <li><c>--retries</c> via <see cref="BootsSettings.Retries"/></li> /// <li><c>--stable</c> via <see cref="BootsSettings.Stable"/></li> /// <li><c>--timeout</c> via <see cref="BootsSettings.Timeout"/></li> /// <li><c>--url</c> via <see cref="BootsSettings.Url"/></li> /// <li><c>--version</c> via <see cref="BootsSettings.Version"/></li> /// </ul> /// </remarks> public static IEnumerable<(BootsSettings Settings, IReadOnlyCollection<Output> Output)> Boots(CombinatorialConfigure<BootsSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) { return configurator.Invoke(Boots, BootsLogger, degreeOfParallelism, completeOnFailure); } } #region BootsSettings /// <summary> /// Used within <see cref="BootsTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] [Serializable] public partial class BootsSettings : ToolSettings { /// <summary> /// Path to the Boots executable. /// </summary> public override string ProcessToolPath => base.ProcessToolPath ?? BootsTasks.BootsPath; public override Action<OutputType, string> ProcessCustomLogger => BootsTasks.BootsLogger; /// <summary> /// Install the latest <em>stable</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c> /// </summary> public virtual BootsProductType Stable { get; internal set; } /// <summary> /// Install the latest <em>preview</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c> /// </summary> public virtual BootsProductType Preview { get; internal set; } /// <summary> /// A Url to a <c>pkg</c> or <c>vsix</c> file to install /// </summary> public virtual string Url { get; internal set; } /// <summary> /// Specifies the type of file to be installed such as <c>vsix</c>, <c>pkg</c>, or <c>msi</c>. Defaults to <c>vsix</c> on Windows and <c>pkg</c> on macOS /// </summary> public virtual BootsFileType FileType { get; internal set; } /// <summary> /// Specifies a timeout for <c>HttpClient</c>. If omitted, uses the .NET default of 100 seconds /// </summary> public virtual int? Timeout { get; internal set; } /// <summary> /// Specifies a timeout for reading/writing from a <c>HttpClient</c> stream. If omitted, uses a default of 300 seconds /// </summary> public virtual int? ReadWriteTimeout { get; internal set; } /// <summary> /// Specifies a number of retries for <c>HttpClient</c> failures. If omitted, uses a default of 3 retries /// </summary> public virtual int? Retries { get; internal set; } /// <summary> /// Show version information /// </summary> public virtual bool? Version { get; internal set; } protected override Arguments ConfigureProcessArguments(Arguments arguments) { arguments .Add("--stable {value}", Stable) .Add("--preview {value}", Preview) .Add("--url {value}", Url) .Add("--file-type {value}", FileType) .Add("--timeout {value}", Timeout) .Add("--read-write-timeout {value}", ReadWriteTimeout) .Add("--retries {value}", Retries) .Add("--version", Version); return base.ConfigureProcessArguments(arguments); } } #endregion #region BootsSettingsExtensions /// <summary> /// Used within <see cref="BootsTasks"/>. /// </summary> [PublicAPI] [ExcludeFromCodeCoverage] public static partial class BootsSettingsExtensions { #region Stable /// <summary> /// <p><em>Sets <see cref="BootsSettings.Stable"/></em></p> /// <p>Install the latest <em>stable</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c></p> /// </summary> [Pure] public static T SetStable<T>(this T toolSettings, BootsProductType stable) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Stable = stable; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Stable"/></em></p> /// <p>Install the latest <em>stable</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c></p> /// </summary> [Pure] public static T ResetStable<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Stable = null; return toolSettings; } #endregion #region Preview /// <summary> /// <p><em>Sets <see cref="BootsSettings.Preview"/></em></p> /// <p>Install the latest <em>preview</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c></p> /// </summary> [Pure] public static T SetPreview<T>(this T toolSettings, BootsProductType preview) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Preview = preview; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Preview"/></em></p> /// <p>Install the latest <em>preview</em> version of a product from VS manifests. Options include: <c>Xamarin.Android</c>, <c>Xamarin.iOS</c>, <c>Xamarin.Mac</c>, and <c>Mono</c></p> /// </summary> [Pure] public static T ResetPreview<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Preview = null; return toolSettings; } #endregion #region Url /// <summary> /// <p><em>Sets <see cref="BootsSettings.Url"/></em></p> /// <p>A Url to a <c>pkg</c> or <c>vsix</c> file to install</p> /// </summary> [Pure] public static T SetUrl<T>(this T toolSettings, string url) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Url = url; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Url"/></em></p> /// <p>A Url to a <c>pkg</c> or <c>vsix</c> file to install</p> /// </summary> [Pure] public static T ResetUrl<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Url = null; return toolSettings; } #endregion #region FileType /// <summary> /// <p><em>Sets <see cref="BootsSettings.FileType"/></em></p> /// <p>Specifies the type of file to be installed such as <c>vsix</c>, <c>pkg</c>, or <c>msi</c>. Defaults to <c>vsix</c> on Windows and <c>pkg</c> on macOS</p> /// </summary> [Pure] public static T SetFileType<T>(this T toolSettings, BootsFileType fileType) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.FileType = fileType; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.FileType"/></em></p> /// <p>Specifies the type of file to be installed such as <c>vsix</c>, <c>pkg</c>, or <c>msi</c>. Defaults to <c>vsix</c> on Windows and <c>pkg</c> on macOS</p> /// </summary> [Pure] public static T ResetFileType<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.FileType = null; return toolSettings; } #endregion #region Timeout /// <summary> /// <p><em>Sets <see cref="BootsSettings.Timeout"/></em></p> /// <p>Specifies a timeout for <c>HttpClient</c>. If omitted, uses the .NET default of 100 seconds</p> /// </summary> [Pure] public static T SetTimeout<T>(this T toolSettings, int? timeout) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Timeout = timeout; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Timeout"/></em></p> /// <p>Specifies a timeout for <c>HttpClient</c>. If omitted, uses the .NET default of 100 seconds</p> /// </summary> [Pure] public static T ResetTimeout<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Timeout = null; return toolSettings; } #endregion #region ReadWriteTimeout /// <summary> /// <p><em>Sets <see cref="BootsSettings.ReadWriteTimeout"/></em></p> /// <p>Specifies a timeout for reading/writing from a <c>HttpClient</c> stream. If omitted, uses a default of 300 seconds</p> /// </summary> [Pure] public static T SetReadWriteTimeout<T>(this T toolSettings, int? readWriteTimeout) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ReadWriteTimeout = readWriteTimeout; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.ReadWriteTimeout"/></em></p> /// <p>Specifies a timeout for reading/writing from a <c>HttpClient</c> stream. If omitted, uses a default of 300 seconds</p> /// </summary> [Pure] public static T ResetReadWriteTimeout<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.ReadWriteTimeout = null; return toolSettings; } #endregion #region Retries /// <summary> /// <p><em>Sets <see cref="BootsSettings.Retries"/></em></p> /// <p>Specifies a number of retries for <c>HttpClient</c> failures. If omitted, uses a default of 3 retries</p> /// </summary> [Pure] public static T SetRetries<T>(this T toolSettings, int? retries) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Retries = retries; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Retries"/></em></p> /// <p>Specifies a number of retries for <c>HttpClient</c> failures. If omitted, uses a default of 3 retries</p> /// </summary> [Pure] public static T ResetRetries<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Retries = null; return toolSettings; } #endregion #region Version /// <summary> /// <p><em>Sets <see cref="BootsSettings.Version"/></em></p> /// <p>Show version information</p> /// </summary> [Pure] public static T SetVersion<T>(this T toolSettings, bool? version) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Version = version; return toolSettings; } /// <summary> /// <p><em>Resets <see cref="BootsSettings.Version"/></em></p> /// <p>Show version information</p> /// </summary> [Pure] public static T ResetVersion<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Version = null; return toolSettings; } /// <summary> /// <p><em>Enables <see cref="BootsSettings.Version"/></em></p> /// <p>Show version information</p> /// </summary> [Pure] public static T EnableVersion<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Version = true; return toolSettings; } /// <summary> /// <p><em>Disables <see cref="BootsSettings.Version"/></em></p> /// <p>Show version information</p> /// </summary> [Pure] public static T DisableVersion<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Version = false; return toolSettings; } /// <summary> /// <p><em>Toggles <see cref="BootsSettings.Version"/></em></p> /// <p>Show version information</p> /// </summary> [Pure] public static T ToggleVersion<T>(this T toolSettings) where T : BootsSettings { toolSettings = toolSettings.NewInstance(); toolSettings.Version = !toolSettings.Version; return toolSettings; } #endregion } #endregion #region BootsProductType /// <summary> /// Used within <see cref="BootsTasks"/>. /// </summary> [PublicAPI] [Serializable] [ExcludeFromCodeCoverage] [TypeConverter(typeof(TypeConverter<BootsProductType>))] public partial class BootsProductType : Enumeration { public static BootsProductType Mono = (BootsProductType) "Mono"; public static BootsProductType Xamarin_Android = (BootsProductType) "Xamarin.Android"; public static BootsProductType Xamarin_iOS = (BootsProductType) "Xamarin.iOS"; public static BootsProductType Xamarin_Mac = (BootsProductType) "Xamarin.Mac"; public static implicit operator BootsProductType(string value) { return new BootsProductType { Value = value }; } } #endregion #region BootsFileType /// <summary> /// Used within <see cref="BootsTasks"/>. /// </summary> [PublicAPI] [Serializable] [ExcludeFromCodeCoverage] [TypeConverter(typeof(TypeConverter<BootsFileType>))] public partial class BootsFileType : Enumeration { public static BootsFileType vsix = (BootsFileType) "vsix"; public static BootsFileType pkg = (BootsFileType) "pkg"; public static BootsFileType msi = (BootsFileType) "msi"; public static implicit operator BootsFileType(string value) { return new BootsFileType { Value = value }; } } #endregion }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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 Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); readonly Func<TWrite, byte[]> serializer; readonly Func<byte[], TRead> deserializer; protected readonly GrpcEnvironment environment; protected readonly object myLock = new object(); protected INativeCall call; protected bool disposed; protected bool started; protected bool cancelRequested; protected AsyncCompletionDelegate<object> sendCompletionDelegate; // Completion of a pending send or sendclose if not null. protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null. protected TaskCompletionSource<object> sendStatusFromServerTcs; protected bool readingDone; // True if last read (i.e. read with null payload) was already received. protected bool halfcloseRequested; // True if send close have been initiated. protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; // Number of streaming send operations started so far. public AsyncCallBase(Func<TWrite, byte[]> serializer, Func<byte[], TRead> deserializer, GrpcEnvironment environment) { this.serializer = GrpcPreconditions.CheckNotNull(serializer); this.deserializer = GrpcPreconditions.CheckNotNull(deserializer); this.environment = GrpcPreconditions.CheckNotNull(environment); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { GrpcPreconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> protected void CancelWithStatus(Status status) { lock (myLock) { cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(INativeCall call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected void StartSendMessageInternal(TWrite msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { GrpcPreconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(allowFinished: false); call.StartSendMessage(HandleSendFinished, payload, writeFlags, !initialMetadataSent); sendCompletionDelegate = completionDelegate; initialMetadataSent = true; streamingWritesCounter++; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// completionDelegate is invoked upon completion. /// </summary> protected Task<TRead> ReadMessageInternalAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); if (readingDone) { // the last read that returns null or throws an exception is idempotent // and maintain its state. GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads."); return streamingReadTcs.Task; } GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time"); GrpcPreconditions.CheckState(!disposed); call.StartReceiveMessage(HandleReadFinished); streamingReadTcs = new TaskCompletionSource<TRead>(); return streamingReadTcs.Task; } } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.ReleaseResourcesIfPossible")) { if (!disposed && call != null) { bool noMoreSendCompletions = sendCompletionDelegate == null && (halfcloseRequested || cancelRequested || finished); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } } protected abstract bool IsClient { get; } private void ReleaseResources() { if (call != null) { call.Dispose(); } disposed = true; OnAfterReleaseResources(); } protected virtual void OnAfterReleaseResources() { } protected virtual void CheckSendingAllowed(bool allowFinished) { GrpcPreconditions.CheckState(started); CheckNotCancelled(); GrpcPreconditions.CheckState(!disposed || allowFinished); GrpcPreconditions.CheckState(!halfcloseRequested, "Already halfclosed."); GrpcPreconditions.CheckState(!finished || allowFinished, "Already finished."); GrpcPreconditions.CheckState(sendCompletionDelegate == null, "Only one write can be pending at a time"); } protected void CheckNotCancelled() { if (cancelRequested) { throw new OperationCanceledException("Remote call has been cancelled."); } } protected byte[] UnsafeSerialize(TWrite msg) { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.UnsafeSerialize")) { return serializer(msg); } } protected Exception TryDeserialize(byte[] payload, out TRead msg) { using (Profilers.ForCurrentThread().NewScope("AsyncCallBase.TryDeserialize")) { try { msg = deserializer(payload); return null; } catch (Exception e) { msg = default(TRead); return e; } } } protected void FireCompletion<T>(AsyncCompletionDelegate<T> completionDelegate, T value, Exception error) { try { completionDelegate(value, error); } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } /// <summary> /// Handles send completion. /// </summary> protected void HandleSendFinished(bool success) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Send failed")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles halfclose (send close from client) completion. /// </summary> protected void HandleSendCloseFromClientFinished(bool success) { AsyncCompletionDelegate<object> origCompletionDelegate = null; lock (myLock) { origCompletionDelegate = sendCompletionDelegate; sendCompletionDelegate = null; ReleaseResourcesIfPossible(); } if (!success) { FireCompletion(origCompletionDelegate, null, new InvalidOperationException("Sending close from client has failed.")); } else { FireCompletion(origCompletionDelegate, null, null); } } /// <summary> /// Handles send status from server completion. /// </summary> protected void HandleSendStatusFromServerFinished(bool success) { lock (myLock) { ReleaseResourcesIfPossible(); } if (!success) { sendStatusFromServerTcs.SetException(new InvalidOperationException("Error sending status from server.")); } else { sendStatusFromServerTcs.SetResult(null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, byte[] receivedMessage) { // if success == false, received message will be null. It that case we will // treat this completion as the last read an rely on C core to handle the failed // read (e.g. deliver approriate statusCode on the clientside). TRead msg = default(TRead); var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null; TaskCompletionSource<TRead> origTcs = null; lock (myLock) { origTcs = streamingReadTcs; if (receivedMessage == null) { // This was the last read. readingDone = true; } if (deserializeException != null && IsClient) { readingDone = true; // TODO(jtattermusch): it might be too late to set the status CancelWithStatus(DeserializeResponseFailureStatus); } if (!readingDone) { streamingReadTcs = null; } ReleaseResourcesIfPossible(); } if (deserializeException != null && !IsClient) { origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException)); return; } origTcs.SetResult(msg); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Infrastructure.Common; using System; using System.Security.Cryptography.X509Certificates; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Security; using Xunit; public static class Tcp_ClientCredentialTypeTests { // Simple echo of a string using NetTcpBinding on both client and server with all default settings. // Default settings are: // - SecurityMode = Transport // - ClientCredentialType = Windows [Fact] [ActiveIssue(592)] [OuterLoop] public static void SameBinding_DefaultSettings_EchoString() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // Simple echo of a string using NetTcpBinding on both client and server with SecurityMode=None [Fact] [OuterLoop] public static void SameBinding_SecurityModeNone_EchoString() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // Simple echo of a string using NetTcpBinding on both client and server with SecurityMode=Transport // By default ClientCredentialType will be 'Windows' [Fact] [ActiveIssue(592)] [OuterLoop] public static void SameBinding_SecurityModeTransport_EchoString() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // Simple echo of a string using a CustomBinding to mimic a NetTcpBinding with Security.Mode = TransportWithMessageCredentials // This does not exactly match the binding elements in a NetTcpBinding which also includes a TransportSecurityBindingElement [Fact] [OuterLoop] public static void SameBinding_SecurityModeTransport_ClientCredentialTypeCertificate_EchoString() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding( new SslStreamSecurityBindingElement(), // This is the binding element used when Security.Mode = TransportWithMessageCredentials new BinaryMessageEncodingBindingElement(), new TcpTransportBindingElement()); var endpointIdentity = new DnsEndpointIdentity(Endpoints.Tcp_CustomBinding_SslStreamSecurity_HostName); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(new Uri(Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address), endpointIdentity)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void TcpClientCredentialType_Certificate_EchoString() { string clientCertThumb = null; EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_Address), new DnsEndpointIdentity(Endpoints.Tcp_VerifyDNS_HostName)); clientCertThumb = BridgeClientCertificateManager.LocalCertThumbprint; // ClientCert as given by the Bridge factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None; factory.Credentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, clientCertThumb); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void TcpClientCredentialType_Certificate_CustomValidator_EchoString() { string clientCertThumb = null; EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Certificate; endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_CustomValidation_Address), new DnsEndpointIdentity(Endpoints.Tcp_VerifyDNS_HostName)); clientCertThumb = BridgeClientCertificateManager.LocalCertThumbprint; // ClientCert as given by the Bridge factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.Custom; MyX509CertificateValidator myX509CertificateValidator = new MyX509CertificateValidator(ScenarioTestHelpers.CertificateIssuerName); factory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = myX509CertificateValidator; factory.Credentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, clientCertThumb); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.True(myX509CertificateValidator.validateMethodWasCalled, "The Validate method of the X509CertificateValidator was NOT called."); Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void TcpClientCredentialType_Certificate_With_ServerAltName_EchoString() { EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_ServerAltName_Address)); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation, All Rights Reserved // // File: JpegBitmapEncoder.cs // //------------------------------------------------------------------------------ using System; using System.Security; using System.Security.Permissions; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Win32.PresentationCore; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Media.Imaging; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Imaging { #region JpegBitmapEncoder /// <summary> /// Built-in Encoder for Jpeg files. /// </summary> public sealed class JpegBitmapEncoder : BitmapEncoder { #region Constructors /// <summary> /// Constructor for JpegBitmapEncoder /// </summary> /// <SecurityNote> /// Critical - will eventually create unmanaged resources /// PublicOK - all inputs are verified /// </SecurityNote> [SecurityCritical ] public JpegBitmapEncoder() : base(true) { _supportsPreview = false; _supportsGlobalThumbnail = false; _supportsGlobalMetadata = false; _supportsFrameThumbnails = true; _supportsMultipleFrames = false; _supportsFrameMetadata = true; } #endregion #region Public Properties /// <summary> /// Set the quality level for the encoding. /// The quality level must be between 1-100, inclusive. /// This property is mutually exclusive with doing lossless encoding. /// </summary> public int QualityLevel { get { return _qualityLevel; } set { if ((value < 1) || (value > 100)) { throw new System.ArgumentOutOfRangeException("value", SR.Get(SRID.ParameterMustBeBetween, 1, 100)); } _qualityLevel = value; } } /// <summary> /// Set a lossless rotation value of Rotation degrees. /// This replaces any previous lossless transformation. /// </summary> public Rotation Rotation { get { if (Rotate90) { return Rotation.Rotate90; } else if (Rotate180) { return Rotation.Rotate180; } else if (Rotate270) { return Rotation.Rotate270; } else { return Rotation.Rotate0; } } set { Rotate90 = false; Rotate180 = false; Rotate270 = false; switch(value) { case(Rotation.Rotate0): // do nothing, we reset everything above // case statement is here for clearness break; case(Rotation.Rotate90): Rotate90 = true; break; case(Rotation.Rotate180): Rotate180 = true; break; case(Rotation.Rotate270): Rotate270 = true; break; } } } /// <summary> /// Set a lossless horizontal flip. /// This replaces any previous lossless transformation. /// </summary> public bool FlipHorizontal { get { return (Convert.ToBoolean((int)_transformation & (int)WICBitmapTransformOptions.WICBitmapTransformFlipHorizontal)); } set { if (value != this.FlipHorizontal) { if (value) { _transformation |= WICBitmapTransformOptions.WICBitmapTransformFlipHorizontal; } else { _transformation &= ~WICBitmapTransformOptions.WICBitmapTransformFlipHorizontal; } } } } /// <summary> /// Set a lossless vertical flip. /// This replaces any previous lossless transformation. /// </summary> public bool FlipVertical { get { return (Convert.ToBoolean((int)_transformation & (int)WICBitmapTransformOptions.WICBitmapTransformFlipVertical)); } set { if (value != this.FlipVertical) { if (value) { _transformation |= WICBitmapTransformOptions.WICBitmapTransformFlipVertical; } else { _transformation &= ~WICBitmapTransformOptions.WICBitmapTransformFlipVertical; } } } } #endregion #region Internal Properties / Methods /// <summary> /// Returns the container format for this encoder /// </summary> /// <SecurityNote> /// Critical - uses guid to create unmanaged resources /// </SecurityNote> internal override Guid ContainerFormat { [SecurityCritical] get { return _containerFormat; } } /// <summary> /// Setups the encoder and other properties before encoding each frame /// </summary> /// <SecurityNote> /// Critical - calls Critical Initialize() /// </SecurityNote> [SecurityCritical] internal override void SetupFrame(SafeMILHandle frameEncodeHandle, SafeMILHandle encoderOptions) { PROPBAG2 propBag = new PROPBAG2(); PROPVARIANT propValue = new PROPVARIANT(); // There are only two encoder options supported here: if (_transformation != c_defaultTransformation) { try { propBag.Init("BitmapTransform"); propValue.Init((byte) _transformation); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } if (_qualityLevel != c_defaultQualityLevel) { try { propBag.Init("ImageQuality"); propValue.Init( ((float)_qualityLevel) / 100.0f); HRESULT.Check(UnsafeNativeMethods.IPropertyBag2.Write( encoderOptions, 1, ref propBag, ref propValue)); } finally { propBag.Clear(); propValue.Clear(); } } HRESULT.Check(UnsafeNativeMethods.WICBitmapFrameEncode.Initialize( frameEncodeHandle, encoderOptions )); } /// <summary> /// Set a lossless rotation value of 90 degrees. /// This replaces any previous lossless transformation. /// We can coexist with Flip operation /// </summary> private bool Rotate90 { get { return ((Convert.ToBoolean((int)_transformation & (int)WICBitmapTransformOptions.WICBitmapTransformRotate90) && (!Rotate270))); } set { if (value != this.Rotate90) { bool IsFlipH = FlipHorizontal; bool IsFlipV = FlipVertical; if (value) { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate90; } else { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate0; } FlipHorizontal = IsFlipH; FlipVertical = IsFlipV; } } } /// <summary> /// Set a lossless rotation value of 180 degrees. /// This replaces any previous lossless transformation. /// We can coexist with Flip operation /// </summary> private bool Rotate180 { get { return ((Convert.ToBoolean((int)_transformation & (int)WICBitmapTransformOptions.WICBitmapTransformRotate180) && (!Rotate270))); } set { if (value != this.Rotate180) { bool IsFlipH = FlipHorizontal; bool IsFlipV = FlipVertical; if (value) { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate180; } else { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate0; } FlipHorizontal = IsFlipH; FlipVertical = IsFlipV; } } } /// <summary> /// Set a lossless rotation value of 270 degrees. /// This replaces any previous lossless transformation. /// We can coexist with Flip operation /// </summary> private bool Rotate270 { get { return (Convert.ToBoolean(((int)_transformation & (int)WICBitmapTransformOptions.WICBitmapTransformRotate270) == (int)WICBitmapTransformOptions.WICBitmapTransformRotate270)); } set { if (value != this.Rotate270) { bool IsFlipH = FlipHorizontal; bool IsFlipV = FlipVertical; if (value) { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate270; } else { _transformation = WICBitmapTransformOptions.WICBitmapTransformRotate0; } FlipHorizontal = IsFlipH; FlipVertical = IsFlipV; } } } #endregion #region Internal Abstract /// Need to implement this to derive from the "sealed" object internal override void SealObject() { throw new NotImplementedException(); } #endregion #region Data Members /// <SecurityNote> /// Critical - CLSID used for creation of critical resources /// </SecurityNote> [SecurityCritical] private Guid _containerFormat = MILGuidData.GUID_ContainerFormatJpeg; // This happens to be the default used by the jpeg lib. private const int c_defaultQualityLevel = 75; private int _qualityLevel = c_defaultQualityLevel; private const WICBitmapTransformOptions c_defaultTransformation = WICBitmapTransformOptions.WICBitmapTransformRotate0; private WICBitmapTransformOptions _transformation = c_defaultTransformation; #endregion } #endregion // JpegBitmapEncoder }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia.Media; using Avalonia.Platform; using SkiaSharp; using System; using System.Collections.Generic; using System.Linq; namespace Avalonia.Skia { public class FormattedTextImpl : IFormattedTextImpl { public FormattedTextImpl( string text, Typeface typeface, TextAlignment textAlignment, TextWrapping wrapping, Size constraint, IReadOnlyList<FormattedTextStyleSpan> spans) { Text = text ?? string.Empty; // Replace 0 characters with zero-width spaces (200B) Text = Text.Replace((char)0, (char)0x200B); var skiaTypeface = TypefaceCache.GetTypeface( typeface?.FontFamilyName ?? "monospace", typeface?.Style ?? FontStyle.Normal, typeface?.Weight ?? FontWeight.Normal); _paint = new SKPaint(); //currently Skia does not measure properly with Utf8 !!! //Paint.TextEncoding = SKTextEncoding.Utf8; _paint.TextEncoding = SKTextEncoding.Utf16; _paint.IsStroke = false; _paint.IsAntialias = true; _paint.LcdRenderText = true; _paint.SubpixelText = true; _paint.Typeface = skiaTypeface; _paint.TextSize = (float)(typeface?.FontSize ?? 12); _paint.TextAlign = textAlignment.ToSKTextAlign(); _wrapping = wrapping; _constraint = constraint; if (spans != null) { foreach (var span in spans) { if (span.ForegroundBrush != null) { SetForegroundBrush(span.ForegroundBrush, span.StartIndex, span.Length); } } } Rebuild(); } public Size Constraint => _constraint; public Size Size => _size; public IEnumerable<FormattedTextLine> GetLines() { return _lines; } public TextHitTestResult HitTestPoint(Point point) { float y = (float)point.Y; var line = _skiaLines.Find(l => l.Top <= y && (l.Top + l.Height) > y); if (!line.Equals(default(AvaloniaFormattedTextLine))) { var rects = GetRects(); for (int c = line.Start; c < line.Start + line.TextLength; c++) { var rc = rects[c]; if (rc.Contains(point)) { return new TextHitTestResult { IsInside = !(line.TextLength > line.Length), TextPosition = c, IsTrailing = (point.X - rc.X) > rc.Width / 2 }; } } int offset = 0; if (point.X >= (rects[line.Start].X + line.Width) / 2 && line.Length > 0) { offset = line.TextLength > line.Length ? line.Length : (line.Length - 1); } return new TextHitTestResult { IsInside = false, TextPosition = line.Start + offset, IsTrailing = Text.Length == (line.Start + offset + 1) }; } bool end = point.X > _size.Width || point.Y > _lines.Sum(l => l.Height); return new TextHitTestResult() { IsInside = false, IsTrailing = end, TextPosition = end ? Text.Length - 1 : 0 }; } public Rect HitTestTextPosition(int index) { var rects = GetRects(); if (index < 0 || index >= rects.Count) { var r = rects.LastOrDefault(); return new Rect(r.X + r.Width, r.Y, 0, _lineHeight); } if (rects.Count == 0) { return new Rect(0, 0, 1, _lineHeight); } if (index == rects.Count) { var lr = rects[rects.Count - 1]; return new Rect(new Point(lr.X + lr.Width, lr.Y), rects[index - 1].Size); } return rects[index]; } public IEnumerable<Rect> HitTestTextRange(int index, int length) { List<Rect> result = new List<Rect>(); var rects = GetRects(); int lastIndex = index + length - 1; foreach (var line in _skiaLines.Where(l => (l.Start + l.Length) > index && lastIndex >= l.Start)) { int lineEndIndex = line.Start + (line.Length > 0 ? line.Length - 1 : 0); double left = rects[line.Start > index ? line.Start : index].X; double right = rects[lineEndIndex > lastIndex ? lastIndex : lineEndIndex].Right; result.Add(new Rect(left, line.Top, right - left, line.Height)); } return result; } public override string ToString() { return Text; } internal void Draw(DrawingContextImpl context, SKCanvas canvas, SKPoint origin, DrawingContextImpl.PaintWrapper foreground, bool canUseLcdRendering) { /* TODO: This originated from Native code, it might be useful for debugging character positions as * we improve the FormattedText support. Will need to port this to C# obviously. Rmove when * not needed anymore. SkPaint dpaint; ctx->Canvas->save(); ctx->Canvas->translate(origin.fX, origin.fY); for (int c = 0; c < Lines.size(); c++) { dpaint.setARGB(255, 0, 0, 0); SkRect rc; rc.fLeft = 0; rc.fTop = Lines[c].Top; rc.fRight = Lines[c].Width; rc.fBottom = rc.fTop + LineOffset; ctx->Canvas->drawRect(rc, dpaint); } for (int c = 0; c < Length; c++) { dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10); dpaint.setStyle(SkPaint::kFill_Style); ctx->Canvas->drawRect(Rects[c], dpaint); } ctx->Canvas->restore(); */ using (var paint = _paint.Clone()) { IDisposable currd = null; var currentWrapper = foreground; SKPaint currentPaint = null; try { ApplyWrapperTo(ref currentPaint, foreground, ref currd, paint, canUseLcdRendering); bool hasCusomFGBrushes = _foregroundBrushes.Any(); for (int c = 0; c < _skiaLines.Count; c++) { AvaloniaFormattedTextLine line = _skiaLines[c]; float x = TransformX(origin.X, 0, paint.TextAlign); if (!hasCusomFGBrushes) { var subString = Text.Substring(line.Start, line.Length); canvas.DrawText(subString, x, origin.Y + line.Top + _lineOffset, paint); } else { float currX = x; string subStr; int len; for (int i = line.Start; i < line.Start + line.Length;) { var fb = GetNextForegroundBrush(ref line, i, out len); if (fb != null) { //TODO: figure out how to get the brush size currentWrapper = context.CreatePaint(fb, new Size()); } else { if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose(); currentWrapper = foreground; } subStr = Text.Substring(i, len); ApplyWrapperTo(ref currentPaint, currentWrapper, ref currd, paint, canUseLcdRendering); canvas.DrawText(subStr, currX, origin.Y + line.Top + _lineOffset, paint); i += len; currX += paint.MeasureText(subStr); } } } } finally { if (!currentWrapper.Equals(foreground)) currentWrapper.Dispose(); currd?.Dispose(); } } } private const float MAX_LINE_WIDTH = 10000; private readonly List<KeyValuePair<FBrushRange, IBrush>> _foregroundBrushes = new List<KeyValuePair<FBrushRange, IBrush>>(); private readonly List<FormattedTextLine> _lines = new List<FormattedTextLine>(); private readonly SKPaint _paint; private readonly List<Rect> _rects = new List<Rect>(); public string Text { get; } private readonly TextWrapping _wrapping; private Size _constraint = new Size(double.PositiveInfinity, double.PositiveInfinity); private float _lineHeight = 0; private float _lineOffset = 0; private Size _size; private List<AvaloniaFormattedTextLine> _skiaLines; private static void ApplyWrapperTo(ref SKPaint current, DrawingContextImpl.PaintWrapper wrapper, ref IDisposable curr, SKPaint paint, bool canUseLcdRendering) { if (current == wrapper.Paint) return; curr?.Dispose(); curr = wrapper.ApplyTo(paint); paint.LcdRenderText = canUseLcdRendering; } private static bool IsBreakChar(char c) { //white space or zero space whitespace return char.IsWhiteSpace(c) || c == '\u200B'; } private static int LineBreak(string textInput, int textIndex, int stop, SKPaint paint, float maxWidth, out int trailingCount) { int lengthBreak; if (maxWidth == -1) { lengthBreak = stop - textIndex; } else { float measuredWidth; string subText = textInput.Substring(textIndex, stop - textIndex); lengthBreak = (int)paint.BreakText(subText, maxWidth, out measuredWidth) / 2; } //Check for white space or line breakers before the lengthBreak int startIndex = textIndex; int index = textIndex; int word_start = textIndex; bool prevBreak = true; trailingCount = 0; while (index < stop) { int prevText = index; char currChar = textInput[index++]; bool currBreak = IsBreakChar(currChar); if (!currBreak && prevBreak) { word_start = prevText; } prevBreak = currBreak; if (index > startIndex + lengthBreak) { if (currBreak) { // eat the rest of the whitespace while (index < stop && IsBreakChar(textInput[index])) { index++; } trailingCount = index - prevText; } else { // backup until a whitespace (or 1 char) if (word_start == startIndex) { if (prevText > startIndex) { index = prevText; } } else { index = word_start; } } break; } if ('\n' == currChar) { int ret = index - startIndex; int lineBreakSize = 1; if (index < stop) { currChar = textInput[index++]; if ('\r' == currChar) { ret = index - startIndex; ++lineBreakSize; } } trailingCount = lineBreakSize; return ret; } if ('\r' == currChar) { int ret = index - startIndex; int lineBreakSize = 1; if (index < stop) { currChar = textInput[index++]; if ('\n' == currChar) { ret = index - startIndex; ++lineBreakSize; } } trailingCount = lineBreakSize; return ret; } } return index - startIndex; } private void BuildRects() { // Build character rects var fm = _paint.FontMetrics; SKTextAlign align = _paint.TextAlign; for (int li = 0; li < _skiaLines.Count; li++) { var line = _skiaLines[li]; float prevRight = TransformX(0, line.Width, align); double nextTop = line.Top + line.Height; if (li + 1 < _skiaLines.Count) { nextTop = _skiaLines[li + 1].Top; } for (int i = line.Start; i < line.Start + line.TextLength; i++) { float w = _paint.MeasureText(Text[i].ToString()); _rects.Add(new Rect( prevRight, line.Top, w, nextTop - line.Top)); prevRight += w; } } } private IBrush GetNextForegroundBrush(ref AvaloniaFormattedTextLine line, int index, out int length) { IBrush result = null; int len = length = line.Start + line.Length - index; if (_foregroundBrushes.Any()) { var bi = _foregroundBrushes.FindIndex(b => b.Key.StartIndex <= index && b.Key.EndIndex > index ); if (bi > -1) { var match = _foregroundBrushes[bi]; len = match.Key.EndIndex - index; result = match.Value; if (len > 0 && len < length) { length = len; } } int endIndex = index + length; int max = bi == -1 ? _foregroundBrushes.Count : bi; var next = _foregroundBrushes.Take(max) .Where(b => b.Key.StartIndex < endIndex && b.Key.StartIndex > index) .OrderBy(b => b.Key.StartIndex) .FirstOrDefault(); if (next.Value != null) { length = next.Key.StartIndex - index; } } return result; } private List<Rect> GetRects() { if (Text.Length > _rects.Count) { BuildRects(); } return _rects; } private void Rebuild() { var length = Text.Length; _lines.Clear(); _rects.Clear(); _skiaLines = new List<AvaloniaFormattedTextLine>(); int curOff = 0; float curY = 0; var metrics = _paint.FontMetrics; var mTop = metrics.Top; // The greatest distance above the baseline for any glyph (will be <= 0). var mBottom = metrics.Bottom; // The greatest distance below the baseline for any glyph (will be >= 0). var mLeading = metrics.Leading; // The recommended distance to add between lines of text (will be >= 0). var mDescent = metrics.Descent; //The recommended distance below the baseline. Will be >= 0. var mAscent = metrics.Ascent; //The recommended distance above the baseline. Will be <= 0. var lastLineDescent = mBottom - mDescent; // This seems like the best measure of full vertical extent // matches Direct2D line height _lineHeight = mDescent - mAscent; // Rendering is relative to baseline _lineOffset = (-metrics.Ascent); string subString; float widthConstraint = (_constraint.Width != double.PositiveInfinity) ? (float)_constraint.Width : -1; for (int c = 0; curOff < length; c++) { float lineWidth = -1; int measured; int trailingnumber = 0; subString = Text.Substring(curOff); float constraint = -1; if (_wrapping == TextWrapping.Wrap) { constraint = widthConstraint <= 0 ? MAX_LINE_WIDTH : widthConstraint; if (constraint > MAX_LINE_WIDTH) constraint = MAX_LINE_WIDTH; } measured = LineBreak(Text, curOff, length, _paint, constraint, out trailingnumber); AvaloniaFormattedTextLine line = new AvaloniaFormattedTextLine(); line.TextLength = measured; subString = Text.Substring(line.Start, line.TextLength); lineWidth = _paint.MeasureText(subString); line.Start = curOff; line.Length = measured - trailingnumber; line.Width = lineWidth; line.Height = _lineHeight; line.Top = curY; _skiaLines.Add(line); curY += _lineHeight; curY += mLeading; curOff += measured; } // Now convert to Avalonia data formats _lines.Clear(); float maxX = 0; for (var c = 0; c < _skiaLines.Count; c++) { var w = _skiaLines[c].Width; if (maxX < w) maxX = w; _lines.Add(new FormattedTextLine(_skiaLines[c].TextLength, _skiaLines[c].Height)); } if (_skiaLines.Count == 0) { _lines.Add(new FormattedTextLine(0, _lineHeight)); _size = new Size(0, _lineHeight); } else { var lastLine = _skiaLines[_skiaLines.Count - 1]; _size = new Size(maxX, lastLine.Top + lastLine.Height); } } private float TransformX(float originX, float lineWidth, SKTextAlign align) { float x = 0; if (align == SKTextAlign.Left) { x = originX; } else { double width = Constraint.Width > 0 && !double.IsPositiveInfinity(Constraint.Width) ? Constraint.Width : _size.Width; switch (align) { case SKTextAlign.Center: x = originX + (float)(width - lineWidth) / 2; break; case SKTextAlign.Right: x = originX + (float)(width - lineWidth); break; } } return x; } private void SetForegroundBrush(IBrush brush, int startIndex, int length) { var key = new FBrushRange(startIndex, length); int index = _foregroundBrushes.FindIndex(v => v.Key.Equals(key)); if (index > -1) { _foregroundBrushes.RemoveAt(index); } if (brush != null) { brush = brush.ToImmutable(); _foregroundBrushes.Insert(0, new KeyValuePair<FBrushRange, IBrush>(key, brush)); } } private struct AvaloniaFormattedTextLine { public float Height; public int Length; public int Start; public int TextLength; public float Top; public float Width; }; private struct FBrushRange { public FBrushRange(int startIndex, int length) { StartIndex = startIndex; Length = length; } public int EndIndex => StartIndex + Length; public int Length { get; private set; } public int StartIndex { get; private set; } public bool Intersects(int index, int len) => (index + len) > StartIndex && (StartIndex + Length) > index; public override string ToString() { return $"{StartIndex}-{EndIndex}"; } } } }
// // SpringerBook.cs // s.im.pl serialization // // Generated by MetaMetadataDotNetTranslator. // Copyright 2017 Interface Ecology Lab. // using Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.PublicationNS; using Ecologylab.BigSemantics.Generated.Library.SearchNS; using Ecologylab.BigSemantics.MetaMetadataNS; using Ecologylab.BigSemantics.MetadataNS; using Ecologylab.BigSemantics.MetadataNS.Builtins; using Ecologylab.BigSemantics.MetadataNS.Scalar; using Ecologylab.Collections; using Simpl.Fundamental.Generic; using Simpl.Serialization; using Simpl.Serialization.Attributes; using System; using System.Collections; using System.Collections.Generic; namespace Ecologylab.BigSemantics.Generated.Library.CreativeWorkNS.PublicationNS { /// <summary> /// A book in Springer Link. /// </summary> [SimplInherit] public class SpringerBook : Book { [SimplScalar] private MetadataString subtitle; [SimplCollection("springer_search")] [MmName("editor_names")] private List<SpringerSearch> editorNames; [SimplCollection("springer_search")] [MmName("book_chapters_incomplete")] private List<SpringerSearch> bookChaptersIncomplete; [SimplScalar] private MetadataString copyright; [SimplScalar] [SimplTag("DOI")] private MetadataString DOI; [SimplScalar] [SimplTag("print_ISBN")] private MetadataString printISBN; [SimplScalar] [SimplTag("online_ISBN")] private MetadataString onlineISBN; [SimplScalar] private MetadataString seriesVolume; [SimplScalar] [SimplTag("series_ISSN")] private MetadataString seriesISSN; [SimplScalar] private MetadataString copyrightHolder; [SimplCollection("springer_search")] [MmName("topics")] private List<SpringerSearch> topics; [SimplCollection("springer_search")] [MmName("ebook_packages")] private List<SpringerSearch> ebookPackages; [SimplCollection("editor_affiliation")] [MmName("editor_affiliations")] private List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> editorAffiliations; public SpringerBook() { } public SpringerBook(MetaMetadataCompositeField mmd) : base(mmd) { } public MetadataString Subtitle { get{return subtitle;} set { if (this.subtitle != value) { this.subtitle = value; // TODO we need to implement our property change notification mechanism. } } } public List<SpringerSearch> EditorNames { get{return editorNames;} set { if (this.editorNames != value) { this.editorNames = value; // TODO we need to implement our property change notification mechanism. } } } public List<SpringerSearch> BookChaptersIncomplete { get{return bookChaptersIncomplete;} set { if (this.bookChaptersIncomplete != value) { this.bookChaptersIncomplete = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString Copyright { get{return copyright;} set { if (this.copyright != value) { this.copyright = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString DOIProp { get{return DOI;} set { if (this.DOI != value) { this.DOI = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString PrintISBN { get{return printISBN;} set { if (this.printISBN != value) { this.printISBN = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString OnlineISBN { get{return onlineISBN;} set { if (this.onlineISBN != value) { this.onlineISBN = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString SeriesVolume { get{return seriesVolume;} set { if (this.seriesVolume != value) { this.seriesVolume = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString SeriesISSN { get{return seriesISSN;} set { if (this.seriesISSN != value) { this.seriesISSN = value; // TODO we need to implement our property change notification mechanism. } } } public MetadataString CopyrightHolder { get{return copyrightHolder;} set { if (this.copyrightHolder != value) { this.copyrightHolder = value; // TODO we need to implement our property change notification mechanism. } } } public List<SpringerSearch> Topics { get{return topics;} set { if (this.topics != value) { this.topics = value; // TODO we need to implement our property change notification mechanism. } } } public List<SpringerSearch> EbookPackages { get{return ebookPackages;} set { if (this.ebookPackages != value) { this.ebookPackages = value; // TODO we need to implement our property change notification mechanism. } } } public List<Ecologylab.BigSemantics.MetadataNS.Scalar.MetadataString> EditorAffiliations { get{return editorAffiliations;} set { if (this.editorAffiliations != value) { this.editorAffiliations = value; // TODO we need to implement our property change notification mechanism. } } } } }
using Shouldly; using StructureMap.Graph; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using System; using System.Linq; using Xunit; namespace StructureMap.Testing.Configuration.DSL { public class RegistryTester { public class RedGreenRegistry : Registry { public RedGreenRegistry() { For<IWidget>().Add<ColorWidget>().Ctor<string>("color").Is("Red").Named( "Red"); For<IWidget>().Add<ColorWidget>().Ctor<string>("color").Is("Green").Named( "Green"); } } public class YellowBlueRegistry : Registry { public YellowBlueRegistry() { For<IWidget>().Add<ColorWidget>().Ctor<string>("color").Is("Yellow").Named( "Yellow"); For<IWidget>().Add<ColorWidget>().Ctor<string>("color").Is("Blue").Named( "Blue"); } } // SAMPLE: simple-registry public class PurpleRegistry : Registry { public PurpleRegistry() { For<IWidget>().Use<AWidget>(); } } // ENDSAMPLE [Fact] public void Can_add_an_instance_for_concrete_class_with_no_constructors() { var registry = new Registry(); registry.For<ConcreteWithNoConstructor>().Use( c => ConcreteWithNoConstructor.Build()); var container = new Container(registry); container.GetInstance<ConcreteWithNoConstructor>().ShouldNotBeNull(); } [Fact] public void an_instance_of_the_base_registry_is_equal_to_itself() { var registry1 = new Registry(); registry1.Equals((object)registry1).ShouldBeTrue(); } [Fact] public void two_instances_of_the_base_registry_type_are_not_considered_equal() { var registry1 = new Registry(); var registry2 = new Registry(); registry1.Equals((object)registry2).ShouldBeFalse(); } [Fact] public void two_instances_of_a_public_derived_registry_type_are_considered_equal() { var registry1 = new TestRegistry(); var registry2 = new TestRegistry(); var registry3 = new TestRegistry2(); var registry4 = new TestRegistry2(); registry1.Equals((object)registry1).ShouldBeTrue(); registry1.Equals((object)registry2).ShouldBeTrue(); registry2.Equals((object)registry1).ShouldBeTrue(); registry3.Equals((object)registry4).ShouldBeTrue(); registry1.Equals((object)registry3).ShouldBeFalse(); registry3.Equals((object)registry1).ShouldBeFalse(); } [Fact] public void two_instances_of_a_non_public_derived_registry_type_are_not_considered_equal() { var registry1 = new InternalTestRegistry(); var registry2 = new InternalTestRegistry(); registry1.Equals((object)registry1).ShouldBeTrue(); registry1.Equals((object)registry2).ShouldBeFalse(); } // SAMPLE: including-registries [Fact] public void include_a_registry() { var registry = new Registry(); registry.IncludeRegistry<YellowBlueRegistry>(); registry.IncludeRegistry<RedGreenRegistry>(); registry.IncludeRegistry<PurpleRegistry>(); // build a container var container = new Container(registry); // verify the default implementation and total registered implementations container.GetInstance<IWidget>().ShouldBeOfType<AWidget>(); container.GetAllInstances<IWidget>().Count().ShouldBe(5); } // ENDSAMPLE public class MutatedWidget : IWidget { public void DoSomething() { } } public class MutatingRegistry : Registry { private static int count; public MutatingRegistry() { For<IWidget>().Use<AWidget>(); if (count++ >= 1) { For<IWidget>().Use<MutatedWidget>(); } } } [Fact] public void Latch_on_a_PluginGraph() { var registry2 = new TestRegistry2(); var graph = PluginGraph.CreateRoot(); graph.ImportRegistry(registry2); graph.QueuedRegistries.Count.ShouldBe(1); graph.ImportRegistry(registry2); graph.QueuedRegistries.Count.ShouldBe(1); } [Fact] public void use_the_basic_actions_as_part_of_building_a_PluginGraph() { var container = new Container(new BasicActionRegistry()); container.GetInstance<IGateway>().ShouldBeOfType<Fake3Gateway>(); } } public class ConcreteWithNoConstructor { private ConcreteWithNoConstructor() { } public static ConcreteWithNoConstructor Build() { return new ConcreteWithNoConstructor(); } } public class TestRegistry : Registry { } public class TestRegistry2 : Registry { private readonly int _count; public TestRegistry2() { _count++; } public int ExecutedCount { get { return _count; } } } internal class InternalTestRegistry : Registry { } public class FakeGateway : IGateway { #region IGateway Members public void DoSomething() { throw new NotImplementedException(); } public string WhoAmI { get { throw new NotImplementedException(); } } #endregion IGateway Members } public class Fake2Gateway : IGateway { #region IGateway Members public void DoSomething() { throw new NotImplementedException(); } public string WhoAmI { get { throw new NotImplementedException(); } } #endregion IGateway Members } public class Fake3Gateway : IGateway { #region IGateway Members public void DoSomething() { throw new NotImplementedException(); } public string WhoAmI { get { throw new NotImplementedException(); } } #endregion IGateway Members } public class BasicActionRegistry : Registry { public BasicActionRegistry() { For<IGateway>().Use<Fake3Gateway>(); } } }
// ReSharper disable InconsistentNaming // ReSharper disable UnusedParameter.Local namespace IIS.SLSharp.Shaders { public abstract partial class ShaderDefinition { public sealed class mat2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2 ( mat4 m ) { throw _invalidAccess; } public mat2 ( vec2 column1, vec2 column2 ) { throw _invalidAccess; } /// <summary>initialized the matrix with a vec4</summary> public mat2 ( vec4 compressedMatrix ) { throw _invalidAccess; } #endregion .ctor /// <summary> /// retrieves the selected column as vector /// </summary> /// <param name="column">zero based column index</param> /// <returns></returns> public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat2x3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2x3 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x3 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x3 ( mat4 m ) { throw _invalidAccess; } public mat2x3 ( vec3 column1, vec3 column2 ) { throw _invalidAccess; } #endregion .ctor public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat2x4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat2x4 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat2x4 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat2x4 ( mat4 m ) { throw _invalidAccess; } public mat2x4 ( vec4 column1, vec4 column2 ) { throw _invalidAccess; } #endregion .ctor public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3x2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3x2 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x2 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x2 ( mat4 m ) { throw _invalidAccess; } public mat3x2 ( vec2 column1, vec2 column2, vec2 column3 ) { throw _invalidAccess; } #endregion .ctor public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3 ( mat4 m ) { throw _invalidAccess; } public mat3 ( vec3 column1, vec3 column2, vec3 column3 ) { throw _invalidAccess; } #endregion .ctor public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat3x4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat3x4 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat3x4 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat3x4 ( mat4 m ) { throw _invalidAccess; } public mat3x4 ( vec4 column1, vec4 column2, vec4 column3 ) { throw _invalidAccess; } #endregion .ctor public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4x2 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4x2 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x2 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x2 ( mat4x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x2 ( mat4 m ) { throw _invalidAccess; } public mat4x2 ( vec2 column1, vec2 column2, vec2 column3, vec2 column4 ) { throw _invalidAccess; } #endregion .ctor public vec2 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4x3 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4x3 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4x3 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4x3 ( mat4 m ) { throw _invalidAccess; } public mat4x3 ( vec3 column1, vec3 column2, vec3 column3, vec3 column4 ) { throw _invalidAccess; } #endregion .ctor public vec3 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } public sealed class mat4 { #region .ctor /// <summary> Initialized all diogonal entries to scale </summary> public mat4 ( float scale ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat2x3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat2x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat3x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat3 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat3x4 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m /// sets the lower right diagonal component(s) to 1, everything else to 0</summary> public mat4 ( mat4x2 m ) { throw _invalidAccess; } /// <summary>initialized the matrix with the upperleft part of m</summary> public mat4 ( mat4x3 m ) { throw _invalidAccess; } public mat4 ( vec4 column1, vec4 column2, vec4 column3, vec4 column4 ) { throw _invalidAccess; } #endregion .ctor public vec4 this[int column] { get { throw _invalidAccess; } set { throw _invalidAccess; } } } } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedParameter.Local
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2012 ServiceStack Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // #if !XBOX && !MONOTOUCH && !SILVERLIGHT using System.Reflection.Emit; #endif using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { internal static class DeserializeType<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); public static ParseStringDelegate GetParseMethod(TypeConfig typeConfig) { var type = typeConfig.Type; #if NETFX_CORE if (!type.GetTypeInfo().IsClass || type.GetTypeInfo().IsAbstract || type.GetTypeInfo().IsInterface) return null; #else if (!type.IsClass || type.IsAbstract || type.IsInterface) return null; #endif var map = DeserializeTypeRef.GetTypeAccessorMap(typeConfig, Serializer); var ctorFn = JsConfig.ModelFactory(type); if (map == null) return value => ctorFn(); return typeof(TSerializer) == typeof(Json.JsonTypeSerializer) ? (ParseStringDelegate)(value => DeserializeTypeRefJson.StringToType(type, value, ctorFn, map)) : value => DeserializeTypeRefJsv.StringToType(type, value, ctorFn, map); } public static object ObjectStringToType(string strType) { var type = ExtractType(strType); if (type != null) { var parseFn = Serializer.GetParseFn(type); var propertyValue = parseFn(strType); return propertyValue; } if (JsConfig.ConvertObjectTypesIntoStringDictionary && !string.IsNullOrEmpty(strType)) { if (strType[0] == JsWriter.MapStartChar) { var dynamicMatch = DeserializeDictionary<TSerializer>.ParseDictionary<string, object>(strType, null, Serializer.UnescapeString, Serializer.UnescapeString); if (dynamicMatch != null && dynamicMatch.Count > 0) { return dynamicMatch; } } if (strType[0] == JsWriter.ListStartChar) { return DeserializeList<List<object>, TSerializer>.Parse(strType); } } return Serializer.UnescapeString(strType); } public static Type ExtractType(string strType) { var typeAttrInObject = Serializer.TypeAttrInObject; if (strType != null && strType.Length > typeAttrInObject.Length && strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.UnescapeSafeString(Serializer.EatValue(strType, ref propIndex)); var type = JsConfig.TypeFinder.Invoke(typeName); if (type == null) { Tracer.Instance.WriteWarning("Could not find type: " + typeName); return null; } #if !SILVERLIGHT && !MONOTOUCH if (type.IsInterface || type.IsAbstract) { return DynamicProxy.GetInstanceFor(type).GetType(); } #endif return type; } return null; } public static object ParseAbstractType<T>(string value) { #if NETFX_CORE if (typeof(T).GetTypeInfo().IsAbstract) #else if (typeof(T).IsAbstract) #endif { if (string.IsNullOrEmpty(value)) return null; var concreteType = ExtractType(value); if (concreteType != null) { return Serializer.GetParseFn(concreteType)(value); } Tracer.Instance.WriteWarning( "Could not deserialize Abstract Type with unknown concrete type: " + typeof(T).FullName); } return null; } public static object ParseQuotedPrimitive(string value) { if (string.IsNullOrEmpty(value)) return null; #if NET40 Guid guidValue; if (Guid.TryParse(value, out guidValue)) return guidValue; #endif if (value.StartsWith(DateTimeSerializer.EscapedWcfJsonPrefix) || value.StartsWith(DateTimeSerializer.WcfJsonPrefix)) { return DateTimeSerializer.ParseWcfJsonDate(value); } if (JsConfig.DateHandler == JsonDateHandler.ISO8601) { // check that we have UTC ISO8601 date: // YYYY-MM-DDThh:mm:ssZ // YYYY-MM-DDThh:mm:ss+02:00 // YYYY-MM-DDThh:mm:ss-02:00 if (value.Length > 14 && value[10] == 'T' && #if NETFX_CORE (value.EndsWith("Z", StringComparison.CurrentCulture) #else (value.EndsWith("Z", StringComparison.InvariantCulture) #endif || value[value.Length - 6] == '+' || value[value.Length - 6] == '-')) { return DateTimeSerializer.ParseShortestXsdDateTime(value); } } return Serializer.UnescapeString(value); } public static object ParsePrimitive(string value) { if (string.IsNullOrEmpty(value)) return null; bool boolValue; if (bool.TryParse(value, out boolValue)) return boolValue; decimal decimalValue; if (decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out decimalValue)) { if (decimalValue == decimal.Truncate(decimalValue)) { if (decimalValue <= ulong.MaxValue && decimalValue >= 0) return (ulong)decimalValue; if (decimalValue <= long.MaxValue && decimalValue >= long.MinValue) { var longValue = (long)decimalValue; if (longValue <= sbyte.MaxValue && longValue >= sbyte.MinValue) return (sbyte)longValue; if (longValue <= byte.MaxValue && longValue >= byte.MinValue) return (byte)longValue; if (longValue <= short.MaxValue && longValue >= short.MinValue) return (short)longValue; if (longValue <= ushort.MaxValue && longValue >= ushort.MinValue) return (ushort)longValue; if (longValue <= int.MaxValue && longValue >= int.MinValue) return (int)longValue; if (longValue <= uint.MaxValue && longValue >= uint.MinValue) return (uint)longValue; } } return decimalValue; } float floatValue; if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out floatValue)) return floatValue; double doubleValue; if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue)) return doubleValue; return null; } internal static object ParsePrimitive(string value, char firstChar) { if (typeof(TSerializer) == typeof(JsonTypeSerializer)) { return firstChar == JsWriter.QuoteChar ? ParseQuotedPrimitive(value) : ParsePrimitive(value); } return (ParsePrimitive(value) ?? ParseQuotedPrimitive(value)); } } internal class TypeAccessor { internal ParseStringDelegate GetProperty; internal SetPropertyDelegate SetProperty; internal Type PropertyType; public static Type ExtractType(ITypeSerializer Serializer, string strType) { var typeAttrInObject = Serializer.TypeAttrInObject; if (strType != null && strType.Length > typeAttrInObject.Length && strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.EatValue(strType, ref propIndex); var type = JsConfig.TypeFinder.Invoke(typeName); if (type == null) Tracer.Instance.WriteWarning("Could not find type: " + typeName); return type; } return null; } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, PropertyInfo propertyInfo) { return new TypeAccessor { PropertyType = propertyInfo.PropertyType, GetProperty = serializer.GetParseFn(propertyInfo.PropertyType), SetProperty = GetSetPropertyMethod(typeConfig, propertyInfo), }; } private static SetPropertyDelegate GetSetPropertyMethod(TypeConfig typeConfig, PropertyInfo propertyInfo) { #if NETFX_CORE if (propertyInfo.PropertyType != propertyInfo.DeclaringType) propertyInfo = propertyInfo.DeclaringType.GetRuntimeProperty(propertyInfo.Name); #else if (propertyInfo.ReflectedType != propertyInfo.DeclaringType) propertyInfo = propertyInfo.DeclaringType.GetProperty(propertyInfo.Name); #endif if (!propertyInfo.CanWrite && !typeConfig.EnableAnonymousFieldSetterses) return null; FieldInfo fieldInfo = null; if (!propertyInfo.CanWrite) { //TODO: What string comparison is used in SST? string fieldNameFormat = Env.IsMono ? "<{0}>" : "<{0}>i__Field"; var fieldName = string.Format(fieldNameFormat, propertyInfo.Name); #if NETFX_CORE var fieldInfos = typeConfig.Type.GetRuntimeFields().Where(p => !p.IsPublic && !p.IsStatic); #else var fieldInfos = typeConfig.Type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.SetField); #endif foreach (var f in fieldInfos) { if (f.IsInitOnly && f.FieldType == propertyInfo.PropertyType && f.Name == fieldName) { fieldInfo = f; break; } } if (fieldInfo == null) return null; } #if SILVERLIGHT || MONOTOUCH || XBOX if (propertyInfo.CanWrite) { #if NETFX_CORE var setMethodInfo = propertyInfo.SetMethod; #else var setMethodInfo = propertyInfo.GetSetMethod(true); #endif return (instance, value) => setMethodInfo.Invoke(instance, new[] { value }); } if (fieldInfo == null) return null; return (instance, value) => fieldInfo.SetValue(instance, value); #else return propertyInfo.CanWrite ? CreateIlPropertySetter(propertyInfo) : CreateIlFieldSetter(fieldInfo); #endif } #if !SILVERLIGHT && !MONOTOUCH && !XBOX private static SetPropertyDelegate CreateIlPropertySetter(PropertyInfo propertyInfo) { var propSetMethod = propertyInfo.GetSetMethod(true); if (propSetMethod == null) return null; var setter = CreateDynamicSetMethod(propertyInfo); var generator = setter.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.Emit(propertyInfo.PropertyType.IsClass ? OpCodes.Castclass : OpCodes.Unbox_Any, propertyInfo.PropertyType); generator.EmitCall(OpCodes.Callvirt, propSetMethod, (Type[])null); generator.Emit(OpCodes.Ret); return (SetPropertyDelegate)setter.CreateDelegate(typeof(SetPropertyDelegate)); } private static SetPropertyDelegate CreateIlFieldSetter(FieldInfo fieldInfo) { var setter = CreateDynamicSetMethod(fieldInfo); var generator = setter.GetILGenerator(); generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Castclass, fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.Emit(fieldInfo.FieldType.IsClass ? OpCodes.Castclass : OpCodes.Unbox_Any, fieldInfo.FieldType); generator.Emit(OpCodes.Stfld, fieldInfo); generator.Emit(OpCodes.Ret); return (SetPropertyDelegate)setter.CreateDelegate(typeof(SetPropertyDelegate)); } private static DynamicMethod CreateDynamicSetMethod(MemberInfo memberInfo) { var args = new[] { typeof(object), typeof(object) }; var name = string.Format("_{0}{1}_", "Set", memberInfo.Name); var returnType = typeof(void); return !memberInfo.DeclaringType.IsInterface ? new DynamicMethod(name, returnType, args, memberInfo.DeclaringType, true) : new DynamicMethod(name, returnType, args, memberInfo.Module, true); } #endif internal static SetPropertyDelegate GetSetPropertyMethod(Type type, PropertyInfo propertyInfo) { if (!propertyInfo.CanWrite || propertyInfo.GetIndexParameters().Any()) return null; #if SILVERLIGHT || MONOTOUCH || XBOX #if NETFX_CORE var setMethodInfo = propertyInfo.SetMethod; #else var setMethodInfo = propertyInfo.GetSetMethod(true); #endif return (instance, value) => setMethodInfo.Invoke(instance, new[] { value }); #else return CreateIlPropertySetter(propertyInfo); #endif } internal static SetPropertyDelegate GetSetFieldMethod(Type type, FieldInfo fieldInfo) { #if SILVERLIGHT || MONOTOUCH || XBOX return (instance, value) => fieldInfo.SetValue(instance, value); #else return CreateIlFieldSetter(fieldInfo); #endif } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, FieldInfo fieldInfo) { return new TypeAccessor { PropertyType = fieldInfo.FieldType, GetProperty = serializer.GetParseFn(fieldInfo.FieldType), SetProperty = GetSetFieldMethod(typeConfig, fieldInfo), }; } private static SetPropertyDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo) { #if NETFX_CORE if (fieldInfo.FieldType != fieldInfo.DeclaringType) fieldInfo = fieldInfo.DeclaringType.GetRuntimeField(fieldInfo.Name); #else if (fieldInfo.ReflectedType != fieldInfo.DeclaringType) fieldInfo = fieldInfo.DeclaringType.GetField(fieldInfo.Name); #endif #if SILVERLIGHT || MONOTOUCH || XBOX return (instance, value) => fieldInfo.SetValue(instance, value); #else return CreateIlFieldSetter(fieldInfo); #endif } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Activities.Presentation.Toolbox { using System; using System.Activities.Presentation.View; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Drawing.Design; using System.Runtime; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; // This class is responsible for rendering cate----ezed tools collection // It also provides methods for notifing user about tool selection/creation events [TemplatePart(Name = "PART_SearchBox"), TemplatePart(Name = "PART_Tools")] [ContentProperty("Categories")] sealed public partial class ToolboxControl : Control { public static readonly DependencyProperty ToolboxFileProperty = DependencyProperty.Register("ToolboxFile", typeof(string), typeof(ToolboxControl), new PropertyMetadata( string.Empty, new PropertyChangedCallback(OnToolboxFileChanged))); static readonly DependencyPropertyKey SelectedToolPropertyKey = DependencyProperty.RegisterReadOnly("SelectedTool", typeof(ToolboxItem), typeof(ToolboxControl), new PropertyMetadata( null, new PropertyChangedCallback(OnToolSelected))); public static readonly DependencyProperty SelectedToolProperty = SelectedToolPropertyKey.DependencyProperty; public static readonly DependencyProperty ToolItemStyleProperty = DependencyProperty.Register("ToolItemStyle", typeof(Style), typeof(ToolboxControl), new UIPropertyMetadata(null)); public static readonly DependencyProperty CategoryItemStyleProperty = DependencyProperty.Register("CategoryItemStyle", typeof(Style), typeof(ToolboxControl), new UIPropertyMetadata(null)); public static readonly DependencyProperty ToolTemplateProperty = DependencyProperty.Register("ToolTemplate", typeof(DataTemplate), typeof(ToolboxControl), new UIPropertyMetadata(null)); public static readonly DependencyProperty CategoryTemplateProperty = DependencyProperty.Register("CategoryTemplate", typeof(DataTemplate), typeof(ToolboxControl), new UIPropertyMetadata(null)); public static readonly RoutedEvent ToolCreatedEvent = EventManager.RegisterRoutedEvent("ToolCreated", RoutingStrategy.Bubble, typeof(ToolCreatedEventHandler), typeof(ToolboxControl)); public static readonly RoutedEvent ToolSelectedEvent = EventManager.RegisterRoutedEvent("ToolSelected", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ToolboxControl)); internal TextBox searchBox; TreeView toolsTreeView; ToolboxCategoryItems categories; [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static ToolboxControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToolboxControl), new FrameworkPropertyMetadata(typeof(ToolboxControl))); } public ToolboxControl() { var callback = new NotifyCollectionChangedEventHandler(this.OnCategoryCollectionChanged); this.categories = new ToolboxCategoryItems(callback); } public event ToolCreatedEventHandler ToolCreated { add { AddHandler(ToolCreatedEvent, value); } remove { RemoveHandler(ToolCreatedEvent, value); } } public event RoutedEventHandler ToolSelected { add { AddHandler(ToolSelectedEvent, value); } remove { RemoveHandler(ToolSelectedEvent, value); } } [Fx.Tag.KnownXamlExternal] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [SuppressMessage(FxCop.Category.Usage, "CA2227:CollectionPropertiesShouldBeReadOnly", Justification = "The setter implemenation is required for XAML support. The setter doesn't replace the collection instance, but copies its content to internal collection")] public ToolboxCategoryItems Categories { get { return this.categories; } set { this.categories.Clear(); if (null != value) { foreach (var category in value) { this.categories.Add(category); } } } } public string ToolboxFile { get { return (string)GetValue(ToolboxFileProperty); } set { SetValue(ToolboxFileProperty, value); } } [Fx.Tag.KnownXamlExternal] public ToolboxItem SelectedTool { get { return (ToolboxItem)GetValue(SelectedToolProperty); } private set { SetValue(SelectedToolPropertyKey, value); } } [Fx.Tag.KnownXamlExternal] public Style ToolItemStyle { get { return (Style)GetValue(ToolItemStyleProperty); } set { SetValue(ToolItemStyleProperty, value); } } [Fx.Tag.KnownXamlExternal] public Style CategoryItemStyle { get { return (Style)GetValue(CategoryItemStyleProperty); } set { SetValue(CategoryItemStyleProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate ToolTemplate { get { return (DataTemplate)GetValue(ToolTemplateProperty); } set { SetValue(ToolTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public DataTemplate CategoryTemplate { get { return (DataTemplate)GetValue(CategoryTemplateProperty); } set { SetValue(CategoryTemplateProperty, value); } } [Fx.Tag.KnownXamlExternal] public WorkflowDesigner AssociatedDesigner { get; set; } static void OnToolboxFileChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ToolboxControl toolboxControl = sender as ToolboxControl; string fileName = args.NewValue as string; if (null == toolboxControl || null == fileName) { throw FxTrace.Exception.AsError(new ArgumentNullException(null == toolboxControl ? "toolboxControl" : "fileName")); } try { ToolboxItemLoader loader = ToolboxItemLoader.GetInstance(); loader.LoadToolboxItems(fileName, toolboxControl.categories, false); } catch { if (!DesignerProperties.GetIsInDesignMode(toolboxControl)) { throw; } } } static void OnToolSelected(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ToolboxControl toolboxControl = sender as ToolboxControl; if (null == toolboxControl) { throw FxTrace.Exception.AsError(new ArgumentNullException("sender")); } if (null != toolboxControl.SelectedTool) { toolboxControl.RaiseEvent(new RoutedEventArgs(ToolSelectedEvent, toolboxControl)); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); //template is applied, look for required controls within it this.searchBox = this.Template.FindName("PART_SearchBox", this) as TextBox; this.toolsTreeView = this.Template.FindName("PART_Tools", this) as TreeView; //if tools tree view exists - assign style and container selectors (there are different styles //for Cateogries and Tools if (null != this.toolsTreeView) { this.toolsTreeView.ItemsSource = this.Categories; this.toolsTreeView.ItemContainerStyleSelector = new TreeViewContainerStyleSelector(this); this.toolsTreeView.ItemTemplateSelector = new TreeViewTemplateSelector(this); this.toolsTreeView.SelectedItemChanged += (s, e) => { var toolWrapper = e.NewValue as ToolboxItemWrapper; this.SelectedTool = toolWrapper != null ? toolWrapper.ToolboxItem : null; }; } } protected override void OnPreviewKeyDown(KeyEventArgs e) { switch (e.Key) { case Key.Up: case Key.Down: if (null != this.searchBox && e.OriginalSource == this.searchBox && null != this.toolsTreeView) { this.toolsTreeView.Focus(); } break; case Key.Enter: ToolboxItemCreated(); e.Handled = true; break; default: if (null != this.searchBox && e.Source != this.searchBox) { if (((e.Key >= Key.A && e.Key <= Key.Z) || (e.Key >= Key.D0 && e.Key <= Key.D9)) && (e.KeyboardDevice.Modifiers == ModifierKeys.None || e.KeyboardDevice.Modifiers == ModifierKeys.Shift)) { this.searchBox.Focus(); } } break; } base.OnPreviewKeyDown(e); } void OnCategoryCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (ToolboxCategory category in e.NewItems) { if (null == category) { throw FxTrace.Exception.ArgumentNull("category"); } var listener = new NotifyCollectionChangedEventHandler(OnToolsCollectionChange); category.HandleToolCollectionNotification(listener, true); var items = new List<ToolboxItemWrapper>(); foreach (ToolboxItemWrapper toolWrapper in category.Tools) { items.Add(toolWrapper); } OnToolsCollectionChange(category, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, items, 0)); } break; default: break; } if (null != this.toolsTreeView) { this.toolsTreeView.ItemsSource = null; this.toolsTreeView.ItemsSource = this.categories; } } void OnToolsCollectionChange(object sender, NotifyCollectionChangedEventArgs args) { switch (args.Action) { case NotifyCollectionChangedAction.Add: foreach (ToolboxItemWrapper tool in args.NewItems) { if (null == tool) { throw FxTrace.Exception.ArgumentNull("tool"); } tool.PropertyChanged += new PropertyChangedEventHandler(OnToolPropertyChanged); OnToolPropertyChanged(tool, null); } break; default: break; } } void OnToolPropertyChanged(object sender, PropertyChangedEventArgs e) { try { ToolboxItemWrapper tool = (ToolboxItemWrapper)sender; tool.ResolveToolboxItem(); } catch { if (!DesignerProperties.GetIsInDesignMode(this)) { throw; } } } internal void OnToolMouseMove(object sender, MouseEventArgs args) { ToolboxItem tool; ToolboxItemWrapper toolWrapper; if (args.LeftButton == MouseButtonState.Pressed && TryGetSelectedToolboxItem(out tool, out toolWrapper)) { IDataObject dataObject = toolWrapper.DataObject ?? new DataObject(); dataObject.SetData(DragDropHelper.WorkflowItemTypeNameFormat, toolWrapper.Type.AssemblyQualifiedName); DragDrop.DoDragDrop(this, dataObject, DragDropEffects.Link | DragDropEffects.Copy); } } internal void OnTreeViewDoubleClick(object sender, MouseEventArgs args) { ToolboxItemCreated(); } void ToolboxItemCreated() { ToolboxItem tool; ToolboxItemWrapper toolWrapper; if (TryGetSelectedToolboxItem(out tool, out toolWrapper)) { if (null != this.AssociatedDesigner && null != this.AssociatedDesigner.Context) { DesignerView target = this.AssociatedDesigner.Context.Services.GetService<DesignerView>(); IDataObject dataObject = toolWrapper.DataObject ?? new DataObject(); dataObject.SetData(DragDropHelper.WorkflowItemTypeNameFormat, toolWrapper.Type.AssemblyQualifiedName); ((RoutedCommand)DesignerView.CreateWorkflowElementCommand).Execute(dataObject, target); } ToolCreatedEventArgs args = new ToolCreatedEventArgs(ToolCreatedEvent, this, tool.CreateComponents()); RaiseEvent(args); } } bool TryGetSelectedToolboxItem(out ToolboxItem toolboxItem, out ToolboxItemWrapper toolboxItemWrapper) { toolboxItem = null; toolboxItemWrapper = null; if (null != this.toolsTreeView && null != this.toolsTreeView.SelectedItem) { ToolboxItemWrapper tool = this.toolsTreeView.SelectedItem as ToolboxItemWrapper; if (null != tool && null != tool.ToolboxItem) { toolboxItem = tool.ToolboxItem; toolboxItemWrapper = tool; } } return (null != toolboxItem); } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="VB6.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack.VisualStudio { using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using Microsoft.Build.Framework; using MSBuild.ExtensionPack.VisualStudio.Extended; /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>Build</i> (<b>Required: </b> Projects <b>Optional: </b>VB6Path, StopOnError)</para> /// <para><b>Remote Execution Support:</b> NA</para> /// <para/> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <ItemGroup> /// <ProjectsToBuild Include="C:\MyVB6Project.vbp"> /// <OutDir>c:\output</OutDir> /// <!-- Note the special use of ChgPropVBP metadata to change project properties at Build Time --> /// <ChgPropVBP>RevisionVer=4;CompatibleMode="0"</ChgPropVBP> /// </ProjectsToBuild> /// <ProjectsToBuild Include="C:\MyVB6Project2.vbp"/> /// </ItemGroup> /// <Target Name="Default"> /// <!-- Build a collection of VB6 projects --> /// <MSBuild.ExtensionPack.VisualStudio.VB6 TaskAction="Build" Projects="@(ProjectsToBuild)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class VB6 : BaseTask { private const char Separator = ';'; /// <summary> /// Sets the VB6Path. Default is [Program Files]\Microsoft Visual Studio\VB98\VB6.exe /// </summary> public string VB6Path { get; set; } /// <summary> /// Set to true to stop processing when a project in the Projects collection fails to compile. Default is false. /// </summary> public bool StopOnError { get; set; } /// <summary> /// Only build if any referenced source file is newer then the build output /// </summary> public bool IfModificationExists { get; set; } /// <summary> /// Sets the projects. Use an 'OutDir' metadata item to specify the output directory. The OutDir will be created if it does not exist. /// </summary> [Required] public ITaskItem[] Projects { get; set; } protected override void InternalExecute() { if (!this.TargetingLocalMachine()) { return; } if (string.IsNullOrEmpty(this.VB6Path)) { string programFilePath = Environment.GetEnvironmentVariable("ProgramFiles"); if (string.IsNullOrEmpty(programFilePath)) { this.Log.LogError("Failed to read a value from the ProgramFiles Environment Variable"); return; } if (File.Exists(programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe")) { this.VB6Path = programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe"; } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "VB6.exe was not found in the default location. Use VB6Path to specify it. Searched at: {0}", programFilePath + @"\Microsoft Visual Studio\VB98\VB6.exe")); return; } } switch (this.TaskAction) { case "Build": this.Build(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private void Build() { if (this.Projects == null) { this.Log.LogError("The collection passed to Projects is empty"); return; } this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Building Projects Collection: {0} projects", this.Projects.Length)); if (this.Projects.Any(project => !this.BuildProject(project) && this.StopOnError)) { this.LogTaskMessage("BuildVB6 Task Execution Failed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "] Stopped by StopOnError set on true"); return; } this.LogTaskMessage("BuildVB6 Task Execution Completed [" + DateTime.Now.ToString("HH:MM:ss", CultureInfo.CurrentCulture) + "]"); } private bool BuildProject(ITaskItem project) { using (Process proc = new Process()) { if (!string.IsNullOrEmpty(project.GetMetadata("ChgPropVBP"))) { this.LogTaskMessage("START - Changing Properties VBP"); VBPProject projectVBP = new VBPProject(project.ItemSpec); if (projectVBP.Load()) { string[] linesProperty = project.GetMetadata("ChgPropVBP").Split(Separator); string[] keyProperty = new string[linesProperty.Length]; string[] valueProperty = new string[linesProperty.Length]; int index; for (index = 0; index <= linesProperty.Length - 1; index++) { if (linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) != -1) { keyProperty[index] = linesProperty[index].Substring(0, linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase)); valueProperty[index] = linesProperty[index].Substring(linesProperty[index].IndexOf("=", StringComparison.OrdinalIgnoreCase) + 1); } if (!string.IsNullOrEmpty(keyProperty[index]) && !string.IsNullOrEmpty(valueProperty[index])) { this.LogTaskMessage(keyProperty[index] + " -> New value: " + valueProperty[index]); projectVBP.SetProjectProperty(keyProperty[index], valueProperty[index], false); } } projectVBP.Save(); } this.LogTaskMessage("END - Changing Properties VBP"); } FileInfo artifactFileInfo = null; if (this.IfModificationExists) { this.LogTaskMessage("START - Checking for modified files"); bool doBuild = false; VBPProject projectVBP = new VBPProject(project.ItemSpec); if (projectVBP.Load()) { FileInfo projectFileInfo = new FileInfo(projectVBP.ProjectFile); artifactFileInfo = projectVBP.ArtifactFile; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "artifactFile '{0}', LastWrite: {1}'", artifactFileInfo.FullName, artifactFileInfo.LastWriteTime)); if (projectFileInfo.LastWriteTime > artifactFileInfo.LastWriteTime) { this.LogTaskMessage(MessageImportance.High, $"File '{projectFileInfo.Name}' is newer then '{artifactFileInfo.Name}'"); doBuild = true; } else { foreach (var file in projectVBP.GetFiles()) { this.LogTaskMessage($"File '{file.FullName}', LastWrite: {file.LastWriteTime}'"); if (file.LastWriteTime > artifactFileInfo.LastWriteTime) { this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "File '{0}' is newer then '{1}'", file.Name, artifactFileInfo.Name)); doBuild = true; break; } } } } if (!doBuild) { this.LogTaskMessage(MessageImportance.High, "Build skipped, because no modifications exists."); return true; } this.LogTaskMessage("END - Checking for modified files"); } proc.StartInfo.FileName = this.VB6Path; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; if (string.IsNullOrEmpty(project.GetMetadata("OutDir"))) { proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @""""; } else { if (!Directory.Exists(project.GetMetadata("OutDir"))) { Directory.CreateDirectory(project.GetMetadata("OutDir")); } proc.StartInfo.Arguments = @"/MAKE /OUT " + @"""" + project.ItemSpec + ".log" + @""" " + @"""" + project.ItemSpec + @"""" + " /outdir " + @"""" + project.GetMetadata("OutDir") + @""""; } // start the process this.LogTaskMessage("Running " + proc.StartInfo.FileName + " " + proc.StartInfo.Arguments); proc.Start(); string outputStream = proc.StandardOutput.ReadToEnd(); if (outputStream.Length > 0) { this.LogTaskMessage(outputStream); } string errorStream = proc.StandardError.ReadToEnd(); if (errorStream.Length > 0) { this.Log.LogError(errorStream); } proc.WaitForExit(); if (proc.ExitCode != 0) { this.Log.LogError("Non-zero exit code from VB6.exe: " + proc.ExitCode); try { using (FileStream myStreamFile = new FileStream(project.ItemSpec + ".log", FileMode.Open)) { StreamReader myStream = new System.IO.StreamReader(myStreamFile); string myBuffer = myStream.ReadToEnd(); this.Log.LogError(myBuffer); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Unable to open log file: '{0}'. Exception: {1}", project.ItemSpec + ".log", ex.Message)); } return false; } if (artifactFileInfo != null) { var myNow = DateTime.Now; artifactFileInfo.LastWriteTime = myNow; artifactFileInfo.LastAccessTime = myNow; } return true; } } } }
// 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.Composition; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.GenerateMember.GenerateConstructor { [ExportLanguageService(typeof(IGenerateConstructorService), LanguageNames.CSharp), Shared] internal class CSharpGenerateConstructorService : AbstractGenerateConstructorService<CSharpGenerateConstructorService, ArgumentSyntax, AttributeArgumentSyntax> { private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation(); protected override bool IsSimpleNameGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { return node is SimpleNameSyntax; } protected override bool IsConstructorInitializerGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { return node is ConstructorInitializerSyntax; } protected override bool IsClassDeclarationGeneration(SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { return node is ClassDeclarationSyntax; } protected override bool TryInitializeConstructorInitializerGeneration( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out IList<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn) { var constructorInitializer = (ConstructorInitializerSyntax)node; if (!constructorInitializer.ArgumentList.CloseParenToken.IsMissing) { token = constructorInitializer.ThisOrBaseKeyword; arguments = constructorInitializer.ArgumentList.Arguments.ToList(); var semanticModel = document.SemanticModel; var currentType = semanticModel.GetEnclosingNamedType(constructorInitializer.SpanStart, cancellationToken); typeToGenerateIn = constructorInitializer.IsKind(SyntaxKind.ThisConstructorInitializer) ? currentType : currentType.BaseType.OriginalDefinition; return typeToGenerateIn != null; } token = default(SyntaxToken); arguments = null; typeToGenerateIn = null; return false; } protected override bool TryInitializeClassDeclarationGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out IMethodSymbol delegatedConstructor, out INamedTypeSymbol typeToGenerateIn) { token = default(SyntaxToken); typeToGenerateIn = null; delegatedConstructor = null; var semanticModel = document.SemanticModel; var classDeclaration = (ClassDeclarationSyntax)node; var classSymbol = semanticModel.GetDeclaredSymbol(classDeclaration, cancellationToken); var baseType = classSymbol.BaseType; var constructor = baseType.Constructors.FirstOrDefault(c => IsSymbolAccessible(c, document)); if (constructor == null) { return false; } typeToGenerateIn = classSymbol; delegatedConstructor = constructor; token = classDeclaration.Identifier; return true; } protected override bool TryInitializeSimpleNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out IList<ArgumentSyntax> arguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is ObjectCreationExpressionSyntax) { var objectCreationExpression = (ObjectCreationExpressionSyntax)fullName.Parent; if (objectCreationExpression.ArgumentList != null && !objectCreationExpression.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(objectCreationExpression.Type, cancellationToken); token = simpleName.Identifier; arguments = objectCreationExpression.ArgumentList.Arguments.ToList(); typeToGenerateIn = symbolInfo.GetAnySymbol() as INamedTypeSymbol; return typeToGenerateIn != null; } } token = default(SyntaxToken); arguments = null; typeToGenerateIn = null; return false; } protected override bool TryInitializeSimpleAttributeNameGenerationState( SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken, out SyntaxToken token, out IList<ArgumentSyntax> arguments, out IList<AttributeArgumentSyntax> attributeArguments, out INamedTypeSymbol typeToGenerateIn) { var simpleName = (SimpleNameSyntax)node; var fullName = simpleName.IsRightSideOfQualifiedName() ? (NameSyntax)simpleName.Parent : simpleName; if (fullName.Parent is AttributeSyntax) { var attribute = (AttributeSyntax)fullName.Parent; if (attribute.ArgumentList != null && !attribute.ArgumentList.CloseParenToken.IsMissing) { var symbolInfo = document.SemanticModel.GetSymbolInfo(attribute, cancellationToken); if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure && !symbolInfo.CandidateSymbols.IsEmpty) { token = simpleName.Identifier; attributeArguments = attribute.ArgumentList.Arguments.ToList(); arguments = attributeArguments.Select(x => SyntaxFactory.Argument(x.NameColon ?? ((x.NameEquals != null) ? SyntaxFactory.NameColon(x.NameEquals.Name) : null), default(SyntaxToken), x.Expression)).ToList(); typeToGenerateIn = symbolInfo.CandidateSymbols.FirstOrDefault().ContainingSymbol as INamedTypeSymbol; return typeToGenerateIn != null; } } } token = default(SyntaxToken); arguments = null; attributeArguments = null; typeToGenerateIn = null; return false; } protected override IList<string> GenerateParameterNames( SemanticModel semanticModel, IEnumerable<ArgumentSyntax> arguments, IList<string> reservedNames) { return semanticModel.GenerateParameterNames(arguments, reservedNames); } protected override IList<string> GenerateParameterNames( SemanticModel semanticModel, IEnumerable<AttributeArgumentSyntax> arguments, IList<string> reservedNames) { return semanticModel.GenerateParameterNames(arguments, reservedNames); } protected override string GenerateNameForArgument( SemanticModel semanticModel, ArgumentSyntax argument) { return semanticModel.GenerateNameForArgument(argument); } protected override string GenerateNameForArgument( SemanticModel semanticModel, AttributeArgumentSyntax argument) { return semanticModel.GenerateNameForArgument(argument); } protected override RefKind GetRefKind(ArgumentSyntax argument) { return argument.RefOrOutKeyword.Kind() == SyntaxKind.RefKeyword ? RefKind.Ref : argument.RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword ? RefKind.Out : RefKind.None; } protected override bool IsNamedArgument(ArgumentSyntax argument) { return argument.NameColon != null; } protected override ITypeSymbol GetArgumentType( SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken) { return semanticModel.GetType(argument.Expression, cancellationToken); } protected override ITypeSymbol GetAttributeArgumentType( SemanticModel semanticModel, AttributeArgumentSyntax argument, CancellationToken cancellationToken) { return semanticModel.GetType(argument.Expression, cancellationToken); } protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType) { return compilation.ClassifyConversion(sourceType, targetType).IsImplicit; } internal override IMethodSymbol GetDelegatingConstructor( State state, SemanticDocument document, int argumentCount, INamedTypeSymbol namedType, ISet<IMethodSymbol> candidates, CancellationToken cancellationToken) { var oldToken = state.Token; var tokenKind = oldToken.Kind(); if (state.IsConstructorInitializerGeneration) { SyntaxToken thisOrBaseKeyword; SyntaxKind newCtorInitializerKind; if (tokenKind != SyntaxKind.BaseKeyword && state.TypeToGenerateIn == namedType) { thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.ThisKeyword); newCtorInitializerKind = SyntaxKind.ThisConstructorInitializer; } else { thisOrBaseKeyword = SyntaxFactory.Token(SyntaxKind.BaseKeyword); newCtorInitializerKind = SyntaxKind.BaseConstructorInitializer; } var ctorInitializer = (ConstructorInitializerSyntax)oldToken.Parent; var oldArgumentList = ctorInitializer.ArgumentList; var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount); var newCtorInitializer = SyntaxFactory.ConstructorInitializer(newCtorInitializerKind, ctorInitializer.ColonToken, thisOrBaseKeyword, newArgumentList); SemanticModel speculativeModel; if (document.SemanticModel.TryGetSpeculativeSemanticModel(ctorInitializer.Span.Start, newCtorInitializer, out speculativeModel)) { var symbolInfo = speculativeModel.GetSymbolInfo(newCtorInitializer, cancellationToken); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, state.ParameterTypes); } } else { var oldNode = oldToken.Parent .AncestorsAndSelf(ascendOutOfTrivia: false) .Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node)) .LastOrDefault(); var typeNameToReplace = (TypeSyntax)oldToken.Parent; TypeSyntax newTypeName; if (namedType != state.TypeToGenerateIn) { while (true) { var parentType = typeNameToReplace.Parent as TypeSyntax; if (parentType == null) { break; } typeNameToReplace = parentType; } newTypeName = namedType.GenerateTypeSyntax().WithAdditionalAnnotations(s_annotation); } else { newTypeName = typeNameToReplace.WithAdditionalAnnotations(s_annotation); } var newNode = oldNode.ReplaceNode(typeNameToReplace, newTypeName); newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); var oldArgumentList = (ArgumentListSyntax)newTypeName.Parent.ChildNodes().FirstOrDefault(n => n is ArgumentListSyntax); if (oldArgumentList != null) { var newArgumentList = GetNewArgumentList(oldArgumentList, argumentCount); if (newArgumentList != oldArgumentList) { newNode = newNode.ReplaceNode(oldArgumentList, newArgumentList); newTypeName = (TypeSyntax)newNode.GetAnnotatedNodes(s_annotation).Single(); } } var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, document.SemanticModel); if (speculativeModel != null) { var symbolInfo = speculativeModel.GetSymbolInfo(newTypeName.Parent, cancellationToken); return GenerateConstructorHelpers.GetDelegatingConstructor( document, symbolInfo, candidates, namedType, state.ParameterTypes); } } return null; } private static ArgumentListSyntax GetNewArgumentList(ArgumentListSyntax oldArgumentList, int argumentCount) { if (oldArgumentList.IsMissing || oldArgumentList.Arguments.Count == argumentCount) { return oldArgumentList; } var newArguments = oldArgumentList.Arguments.Take(argumentCount); return SyntaxFactory.ArgumentList(new SeparatedSyntaxList<ArgumentSyntax>().AddRange(newArguments)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Text; namespace System.IO { public static partial class Path { public static readonly char DirectorySeparatorChar = '\\'; public static readonly char VolumeSeparatorChar = ':'; public static readonly char PathSeparator = ';'; private const string DirectorySeparatorCharAsString = "\\"; private static readonly char[] InvalidFileNameChars = { '\"', '<', '>', '|', '\0', (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, (char)31, ':', '*', '?', '\\', '/' }; // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. // string.WhitespaceChars will trim more aggressively than what the underlying FS does (for ex, NTFS, FAT). private static readonly char[] TrimEndChars = { (char)0x9, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20, (char)0x85, (char)0xA0 }; // The max total path is 260, and the max individual component length is 255. // For example, D:\<256 char file name> isn't legal, even though it's under 260 chars. internal static readonly int MaxPath = 260; private static readonly int MaxComponentLength = 255; internal static readonly int MaxLongPath = short.MaxValue; private static bool IsDirectoryOrVolumeSeparator(char c) { return PathInternal.IsDirectorySeparator(c) || VolumeSeparatorChar == c; } // Expands the given path to a fully qualified path. [Pure] [System.Security.SecuritySafeCritical] public static string GetFullPath(string path) { string fullPath = GetFullPathInternal(path); // Emulate FileIOPermissions checks, retained for compatibility PathInternal.CheckInvalidPathChars(fullPath, true); int startIndex = PathInternal.IsExtended(fullPath) ? PathInternal.ExtendedPathPrefix.Length + 2 : 2; if (fullPath.Length > startIndex && fullPath.IndexOf(':', startIndex) != -1) { throw new NotSupportedException(SR.Argument_PathFormatNotSupported); } return fullPath; } /// <summary> /// Checks for known bad extended paths (paths that start with \\?\) /// </summary> /// <param name="fullCheck">Check for invalid characters if true.</param> /// <returns>'true' if the path passes validity checks.</returns> private static bool ValidateExtendedPath(string path, bool fullCheck) { if (path.Length == PathInternal.ExtendedPathPrefix.Length) { // Effectively empty and therefore invalid return false; } if (path.StartsWith(PathInternal.UncExtendedPathPrefix, StringComparison.Ordinal)) { // UNC specific checks if (path.Length == PathInternal.UncExtendedPathPrefix.Length || path[PathInternal.UncExtendedPathPrefix.Length] == DirectorySeparatorChar) { // Effectively empty and therefore invalid (\\?\UNC\ or \\?\UNC\\) return false; } int serverShareSeparator = path.IndexOf(DirectorySeparatorChar, PathInternal.UncExtendedPathPrefix.Length); if (serverShareSeparator == -1 || serverShareSeparator == path.Length - 1) { // Need at least a Server\Share return false; } } // Segments can't be empty "\\" or contain *just* "." or ".." char twoBack = '?'; char oneBack = DirectorySeparatorChar; char currentCharacter; bool periodSegment = false; for (int i = PathInternal.ExtendedPathPrefix.Length; i < path.Length; i++) { currentCharacter = path[i]; switch (currentCharacter) { case '\\': if (oneBack == DirectorySeparatorChar || periodSegment) throw new ArgumentException(SR.Arg_PathIllegal); periodSegment = false; break; case '.': periodSegment = (oneBack == DirectorySeparatorChar || (twoBack == DirectorySeparatorChar && oneBack == '.')); break; default: periodSegment = false; break; } twoBack = oneBack; oneBack = currentCharacter; } if (periodSegment) { return false; } if (fullCheck) { // Look for illegal path characters. PathInternal.CheckInvalidPathChars(path); } return true; } [System.Security.SecurityCritical] // auto-generated private unsafe static string NormalizePath(string path, bool fullCheck, int maxPathLength, bool expandShortPaths) { Contract.Requires(path != null, "path can't be null"); // If the path is in extended syntax, we don't need to normalize, but we still do some basic validity checks if (PathInternal.IsExtended(path)) { if (!ValidateExtendedPath(path, fullCheck)) { throw new ArgumentException(SR.Arg_PathIllegal); } // \\?\GLOBALROOT gives access to devices out of the scope of the current user, we // don't want to allow this for security reasons. // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#nt_namespaces if (path.StartsWith(@"\\?\globalroot", StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(SR.Arg_PathGlobalRoot); return path; } // If we're doing a full path check, trim whitespace and look for // illegal path characters. if (fullCheck) { // Trim whitespace off the end of the string. // Win32 normalization trims only U+0020. path = path.TrimEnd(TrimEndChars); // Look for illegal path characters. PathInternal.CheckInvalidPathChars(path); } int index = 0; // We prefer to allocate on the stack for workingset/perf gain. If the // starting path is less than MaxPath then we can stackalloc; otherwise we'll // use a StringBuilder (PathHelper does this under the hood). The latter may // happen in 2 cases: // 1. Starting path is greater than MaxPath but it normalizes down to MaxPath. // This is relevant for paths containing escape sequences. In this case, we // attempt to normalize down to MaxPath, but the caller pays a perf penalty // since StringBuilder is used. // 2. IsolatedStorage, which supports paths longer than MaxPath (value given // by maxPathLength. PathHelper newBuffer = new PathHelper(path.Length + MaxPath, maxPathLength); uint numSpaces = 0; uint numDots = 0; bool fixupDirectorySeparator = false; // Number of significant chars other than potentially suppressible // dots and spaces since the last directory or volume separator char uint numSigChars = 0; int lastSigChar = -1; // Index of last significant character. // Whether this segment of the path (not the complete path) started // with a volume separator char. Reject "c:...". bool startedWithVolumeSeparator = false; bool firstSegment = true; int lastDirectorySeparatorPos = 0; bool mightBeShortFileName = false; // LEGACY: This code is here for backwards compatibility reasons. It // ensures that \\foo.cs\bar.cs stays \\foo.cs\bar.cs instead of being // turned into \foo.cs\bar.cs. if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[0])) { newBuffer.Append('\\'); index++; lastSigChar = 0; } // Normalize the string, stripping out redundant dots, spaces, and // slashes. while (index < path.Length) { char currentChar = path[index]; // We handle both directory separators and dots specially. For // directory separators, we consume consecutive appearances. // For dots, we consume all dots beyond the second in // succession. All other characters are added as is. In // addition we consume all spaces after the last other char // in a directory name up until the directory separator. if (PathInternal.IsDirectorySeparator(currentChar)) { // If we have a path like "123.../foo", remove the trailing dots. // However, if we found "c:\temp\..\bar" or "c:\temp\...\bar", don't. // Also remove trailing spaces from both files & directory names. // This was agreed on with the OS team to fix undeletable directory // names ending in spaces. // If we saw a '\' as the previous last significant character and // are simply going to write out dots, suppress them. // If we only contain dots and slashes though, only allow // a string like [dot]+ [space]*. Ignore everything else. // Legal: "\.. \", "\...\", "\. \" // Illegal: "\.. .\", "\. .\", "\ .\" if (numSigChars == 0) { // Dot and space handling if (numDots > 0) { // Look for ".[space]*" or "..[space]*" int start = lastSigChar + 1; if (path[start] != '.') throw new ArgumentException(SR.Arg_PathIllegal); // Only allow "[dot]+[space]*", and normalize the // legal ones to "." or ".." if (numDots >= 2) { // Reject "C:..." if (startedWithVolumeSeparator && numDots > 2) throw new ArgumentException(SR.Arg_PathIllegal); if (path[start + 1] == '.') { // Search for a space in the middle of the // dots and throw for (int i = start + 2; i < start + numDots; i++) { if (path[i] != '.') throw new ArgumentException(SR.Arg_PathIllegal); } numDots = 2; } else { if (numDots > 1) throw new ArgumentException(SR.Arg_PathIllegal); numDots = 1; } } if (numDots == 2) { newBuffer.Append('.'); } newBuffer.Append('.'); fixupDirectorySeparator = false; // Continue in this case, potentially writing out '\'. } if (numSpaces > 0 && firstSegment) { // Handle strings like " \\server\share". if (index + 1 < path.Length && PathInternal.IsDirectorySeparator(path[index + 1])) { newBuffer.Append(DirectorySeparatorChar); } } } numDots = 0; numSpaces = 0; // Suppress trailing spaces if (!fixupDirectorySeparator) { fixupDirectorySeparator = true; newBuffer.Append(DirectorySeparatorChar); } numSigChars = 0; lastSigChar = index; startedWithVolumeSeparator = false; firstSegment = false; // For short file names, we must try to expand each of them as // soon as possible. We need to allow people to specify a file // name that doesn't exist using a path with short file names // in it, such as this for a temp file we're trying to create: // C:\DOCUME~1\USERNA~1.RED\LOCALS~1\Temp\bg3ylpzp // We could try doing this afterwards piece by piece, but it's // probably a lot simpler to do it here. if (mightBeShortFileName) { newBuffer.TryExpandShortFileName(); mightBeShortFileName = false; } int thisPos = newBuffer.Length - 1; if (thisPos - lastDirectorySeparatorPos > MaxComponentLength + 1) { // Components can be up to 255 characters plus an additional null, // so separators can be 256 characters apart throw new PathTooLongException(SR.IO_PathTooLong); } lastDirectorySeparatorPos = thisPos; } // if (Found directory separator) else if (currentChar == '.') { // Reduce only multiple .'s only after slash to 2 dots. For // instance a...b is a valid file name. numDots++; // Don't flush out non-terminal spaces here, because they may in // the end not be significant. Turn "c:\ . .\foo" -> "c:\foo" // which is the conclusion of removing trailing dots & spaces, // as well as folding multiple '\' characters. } else if (currentChar == ' ') { numSpaces++; } else { // Normal character logic if (currentChar == '~' && expandShortPaths) mightBeShortFileName = true; fixupDirectorySeparator = false; // To reject strings like "C:...\foo" and "C :\foo" if (firstSegment && currentChar == VolumeSeparatorChar) { // Only accept "C:", not "c :" or ":" // Get a drive letter or ' ' if index is 0. char driveLetter = (index > 0) ? path[index - 1] : ' '; bool validPath = ((numDots == 0) && (numSigChars >= 1) && (driveLetter != ' ')); if (!validPath) throw new ArgumentException(SR.Arg_PathIllegal); startedWithVolumeSeparator = true; // We need special logic to make " c:" work, we should not fix paths like " foo::$DATA" if (numSigChars > 1) { // Common case, simply do nothing int spaceCount = 0; // How many spaces did we write out, numSpaces has already been reset. while ((spaceCount < newBuffer.Length) && newBuffer[spaceCount] == ' ') spaceCount++; if (numSigChars - spaceCount == 1) { //Safe to update stack ptr directly newBuffer.Length = 0; newBuffer.Append(driveLetter); // Overwrite spaces, we need a special case to not break " foo" as a relative path. } } numSigChars = 0; } else { numSigChars += 1 + numDots + numSpaces; } // Copy any spaces & dots since the last significant character // to here. Note we only counted the number of dots & spaces, // and don't know what order they're in. Hence the copy. if (numDots > 0 || numSpaces > 0) { int numCharsToCopy = (lastSigChar >= 0) ? index - lastSigChar - 1 : index; if (numCharsToCopy > 0) { for (int i = 0; i < numCharsToCopy; i++) { newBuffer.Append(path[lastSigChar + 1 + i]); } } numDots = 0; numSpaces = 0; } newBuffer.Append(currentChar); lastSigChar = index; } index++; } // end while // Components can be up to 255 characters plus an additional null if (newBuffer.Length - lastDirectorySeparatorPos > MaxComponentLength) { throw new PathTooLongException(SR.IO_PathTooLong); } // Drop any trailing dots and spaces from file & directory names, EXCEPT // we MUST make sure that "C:\foo\.." is correctly handled. // Also handle "C:\foo\." -> "C:\foo", while "C:\." -> "C:\" if (numSigChars == 0) { if (numDots > 0) { // Look for ".[space]*" or "..[space]*" int start = lastSigChar + 1; if (path[start] != '.') throw new ArgumentException(SR.Arg_PathIllegal); // Only allow "[dot]+[space]*", and normalize the // legal ones to "." or ".." if (numDots >= 2) { // Reject "C:..." if (startedWithVolumeSeparator && numDots > 2) throw new ArgumentException(SR.Arg_PathIllegal); if (path[start + 1] == '.') { // Search for a space in the middle of the // dots and throw for (int i = start + 2; i < start + numDots; i++) { if (path[i] != '.') throw new ArgumentException(SR.Arg_PathIllegal); } numDots = 2; } else { if (numDots > 1) throw new ArgumentException(SR.Arg_PathIllegal); numDots = 1; } } if (numDots == 2) { newBuffer.Append('.'); } newBuffer.Append('.'); } } // if (numSigChars == 0) // If we ended up eating all the characters, bail out. if (newBuffer.Length == 0) throw new ArgumentException(SR.Arg_PathIllegal); // Disallow URL's here. Some of our other Win32 API calls will reject // them later, so we might be better off rejecting them here. // Note we've probably turned them into "file:\D:\foo.tmp" by now. // But for compatibility, ensure that callers that aren't doing a // full check aren't rejected here. if (fullCheck) { if (newBuffer.OrdinalStartsWith("http:", false) || newBuffer.OrdinalStartsWith("file:", false)) { throw new ArgumentException(SR.Argument_PathUriFormatNotSupported); } } // If the last part of the path (file or directory name) had a tilde, // expand that too. if (mightBeShortFileName) { newBuffer.TryExpandShortFileName(); } // Call the Win32 API to do the final canonicalization step. int result = 1; if (fullCheck) { // NOTE: Win32 GetFullPathName requires the input buffer to be big enough to fit the initial // path which is a concat of CWD and the relative path, this can be of an arbitrary // size and could be > MaxPath (which becomes an artificial limit at this point), // even though the final normalized path after fixing up the relative path syntax // might be well within the MaxPath restriction. For ex, // "c:\SomeReallyLongDirName(thinkGreaterThan_MAXPATH)\..\foo.txt" which actually requires a // buffer well with in the MaxPath as the normalized path is just "c:\foo.txt" // This buffer requirement seems wrong, it could be a bug or a perf optimization // like returning required buffer length quickly or avoid stratch buffer etc. // Either way we need to workaround it here... // Ideally we would get the required buffer length first by calling GetFullPathName // once without the buffer and use that in the later call but this doesn't always work // due to Win32 GetFullPathName bug. For instance, in Win2k, when the path we are trying to // fully qualify is a single letter name (such as "a", "1", ",") GetFullPathName // fails to return the right buffer size (i.e, resulting in insufficient buffer). // To workaround this bug we will start with MaxPath buffer and grow it once if the // return value is > MaxPath. result = newBuffer.GetFullPathName(); // If we called GetFullPathName with something like "foo" and our // command window was in short file name mode (ie, by running edlin or // DOS versions of grep, etc), we might have gotten back a short file // name. So, check to see if we need to expand it. mightBeShortFileName = false; for (int i = 0; i < newBuffer.Length && !mightBeShortFileName; i++) { if (newBuffer[i] == '~' && expandShortPaths) mightBeShortFileName = true; } if (mightBeShortFileName) { bool r = newBuffer.TryExpandShortFileName(); // Consider how the path "Doesn'tExist" would expand. If // we add in the current directory, it too will need to be // fully expanded, which doesn't happen if we use a file // name that doesn't exist. if (!r) { int lastSlash = -1; for (int i = newBuffer.Length - 1; i >= 0; i--) { if (newBuffer[i] == DirectorySeparatorChar) { lastSlash = i; break; } } if (lastSlash >= 0) { // This bounds check is for safe memcpy but we should never get this far if (newBuffer.Length >= maxPathLength) throw new PathTooLongException(SR.IO_PathTooLong); int lenSavedName = newBuffer.Length - lastSlash - 1; Debug.Assert(lastSlash < newBuffer.Length, "path unexpectedly ended in a '\'"); newBuffer.Fixup(lenSavedName, lastSlash); } } } } if (result != 0) { /* Throw an ArgumentException for paths like \\, \\server, \\server\ This check can only be properly done after normalizing, so \\foo\.. will be properly rejected. */ if (newBuffer.Length > 1 && newBuffer[0] == '\\' && newBuffer[1] == '\\') { int startIndex = 2; while (startIndex < result) { if (newBuffer[startIndex] == '\\') { startIndex++; break; } else { startIndex++; } } if (startIndex == result) throw new ArgumentException(SR.Arg_PathIllegalUNC); } } // Check our result and form the managed string as necessary. if (newBuffer.Length >= maxPathLength) throw new PathTooLongException(SR.IO_PathTooLong); if (result == 0) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.mincore.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path); } string returnVal = newBuffer.ToString(); if (string.Equals(returnVal, path, StringComparison.Ordinal)) { returnVal = path; } return returnVal; } [System.Security.SecuritySafeCritical] public static string GetTempPath() { StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempPathW(MaxPath, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return GetFullPathInternal(StringBuilderCache.GetStringAndRelease(sb)); } [System.Security.SecurityCritical] private static string InternalGetTempFileName(bool checkHost) { // checkHost was originally intended for file security checks, but is ignored. string path = GetTempPath(); StringBuilder sb = StringBuilderCache.Acquire(MaxPath); uint r = Interop.mincore.GetTempFileNameW(path, "tmp", 0, sb); if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); return StringBuilderCache.GetStringAndRelease(sb); } // Tests if the given path contains a root. A path is considered rooted // if it starts with a backslash ("\") or a drive letter and a colon (":"). [Pure] public static bool IsPathRooted(string path) { if (path != null) { PathInternal.CheckInvalidPathChars(path); int length = path.Length; if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])) || (length >= 2 && path[1] == VolumeSeparatorChar)) return true; } return false; } } }
// Copyright (c) 2008-2018, Hazelcast, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Concurrent; using System.Threading; using Hazelcast.Client.Connection; using Hazelcast.Client.Protocol.Codec; using Hazelcast.Core; using Hazelcast.IO; using Hazelcast.IO.Serialization; using Hazelcast.Logging; using Hazelcast.Net.Ext; using Hazelcast.Util; #pragma warning disable CS1591 namespace Hazelcast.Client.Spi { internal sealed class ClientPartitionService : IClientPartitionService { private const int PartitionTimeout = 60000; private const int PartitionRefreshPeriod = 10000; private static readonly ILogger Logger = Logging.Logger.GetLogger(typeof (IClientPartitionService)); private readonly HazelcastClient _client; private readonly ConcurrentDictionary<int, Address> _partitions = new ConcurrentDictionary<int, Address>(); private readonly AtomicBoolean _updating = new AtomicBoolean(false); private volatile bool _isLive; private volatile int _partitionCount; private CancellationTokenSource _partitionUpdaterToken; public ClientPartitionService(HazelcastClient client) { _client = client; } public Address GetPartitionOwner(int partitionId) { Address rtn; _partitions.TryGetValue(partitionId, out rtn); return rtn; } public int GetPartitionId(object key) { var data = _client.GetSerializationService().ToData(key); return GetPartitionId(data); } public int GetPartitionCount() { if (_partitionCount == 0) { GetPartitionsBlocking(); } return _partitionCount; } public void RefreshPartitions() { _client.GetClientExecutionService().Submit(() => { GetPartitions(); }).IgnoreExceptions(); } public void Start() { _isLive = true; _partitionUpdaterToken = new CancellationTokenSource(); _client.GetClientExecutionService().ScheduleWithFixedDelay(() => GetPartitions(), 0, PartitionRefreshPeriod, TimeUnit.Milliseconds, _partitionUpdaterToken.Token); } public void Stop() { try { _isLive = false; try { _partitionUpdaterToken.Cancel(); } finally { _partitionUpdaterToken.Dispose(); } } catch (Exception e) { Logger.Finest("Shut down partition refresher thread problem...", e); } _partitions.Clear(); } internal int GetPartitionId(IData key) { var pc = GetPartitionCount(); if (pc <= 0) { return 0; } var hash = key.GetPartitionHash(); return (hash == int.MinValue) ? 0 : Math.Abs(hash)%pc; } private bool GetPartitions() { if (_isLive && _updating.CompareAndSet(false, true)) { try { Logger.Finest("Updating partition list."); var clusterService = _client.GetClientClusterService(); var ownerAddress = clusterService.GetOwnerConnectionAddress(); if (ownerAddress == null) { throw new InvalidOperationException("Owner address was null"); } var connection = _client.GetConnectionManager().GetConnection(ownerAddress); if (connection == null) { throw new InvalidOperationException( "Owner connection is not available, could not get partitions."); } var response = GetPartitionsFrom(connection); var result = ProcessPartitionResponse(response); Logger.Finest("Partition list updated"); return result; } catch (HazelcastInstanceNotActiveException) { } catch (Exception e) { Logger.Warning("Error when getting list of partitions", e); } finally { _updating.Set(false); } } return false; } private void GetPartitionsBlocking() { while (!GetPartitions() && _isLive) { Thread.Sleep(PartitionRefreshPeriod); } } private ClientGetPartitionsCodec.ResponseParameters GetPartitionsFrom(ClientConnection connection) { var request = ClientGetPartitionsCodec.EncodeRequest(); var task = ((ClientInvocationService) _client.GetInvocationService()).InvokeOnConnection(request, connection); var result = ThreadUtil.GetResult(task, PartitionTimeout); return ClientGetPartitionsCodec.DecodeResponse(result); } private bool ProcessPartitionResponse(ClientGetPartitionsCodec.ResponseParameters response) { var partitionResponse = response.partitions; foreach (var entry in partitionResponse) { var address = entry.Key; foreach (var partition in entry.Value) { _partitions.AddOrUpdate(partition, address, (p, a) => address); } } _partitionCount = _partitions.Count; return _partitionCount > 0; } // { // if (owner != null) // var owner = _client.GetPartitionService().GetPartitionOwner(_partitionId); // { // public IMember GetOwner() // TODO: will be useful when the ClientPartitionServiceProxy is implemeneted // internal class Partition : IPartition // { // private readonly HazelcastClient _client; // private readonly int _partitionId; // // public Partition(HazelcastClient client, int partitionId) // { // _client = client; // _partitionId = partitionId; // } // // public int GetPartitionId() // { // return _partitionId; // } // // return _client.GetClientClusterService().GetMember(owner); // } // return null; // } // // public override string ToString() // { // var sb = new StringBuilder("PartitionImpl{"); // sb.Append("partitionId=").Append(_partitionId); // sb.Append('}'); // return sb.ToString(); // } // } } }
using System.Buffers; using System.Diagnostics; using System.IO; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace k8s { /// <summary> /// <para> /// The <see cref="StreamDemuxer"/> allows you to interact with processes running in a container in a Kubernetes pod. You can start an exec or attach command /// by calling <see cref="Kubernetes.WebSocketNamespacedPodExecAsync(string, string, IEnumerable{string}, string, bool, bool, bool, bool, Dictionary{string, List{string}}, CancellationToken)"/> /// or <see cref="Kubernetes.WebSocketNamespacedPodAttachAsync(string, string, string, bool, bool, bool, bool, Dictionary{string, List{string}}, CancellationToken)"/>. These methods /// will return you a <see cref="WebSocket"/> connection. /// </para> /// <para> /// Kubernetes 'multiplexes' multiple channels over this <see cref="WebSocket"/> connection, such as standard input, standard output and standard error. The <see cref="StreamDemuxer"/> /// allows you to extract individual <see cref="Stream"/>s from this <see cref="WebSocket"/> class. You can then use these streams to send/receive data from that process. /// </para> /// </summary> public class StreamDemuxer : IStreamDemuxer { private readonly WebSocket webSocket; private readonly Dictionary<byte, ByteBuffer> buffers = new Dictionary<byte, ByteBuffer>(); private readonly CancellationTokenSource cts = new CancellationTokenSource(); private readonly StreamType streamType; private readonly bool ownsSocket; private Task runLoop; private bool disposedValue; /// <summary> /// Initializes a new instance of the <see cref="StreamDemuxer"/> class. /// </summary> /// <param name="webSocket"> /// A <see cref="WebSocket"/> which contains a multiplexed stream, such as the <see cref="WebSocket"/> returned by the exec or attach commands. /// </param> /// <param name="streamType"> /// A <see cref="StreamType"/> specifies the type of the stream. /// </param> /// <param name="ownsSocket"> /// A value indicating whether this instance of the <see cref="StreamDemuxer"/> owns the underlying <see cref="WebSocket"/>, /// and should dispose of it when this instance is disposed of. /// </param> public StreamDemuxer(WebSocket webSocket, StreamType streamType = StreamType.RemoteCommand, bool ownsSocket = false) { this.streamType = streamType; this.webSocket = webSocket ?? throw new ArgumentNullException(nameof(webSocket)); this.ownsSocket = ownsSocket; } public event EventHandler ConnectionClosed; /// <summary> /// Starts reading the data sent by the server. /// </summary> public void Start() { runLoop = Task.Run(async () => await RunLoop(cts.Token).ConfigureAwait(false)); } /// <summary> /// Gets a <see cref="Stream"/> which allows you to read to and/or write from a remote channel. /// </summary> /// <param name="inputIndex"> /// The index of the channel from which to read. /// </param> /// <param name="outputIndex"> /// The index of the channel to which to write. /// </param> /// <returns> /// A <see cref="Stream"/> which allows you to read/write to the requested channels. /// </returns> public Stream GetStream(ChannelIndex? inputIndex, ChannelIndex? outputIndex) { return GetStream((byte?)inputIndex, (byte?)outputIndex); } /// <summary> /// Gets a <see cref="Stream"/> which allows you to read to and/or write from a remote channel. /// </summary> /// <param name="inputIndex"> /// The index of the channel from which to read. /// </param> /// <param name="outputIndex"> /// The index of the channel to which to write. /// </param> /// <returns> /// A <see cref="Stream"/> which allows you to read/write to the requested channels. /// </returns> public Stream GetStream(byte? inputIndex, byte? outputIndex) { lock (buffers) { if (inputIndex != null && !buffers.ContainsKey(inputIndex.Value)) { var buffer = new ByteBuffer(); buffers.Add(inputIndex.Value, buffer); } } var inputBuffer = inputIndex == null ? null : buffers[inputIndex.Value]; return new MuxedStream(this, inputBuffer, outputIndex); } /// <summary> /// Directly writes data to a channel. /// </summary> /// <param name="index"> /// The index of the channel to which to write. /// </param> /// <param name="buffer"> /// The buffer from which to read data. /// </param> /// <param name="offset"> /// The offset at which to start reading. /// </param> /// <param name="count"> /// The number of bytes to read. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation. /// </param> /// <returns> /// A <see cref="Task"/> which represents the asynchronous operation. /// </returns> public Task Write(ChannelIndex index, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) { return Write((byte)index, buffer, offset, count, cancellationToken); } /// <summary> /// Directly writes data to a channel. /// </summary> /// <param name="index"> /// The index of the channel to which to write. /// </param> /// <param name="buffer"> /// The buffer from which to read data. /// </param> /// <param name="offset"> /// The offset at which to start reading. /// </param> /// <param name="count"> /// The number of bytes to read. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> which can be used to cancel the asynchronous operation. /// </param> /// <returns> /// A <see cref="Task"/> which represents the asynchronous operation. /// </returns> public async Task Write(byte index, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) { var writeBuffer = ArrayPool<byte>.Shared.Rent(count + 1); try { writeBuffer[0] = (byte)index; Array.Copy(buffer, offset, writeBuffer, 1, count); var segment = new ArraySegment<byte>(writeBuffer, 0, count + 1); await webSocket.SendAsync(segment, WebSocketMessageType.Binary, false, cancellationToken) .ConfigureAwait(false); } finally { ArrayPool<byte>.Shared.Return(writeBuffer); } } protected async Task RunLoop(CancellationToken cancellationToken) { // Get a 1KB buffer var buffer = ArrayPool<byte>.Shared.Rent(1024 * 1024); // This maps remembers bytes skipped for each stream. var streamBytesToSkipMap = new Dictionary<byte, int>(); try { var segment = new ArraySegment<byte>(buffer); while (!cancellationToken.IsCancellationRequested && webSocket.CloseStatus == null) { // We always get data in this format: // [stream index] (1 for stdout, 2 for stderr) // [payload] var result = await webSocket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false); // Ignore empty messages if (result.Count < 2) { continue; } var streamIndex = buffer[0]; var extraByteCount = 1; while (true) { var bytesToSkip = 0; if (!streamBytesToSkipMap.TryGetValue(streamIndex, out bytesToSkip)) { // When used in port-forwarding, the first 2 bytes from the web socket is port bytes, skip. // https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/server/portforward/websocket.go bytesToSkip = streamType == StreamType.PortForward ? 2 : 0; } var bytesCount = result.Count - extraByteCount; if (bytesToSkip > 0 && bytesToSkip >= bytesCount) { // skip the entire data. bytesToSkip -= bytesCount; extraByteCount += bytesCount; bytesCount = 0; } else { bytesCount -= bytesToSkip; extraByteCount += bytesToSkip; bytesToSkip = 0; if (buffers.ContainsKey(streamIndex)) { buffers[streamIndex].Write(buffer, extraByteCount, bytesCount); } } streamBytesToSkipMap[streamIndex] = bytesToSkip; if (result.EndOfMessage == true) { break; } extraByteCount = 0; result = await webSocket.ReceiveAsync(segment, cancellationToken).ConfigureAwait(false); } } } finally { ArrayPool<byte>.Shared.Return(buffer); runLoop = null; foreach (var b in buffers.Values) { b.WriteEnd(); } ConnectionClosed?.Invoke(this, EventArgs.Empty); } } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { try { if (runLoop != null) { cts.Cancel(); cts.Dispose(); runLoop.Wait(); } } catch (Exception ex) { // Dispose methods can never throw. Debug.Write(ex); } if (ownsSocket) { webSocket.Dispose(); } } disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~StreamDemuxer() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(true); GC.SuppressFinalize(this); } } }
/* * 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 log4net; using Nini.Config; using OpenSim.Framework; using OpenMetaverse; namespace OpenSim.Region.PhysicsModules.SharedBase { public delegate void physicsCrash(); public delegate void RaycastCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 normal); public delegate void RayCallback(List<ContactResult> list); public delegate void JointMoved(PhysicsJoint joint); public delegate void JointDeactivated(PhysicsJoint joint); public delegate void JointErrorMessage(PhysicsJoint joint, string message); // this refers to an "error message due to a problem", not "amount of joint constraint violation" public enum RayFilterFlags : ushort { // the flags water = 0x01, land = 0x02, agent = 0x04, nonphysical = 0x08, physical = 0x10, phantom = 0x20, volumedtc = 0x40, // ray cast colision control (may only work for meshs) ContactsUnImportant = 0x2000, BackFaceCull = 0x4000, ClosestHit = 0x8000, // some combinations LSLPhantom = phantom | volumedtc, PrimsNonPhantom = nonphysical | physical, PrimsNonPhantomAgents = nonphysical | physical | agent, AllPrims = nonphysical | phantom | volumedtc | physical, AllButLand = agent | nonphysical | physical | phantom | volumedtc, ClosestAndBackCull = ClosestHit | BackFaceCull, All = 0x3f } public delegate void RequestAssetDelegate(UUID assetID, AssetReceivedDelegate callback); public delegate void AssetReceivedDelegate(AssetBase asset); /// <summary> /// Contact result from a raycast. /// </summary> public struct ContactResult { public Vector3 Pos; public float Depth; public uint ConsumerID; public Vector3 Normal; } public abstract class PhysicsScene { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// A unique identifying string for this instance of the physics engine. /// Useful in debug messages to distinguish one OdeScene instance from another. /// Usually set to include the region name that the physics engine is acting for. /// </summary> public string PhysicsSceneName { get; protected set; } /// <summary> /// A string identifying the family of this physics engine. Most common values returned /// are "OpenDynamicsEngine" and "BulletSim" but others are possible. /// </summary> public string EngineType { get; protected set; } // The only thing that should register for this event is the SceneGraph // Anything else could cause problems. public event physicsCrash OnPhysicsCrash; public static PhysicsScene Null { get { return new NullPhysicsScene(); } } public RequestAssetDelegate RequestAssetMethod { get; set; } protected void Initialise(RequestAssetDelegate m, float[] terrain, float waterHeight) { RequestAssetMethod = m; SetTerrain(terrain); SetWaterLevel(waterHeight); } public virtual void TriggerPhysicsBasedRestart() { physicsCrash handler = OnPhysicsCrash; if (handler != null) { OnPhysicsCrash(); } } /// <summary> /// Add an avatar /// </summary> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="velocity"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public abstract PhysicsActor AddAvatar( string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying); /// <summary> /// Add an avatar /// </summary> /// <param name="localID"></param> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="velocity"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public virtual PhysicsActor AddAvatar( uint localID, string avName, Vector3 position, Vector3 velocity, Vector3 size, bool isFlying) { PhysicsActor ret = AddAvatar(avName, position, velocity, size, isFlying); if (ret != null) ret.LocalID = localID; return ret; } /// <summary> /// Remove an avatar. /// </summary> /// <param name="actor"></param> public abstract void RemoveAvatar(PhysicsActor actor); /// <summary> /// Remove a prim. /// </summary> /// <param name="prim"></param> public abstract void RemovePrim(PhysicsActor prim); public abstract PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, uint localid); public virtual PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapetype, uint localid) { return AddPrimShape(primName, pbs, position, size, rotation, isPhysical, localid); } public virtual float TimeDilation { get { return 1.0f; } } public virtual bool SupportsNINJAJoints { get { return false; } } public virtual PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position, Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation) { return null; } public virtual void RequestJointDeletion(string objectNameInScene) { return; } public virtual void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor) { return; } public virtual void DumpJointInfo() { return; } public event JointMoved OnJointMoved; protected virtual void DoJointMoved(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointMoved != null) { OnJointMoved(joint); } } public event JointDeactivated OnJointDeactivated; protected virtual void DoJointDeactivated(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointDeactivated != null) { OnJointDeactivated(joint); } } public event JointErrorMessage OnJointErrorMessage; protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointErrorMessage != null) { OnJointErrorMessage(joint, message); } } public virtual Vector3 GetJointAnchor(PhysicsJoint joint) { return Vector3.Zero; } public virtual Vector3 GetJointAxis(PhysicsJoint joint) { return Vector3.Zero; } public abstract void AddPhysicsActorTaint(PhysicsActor prim); /// <summary> /// Perform a simulation of the current physics scene over the given timestep. /// </summary> /// <param name="timeStep"></param> /// <returns>The number of frames simulated over that period.</returns> public abstract float Simulate(float timeStep); /// <summary> /// Get statistics about this scene. /// </summary> /// <remarks>This facility is currently experimental and subject to change.</remarks> /// <returns> /// A dictionary where the key is the statistic name. If no statistics are supplied then returns null. /// </returns> public virtual Dictionary<string, float> GetStats() { return null; } public abstract void GetResults(); public abstract void SetTerrain(float[] heightMap); public abstract void SetWaterLevel(float baseheight); public abstract void DeleteTerrain(); public abstract void Dispose(); public abstract Dictionary<uint, float> GetTopColliders(); public abstract bool IsThreaded { get; } /// <summary> /// True if the physics plugin supports raycasting against the physics scene /// </summary> public virtual bool SupportsRayCast() { return false; } public virtual bool SupportsCombining() { return false; } public virtual void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) {} public virtual void UnCombine(PhysicsScene pScene) {} /// <summary> /// Queue a raycast against the physics scene. /// The provided callback method will be called when the raycast is complete /// /// Many physics engines don't support collision testing at the same time as /// manipulating the physics scene, so we queue the request up and callback /// a custom method when the raycast is complete. /// This allows physics engines that give an immediate result to callback immediately /// and ones that don't, to callback when it gets a result back. /// /// ODE for example will not allow you to change the scene while collision testing or /// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene. /// /// This is named RayCastWorld to not conflict with modrex's Raycast method. /// </summary> /// <param name="position">Origin of the ray</param> /// <param name="direction">Direction of the ray</param> /// <param name="length">Length of ray in meters</param> /// <param name="retMethod">Method to call when the raycast is complete</param> public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod) { if (retMethod != null) retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero); } public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod) { if (retMethod != null) retMethod(new List<ContactResult>()); } public virtual List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count) { return new List<ContactResult>(); } public virtual object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter) { return null; } public virtual bool SupportsRaycastWorldFiltered() { return false; } // Extendable interface for new, physics engine specific operations public virtual object Extension(string pFunct, params object[] pParams) { // A NOP if the extension thing is not implemented by the physics engine return null; } } }
using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; namespace R4Mvc.Tools.Extensions { /// <summary> /// A collection of helper and fluent extension methods to help manipulate SyntaxNodes /// </summary> public static class SyntaxNodeHelpers { public static bool InheritsFrom<T>(this ITypeSymbol symbol) { var matchingTypeName = typeof(T).FullName; if (typeof(T).IsInterface) { return symbol.ToString() == matchingTypeName || symbol.AllInterfaces.Any(i => i.ToString() == matchingTypeName); } while (true) { if (symbol.TypeKind == TypeKind.Class && symbol.ToString() == matchingTypeName) { return true; } if (symbol.BaseType != null) { symbol = symbol.BaseType; continue; } break; } return false; } public static SyntaxToken[] CreateModifiers(params SyntaxKind[] kinds) { return kinds.Select(m => Token(TriviaList(), m, TriviaList(Space))).ToArray(); } public static bool IsNotR4MVCGenerated(this ISymbol method) { return !method.GetAttributes().Any(a => a.AttributeClass.InheritsFrom<GeneratedCodeAttribute>()); } public static bool IsNotR4MvcExcluded(this ISymbol method) { return !method.GetAttributes().Any(a => a.AttributeClass.InheritsFrom<R4MvcExcludeAttribute>() || a.AttributeClass.Name == "R4MvcExclude"); } private static string[] _controllerClassMethodNames = null; private static string[] _pageClassMethodNames = null; public static void PopulateControllerClassMethodNames(CSharpCompilation compilation) { var result = new List<string>(); var typeSymbol = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Mvc.Controller"); while (typeSymbol != null) { var methodNames = typeSymbol.GetMembers() .Where(r => r.Kind == SymbolKind.Method && r.DeclaredAccessibility == Accessibility.Public && r.IsVirtual) .Select(s => s.Name); result.AddRange(methodNames); typeSymbol = typeSymbol.BaseType; } _controllerClassMethodNames = result.Distinct().ToArray(); result = new List<string>(); typeSymbol = compilation.GetTypeByMetadataName("Microsoft.AspNetCore.Mvc.RazorPages.PageModel"); while (typeSymbol != null) { var methodNames = typeSymbol.GetMembers() .Where(r => r.Kind == SymbolKind.Method && r.DeclaredAccessibility == Accessibility.Public && r.IsVirtual) .Select(s => s.Name); result.AddRange(methodNames); typeSymbol = typeSymbol.BaseType; } _pageClassMethodNames = result.Distinct().ToArray(); } public static bool IsMvcAction(this IMethodSymbol method) { if (method.GetAttributes().Any(a => a.AttributeClass.InheritsFrom<NonActionAttribute>())) return false; if (_controllerClassMethodNames.Contains(method.Name)) return false; return true; } public static bool IsRazorPageAction(this IMethodSymbol method) { if (method.GetAttributes().Any(a => a.AttributeClass.InheritsFrom<NonActionAttribute>())) return false; if (_pageClassMethodNames.Contains(method.Name)) return false; if (!method.Name.StartsWith("On")) return false; return true; } public static IEnumerable<IMethodSymbol> GetPublicNonGeneratedControllerMethods(this ITypeSymbol controller) { return controller.GetMembers() .OfType<IMethodSymbol>() .Where(m => m.DeclaredAccessibility == Accessibility.Public && m.MethodKind == MethodKind.Ordinary) .Where(IsNotR4MVCGenerated) .Where(IsNotR4MvcExcluded) .Where(IsMvcAction); } public static IEnumerable<IMethodSymbol> GetPublicNonGeneratedPageMethods(this ITypeSymbol controller) { return controller.GetMembers() .OfType<IMethodSymbol>() .Where(m => m.DeclaredAccessibility == Accessibility.Public && m.MethodKind == MethodKind.Ordinary) .Where(IsNotR4MVCGenerated) .Where(IsNotR4MvcExcluded) .Where(IsRazorPageAction); } private static AttributeSyntax CreateGeneratedCodeAttribute() { var arguments = AttributeArgumentList( SeparatedList( new[] { AttributeArgument( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(Constants.ProjectName))), AttributeArgument( LiteralExpression(SyntaxKind.StringLiteralExpression, Literal(Constants.Version))) })); return Attribute(IdentifierName("GeneratedCode"), arguments); } public static AttributeListSyntax GeneratedNonUserCodeAttributeList() => AttributeList(SeparatedList(new[] { CreateGeneratedCodeAttribute(), Attribute(IdentifierName("DebuggerNonUserCode")) })); public static MethodDeclarationSyntax WithNonActionAttribute(this MethodDeclarationSyntax node) => node.AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("NonAction"))))); public static MethodDeclarationSyntax WithNonHandlerAttribute(this MethodDeclarationSyntax node) => node.AddAttributeLists(AttributeList(SingletonSeparatedList(Attribute(IdentifierName("NonHandler"))))); public static FieldDeclarationSyntax WithGeneratedAttribute(this FieldDeclarationSyntax node) => node.AddAttributeLists(AttributeList(SingletonSeparatedList(CreateGeneratedCodeAttribute()))); public static PropertyDeclarationSyntax WithGeneratedNonUserCodeAttribute(this PropertyDeclarationSyntax node) => node.AddAttributeLists(AttributeList(SeparatedList(new[] { CreateGeneratedCodeAttribute(), Attribute(IdentifierName("DebuggerNonUserCode")) }))); /// TODO: Can this use a aeparated list? public static ClassDeclarationSyntax WithModifiers(this ClassDeclarationSyntax node, params SyntaxKind[] modifiers) { return node.AddModifiers(CreateModifiers(modifiers)); } public static ConstructorDeclarationSyntax WithModifiers(this ConstructorDeclarationSyntax node, params SyntaxKind[] modifiers) { return node.AddModifiers(CreateModifiers(modifiers)); } public static MethodDeclarationSyntax WithModifiers(this MethodDeclarationSyntax node, params SyntaxKind[] modifiers) { return node.AddModifiers(CreateModifiers(modifiers)); } public static FieldDeclarationSyntax WithModifiers(this FieldDeclarationSyntax node, params SyntaxKind[] modifiers) { return node.AddModifiers(CreateModifiers(modifiers)); } public static PropertyDeclarationSyntax WithModifiers(this PropertyDeclarationSyntax node, params SyntaxKind[] modifiers) { if (modifiers.Length == 0) return node; return node.AddModifiers(CreateModifiers(modifiers)); } public static MemberAccessExpressionSyntax MemberAccess(string entityName, string memberName) { return MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName(entityName), IdentifierName(memberName)); } public static string GetRouteName(this IParameterSymbol property) { return property.GetAttributes() .Where(attr => attr.AttributeClass.InheritsFrom<BindAttribute>()) .SelectMany(attr => attr.NamedArguments.Where(arg => arg.Key == nameof(BindAttribute.Prefix))) .Select(arg => arg.Value.Value as string) .Where(prefix => !string.IsNullOrEmpty(prefix)) .DefaultIfEmpty(property.Name) .First(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; using ServiceStack.Common.Support; using ServiceStack.Logging; namespace ServiceStack.Common.Utils { public class ReflectionUtils { public static readonly ILog Log = LogManager.GetLogger(typeof(ReflectionUtils)); /// <summary> /// Populate an object with Example data. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static object PopulateObject(object obj) { if (obj == null) return null; return PopulateObjectInternal(obj, new Dictionary<Type, int>(20)); } /// <summary> /// Populates the object with example data. /// </summary> /// <param name="obj"></param> /// <param name="recursionInfo">Tracks how deeply nested we are</param> /// <returns></returns> private static object PopulateObjectInternal(object obj, Dictionary<Type,int> recursionInfo) { if (obj == null) return null; if (obj is string) return obj; // prevents it from dropping into the char[] Chars property. Sheesh var members = obj.GetType().GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (var info in members) { var fieldInfo = info as FieldInfo; var propertyInfo = info as PropertyInfo; if (fieldInfo != null || propertyInfo != null) { var memberType = fieldInfo != null ? fieldInfo.FieldType : propertyInfo.PropertyType; var value = CreateDefaultValue(memberType, recursionInfo); SetValue(fieldInfo, propertyInfo, obj, value); } } return obj; } private static readonly Dictionary<Type, object> DefaultValueTypes = new Dictionary<Type, object>(); public static object GetDefaultValue(Type type) { if (!type.IsValueType) return null; object defaultValue; lock (DefaultValueTypes) { if (!DefaultValueTypes.TryGetValue(type, out defaultValue)) { defaultValue = Activator.CreateInstance(type); DefaultValueTypes[type] = defaultValue; } } return defaultValue; } private static readonly Dictionary<string, AssignmentDefinition> AssignmentDefinitionCache = new Dictionary<string, AssignmentDefinition>(); public static AssignmentDefinition GetAssignmentDefinition(Type toType, Type fromType) { var cacheKey = toType.FullName + "<" + fromType.FullName; lock (AssignmentDefinitionCache) { AssignmentDefinition definition; if (AssignmentDefinitionCache.TryGetValue(cacheKey, out definition)) { return definition; } definition = new AssignmentDefinition { ToType = toType, FromType = fromType, }; var members = fromType.GetMembers(BindingFlags.Public | BindingFlags.Instance); foreach (var info in members) { var fromPropertyInfo = info as PropertyInfo; if (fromPropertyInfo != null) { var toPropertyInfo = GetPropertyInfo(toType, fromPropertyInfo.Name); if (toPropertyInfo == null) continue; if (!fromPropertyInfo.CanRead) continue; if (!toPropertyInfo.CanWrite) continue; definition.AddMatch(fromPropertyInfo, toPropertyInfo); } var fromFieldInfo = info as FieldInfo; if (fromFieldInfo != null) { var toFieldInfo = GetFieldInfo(toType, fromFieldInfo.Name); if (toFieldInfo == null) continue; definition.AddMatch(fromFieldInfo, toFieldInfo); } } AssignmentDefinitionCache[cacheKey] = definition; return definition; } } public static To PopulateObject<To, From>(To to, From from) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.Populate(to, from); return to; } public static To PopulateWithNonDefaultValues<To, From>(To to, From from) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.PopulateWithNonDefaultValues(to, from); return to; } public static To PopulateFromPropertiesWithAttribute<To, From>(To to, From from, Type attributeType) { if (Equals(to, default(To)) || Equals(from, default(From))) return default(To); var assignmentDefinition = GetAssignmentDefinition(to.GetType(), from.GetType()); assignmentDefinition.PopulateFromPropertiesWithAttribute(to, from, attributeType); return to; } public static void SetProperty(object obj, PropertyInfo propertyInfo, object value) { if (!propertyInfo.CanWrite) { Log.WarnFormat("Attempted to set read only property '{0}'", propertyInfo.Name); return; } var propertySetMetodInfo = propertyInfo.GetSetMethod(); if (propertySetMetodInfo != null) { propertySetMetodInfo.Invoke(obj, new[] { value }); } } public static object GetProperty(object obj, PropertyInfo propertyInfo) { if (propertyInfo == null || !propertyInfo.CanRead) return null; var getMethod = propertyInfo.GetGetMethod(); return getMethod != null ? getMethod.Invoke(obj, new object[0]) : null; } public static void SetValue(FieldInfo fieldInfo, PropertyInfo propertyInfo, object obj, object value) { try { if (IsUnsettableValue(fieldInfo, propertyInfo)) return; if (fieldInfo != null && !fieldInfo.IsLiteral) { fieldInfo.SetValue(obj, value); } else { SetProperty(obj, propertyInfo, value); } } catch (Exception ex) { var name = (fieldInfo != null) ? fieldInfo.Name : propertyInfo.Name; Log.DebugFormat("Could not set member: {0}. Error: {1}", name, ex.Message); } } public static bool IsUnsettableValue(FieldInfo fieldInfo, PropertyInfo propertyInfo) { if (propertyInfo != null && propertyInfo.ReflectedType != null) { // Properties on non-user defined classes should not be set // Currently we define those properties as properties declared on // types defined in mscorlib if (propertyInfo.DeclaringType.Assembly == typeof(object).Assembly) { return true; } } return false; } public static object[] CreateDefaultValues(IEnumerable<Type> types, Dictionary<Type, int> recursionInfo) { var values = new List<object>(); foreach (var type in types) { values.Add(CreateDefaultValue(type, recursionInfo)); } return values.ToArray(); } private const int MaxRecursionLevelForDefaultValues = 2; // do not nest a single type more than this deep. public static object CreateDefaultValue(Type type, Dictionary<Type, int> recursionInfo) { if (type == typeof(string)) { return type.Name; } if (type.IsEnum) { return Enum.GetValues(type).GetValue(0); } // If we have hit our recursion limit for this type, then return null int recurseLevel; // will get set to 0 if TryGetValue() fails recursionInfo.TryGetValue(type, out recurseLevel); if (recurseLevel > MaxRecursionLevelForDefaultValues) return null; recursionInfo[type] = recurseLevel + 1; // increase recursion level for this type try // use a try/finally block to make sure we decrease the recursion level for this type no matter which code path we take, { //when using KeyValuePair<TKey, TValue>, TKey must be non-default to stuff in a Dictionary if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>)) { var genericTypes = type.GetGenericArguments(); var valueType = Activator.CreateInstance(type, CreateDefaultValue(genericTypes[0], recursionInfo), CreateDefaultValue(genericTypes[1], recursionInfo)); return PopulateObjectInternal(valueType, recursionInfo); } if (type.IsValueType) { return Activator.CreateInstance(type); } if (type.IsArray) { return PopulateArray(type, recursionInfo); } var constructorInfo = type.GetConstructor(Type.EmptyTypes); var hasEmptyConstructor = constructorInfo != null; if (hasEmptyConstructor) { var value = constructorInfo.Invoke(new object[0]); Type[] interfaces = type.FindInterfaces((t, critera) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(ICollection<>) , null); bool isGenericCollection = interfaces.Length > 0; if (isGenericCollection) { SetGenericCollection(interfaces[0], value, recursionInfo); } //when the object might have nested properties such as enums with non-0 values, etc return PopulateObjectInternal(value, recursionInfo); } return null; } finally { recursionInfo[type] = recurseLevel; } } public static void SetGenericCollection(Type realisedListType, object genericObj, Dictionary<Type, int> recursionInfo) { var args = realisedListType.GetGenericArguments(); if (args.Length != 1) { Log.ErrorFormat("Found a generic list that does not take one generic argument: {0}", realisedListType); return; } var methodInfo = realisedListType.GetMethod("Add"); if (methodInfo != null) { var argValues = CreateDefaultValues(args, recursionInfo); methodInfo.Invoke(genericObj, argValues); } } public static Array PopulateArray(Type type, Dictionary<Type, int> recursionInfo) { var elementType = type.GetElementType(); var objArray = Array.CreateInstance(elementType, 1); var objElementType = CreateDefaultValue(elementType, recursionInfo); objArray.SetValue(objElementType, 0); return objArray; } //TODO: replace with InAssignableFrom public static bool CanCast(Type toType, Type fromType) { if (toType.IsInterface) { var interfaceList = fromType.GetInterfaces().ToList(); if (interfaceList.Contains(toType)) return true; } else { Type baseType = fromType; bool areSameTypes; do { areSameTypes = baseType == toType; } while (!areSameTypes && (baseType = fromType.BaseType) != null); if (areSameTypes) return true; } return false; } public static MemberInfo GetMemberInfo(Type fromType, string memberName) { var baseType = fromType; do { var members = baseType.GetMembers(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var memberInfo in members) { if (memberInfo.Name == memberName) return memberInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static FieldInfo GetFieldInfo(Type fromType, string fieldName) { var baseType = fromType; do { var fieldInfos = baseType.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var fieldInfo in fieldInfos) { if (fieldInfo.Name == fieldName) return fieldInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static PropertyInfo GetPropertyInfo(Type fromType, string propertyName) { var baseType = fromType; do { var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var propertyInfo in propertyInfos) { if (propertyInfo.Name == propertyName) return propertyInfo; } } while ((baseType = baseType.BaseType) != null); return null; } public static IEnumerable<KeyValuePair<PropertyInfo, T>> GetPropertyAttributes<T>(Type fromType) where T : Attribute { var attributeType = typeof(T); var baseType = fromType; do { var propertyInfos = baseType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); foreach (var propertyInfo in propertyInfos) { var attributes = propertyInfo.GetCustomAttributes(attributeType, true); foreach (T attribute in attributes) { yield return new KeyValuePair<PropertyInfo, T>(propertyInfo, attribute); } } } while ((baseType = baseType.BaseType) != null); } public static object CreateInstance(Type type) { return Text.ReflectionExtensions.CreateInstance(type); } } }
using System; using System.Collections.Generic; using Loon.Core.Event; using Loon.Core.Graphics.Opengl; using Loon.Utils.Collection; using Loon.Action.Sprite.Effect; using Loon.Utils; using Loon.Core; using Loon.Core.Geom; using Loon.Java; using Loon.Action.Sprite; namespace Loon.Action.Avg { public class AVGCG { public sealed class _Updateable : Updateable { private readonly AVGChara c; public _Updateable(AVGChara c) { this.c = c; } public void Action() { c.Dispose(); } } private long charaShowDelay = 60; private LTexture background; private ArrayMap charas; private bool style, loop; internal int sleep, sleepMax, shakeNumber; public AVGCG() { this.charas = new ArrayMap(10); this.style = true; this.loop = true; } public LTexture getBackgroundCG() { return background; } public void NoneBackgroundCG() { if (background != null) { background.Destroy(); background = null; } } public void SetBackgroundCG(LTexture backgroundCG) { if (backgroundCG == this.background) { return; } if (background != null) { background.Destroy(); background = null; } this.background = backgroundCG; } private static string _Update(string n) { string name = n; if (StringUtils.StartsWith(name,'"')) { name = name.Replace("\"", ""); } return name; } public void SetBackgroundCG(string resName) { this.SetBackgroundCG(new LTexture(_Update(resName))); } public void Add(string resName, AVGChara chara) { if (chara == null) { return; } string path = _Update(resName); lock (charas) { chara.SetFlag(ISprite_Constants.TYPE_FADE_OUT, charaShowDelay); this.charas.Put(path.Replace(" ", "").ToLower(), chara); } } public void Add(string resName, int x, int y) { Add(resName, x, y, LSystem.screenRect.width, LSystem.screenRect.height); } public void Add(string resName, int x, int y, int w, int h) { string path = _Update(resName); lock (charas) { string keyName = path.Replace(" ", "").ToLower(); AVGChara chara = (AVGChara)charas.Get(keyName); if (chara == null) { chara = new AVGChara(path, x, y, w, h); chara.SetFlag(ISprite_Constants.TYPE_FADE_OUT, charaShowDelay); charas.Put(keyName, chara); } else { chara.SetFlag(ISprite_Constants.TYPE_FADE_OUT, charaShowDelay); chara.SetX(x); chara.SetY(y); } } } public AVGChara Remove(string resName) { string path = _Update(resName); lock (charas) { string name = path.Replace(" ", "").ToLower(); AVGChara chara = null; if (style) { chara = (AVGChara)charas.Get(name); if (chara != null) { chara.SetFlag(ISprite_Constants.TYPE_FADE_IN, charaShowDelay); } } else { chara = (AVGChara)charas.Remove(name); if (chara != null) { XNA_dispose(chara); } } return chara; } } public void Replace(string res1, string res2) { string path1 = _Update(res1); string path2 = _Update(res2); lock (charas) { string name = path1.Replace(" ", "").ToLower(); AVGChara old = null; if (style) { old = (AVGChara)charas.Get(name); if (old != null) { old.SetFlag(ISprite_Constants.TYPE_FADE_IN, charaShowDelay); } } else { old = (AVGChara)charas.Remove(name); if (old != null) { XNA_dispose(old); } } if (old != null) { int x = old.GetX(); int y = old.GetY(); AVGChara newObject = new AVGChara(path2, 0, 0, old.maxWidth, old.maxHeight); newObject.SetMove(false); newObject.SetX(x); newObject.SetY(y); Add(path2, newObject); } } } private static void XNA_dispose(AVGChara c) { Updateable remove = new _Updateable(c); LSystem.Load(remove); } public void Paint(GLEx g) { if (background != null) { if (shakeNumber > 0) { g.DrawTexture(background, shakeNumber / 2 - LSystem.random.Next(shakeNumber), shakeNumber / 2 - LSystem.random.Next(shakeNumber)); } else { g.DrawTexture(background, 0, 0); } } lock (charas) { for (int i = 0; i < charas.Size(); i++) { AVGChara chara = (AVGChara)charas.Get(i); if (chara == null || !chara.isVisible) { continue; } if (style) { if (chara.flag != -1) { if (chara.flag == ISprite_Constants.TYPE_FADE_IN) { chara.currentFrame--; if (chara.currentFrame == 0) { chara.opacity = 0; chara.flag = -1; chara.Dispose(); charas.Remove(chara); } } else { chara.currentFrame++; if (chara.currentFrame == chara.time) { chara.opacity = 0; chara.flag = -1; } } chara.opacity = (chara.currentFrame / chara.time) * 255; if (chara.opacity > 0) { g.SetAlpha(chara.opacity / 255); } } } if (chara.isAnimation) { AVGAnm animation = chara.anm; if (animation.load) { if (animation.loop && animation.startTime == -1) { animation.Start(0, loop); } Point.Point2i point = animation.GetPos(JavaRuntime .CurrentTimeMillis()); if (animation.alpha != 1f) { g.SetAlpha(animation.alpha); } g.DrawTexture(animation.texture, chara.x, chara.y, animation.width, animation.height, point.x, point.y, point.x + animation.imageWidth, point.y + animation.imageHeight, animation.angle, animation.color); if (animation.alpha != 1f) { g.SetAlpha(1f); } } } else { chara.Next(); chara.draw(g); } if (style) { if (chara.flag != -1 && chara.opacity > 0) { g.SetAlpha(1f); } } } } } public void Clear() { lock (charas) { charas.Clear(); } } public ArrayMap getCharas() { return charas; } public int Count() { if (charas != null) { return charas.Size(); } return 0; } public long GetCharaShowDelay() { return charaShowDelay; } public void SetCharaShowDelay(long charaShowDelay) { this.charaShowDelay = charaShowDelay; } public bool IsStyle() { return style; } public void SetStyle(bool style) { this.style = style; } public bool IsLoop() { return loop; } public void SetLoop(bool loop) { this.loop = loop; } public void Dispose() { lock (charas) { if (style) { for (int i = 0; i < charas.Size(); i++) { AVGChara ch = (AVGChara)charas.Get(i); if (ch != null) { ch.SetFlag(ISprite_Constants.TYPE_FADE_IN, charaShowDelay); } } } else { for (int i = 0; i < charas.Size(); i++) { AVGChara ch = (AVGChara)charas.Get(i); if (ch != null) { ch.Dispose(); ch = null; } } charas.Clear(); } } } } }
// 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, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.InteractiveWindow; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Repl; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods; using Microsoft.VisualStudioTools; using IServiceProvider = System.IServiceProvider; using Task = System.Threading.Tasks.Task; namespace Microsoft.PythonTools.Commands { /// <summary> /// Provides the command to send selected text from a buffer to the remote REPL window. /// /// The command supports either sending a selection or sending line-by-line. In line-by-line /// mode the user should be able to just hold down on Alt-Enter and have an entire script /// execute as if they ran it in the interactive window. Focus will continue to remain in /// the active text view. /// /// In selection mode the users selection is executed and focus is transfered to the interactive /// window and their selection remains unchanged. /// </summary> class SendToReplCommand : Command { protected readonly IServiceProvider _serviceProvider; private static string[] _newLineChars = new[] { "\r\n", "\n", "\r" }; private static object _executedLastLine = new object(); public SendToReplCommand(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override async void DoCommand(object sender, EventArgs args) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); var project = activeView.GetProjectAtCaret(_serviceProvider); var analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider); ITextSelection selection = activeView.Selection; ITextSnapshot snapshot = activeView.TextBuffer.CurrentSnapshot; var repl = ExecuteInReplCommand.EnsureReplWindow(_serviceProvider, analyzer, project); string input; bool focusRepl = false, alwaysSubmit = false; if (selection.StreamSelectionSpan.Length > 0) { // Easy, just send the selection to the interactive window. input = activeView.Selection.StreamSelectionSpan.GetText(); if (!input.EndsWith("\n") && !input.EndsWith("\r")) { input += activeView.Options.GetNewLineCharacter(); } focusRepl = true; } else if (!activeView.Properties.ContainsProperty(_executedLastLine)) { // No selection, and we haven't hit the end of the file in line-by-line mode. // Send the current line, and then move the caret to the next non-blank line. ITextSnapshotLine targetLine = snapshot.GetLineFromPosition(selection.Start.Position); var targetSpan = targetLine.Extent; // If the line is inside a code cell, expand the target span to // contain the entire cell. var cellStart = CodeCellAnalysis.FindStartOfCell(targetLine); if (cellStart != null) { var cellEnd = CodeCellAnalysis.FindEndOfCell(cellStart, targetLine); targetSpan = new SnapshotSpan(cellStart.Start, cellEnd.End); targetLine = CodeCellAnalysis.FindEndOfCell(cellEnd, targetLine, includeWhitespace: true); alwaysSubmit = true; } input = targetSpan.GetText(); bool moved = false; while (targetLine.LineNumber < snapshot.LineCount - 1) { targetLine = snapshot.GetLineFromLineNumber(targetLine.LineNumber + 1); // skip over blank lines, unless it's the last line, in which case we want to land on it no matter what if (!string.IsNullOrWhiteSpace(targetLine.GetText()) || targetLine.LineNumber == snapshot.LineCount - 1) { activeView.Caret.MoveTo(new SnapshotPoint(snapshot, targetLine.Start)); activeView.Caret.EnsureVisible(); moved = true; break; } } if (!moved) { // There's no where for the caret to go, don't execute the line if // we've already executed it. activeView.Caret.PositionChanged += Caret_PositionChanged; activeView.Properties[_executedLastLine] = _executedLastLine; } } else if ((repl.InteractiveWindow.CurrentLanguageBuffer?.CurrentSnapshot.Length ?? 0) != 0) { // We reached the end of the file but have some text buffered. Execute it now. input = activeView.Options.GetNewLineCharacter(); } else { // We've hit the end of the current text view and executed everything input = null; } if (input != null) { repl.Show(focusRepl); var inputs = repl.InteractiveWindow.Properties.GetOrCreateSingletonProperty( () => new InteractiveInputs(repl.InteractiveWindow, _serviceProvider, alwaysSubmit) ); await inputs.EnqueueAsync(input); } // Take focus back if REPL window has stolen it and we're in line-by-line mode. if (!focusRepl && !activeView.HasAggregateFocus) { var adapterService = _serviceProvider.GetComponentModel().GetService<VisualStudio.Editor.IVsEditorAdaptersFactoryService>(); var tv = adapterService.GetViewAdapter(activeView); tv.SendExplicitFocus(); } } private static void Caret_PositionChanged(object sender, CaretPositionChangedEventArgs e) { e.TextView.Properties.RemoveProperty(_executedLastLine); e.TextView.Caret.PositionChanged -= Caret_PositionChanged; } private bool IsRealInterpreter(IPythonInterpreterFactory factory) { if (factory == null) { return false; } var interpreterService = _serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>(); return interpreterService != null && interpreterService.NoInterpretersValue != factory; } public override int? EditFilterQueryStatus(ref VisualStudio.OLE.Interop.OLECMD cmd, IntPtr pCmdText) { var activeView = CommonPackage.GetActiveTextView(_serviceProvider); var empty = activeView.Selection.IsEmpty; Intellisense.VsProjectAnalyzer analyzer; if (activeView != null && (analyzer = activeView.GetAnalyzerAtCaret(_serviceProvider)) != null) { if (activeView.Selection.Mode == TextSelectionMode.Box || analyzer == null || !IsRealInterpreter(analyzer.InterpreterFactory)) { cmd.cmdf = (uint)(OLECMDF.OLECMDF_SUPPORTED); } else { cmd.cmdf = (uint)(OLECMDF.OLECMDF_ENABLED | OLECMDF.OLECMDF_SUPPORTED); } } else { cmd.cmdf = (uint)(OLECMDF.OLECMDF_INVISIBLE); } return VSConstants.S_OK; } public override EventHandler BeforeQueryStatus { get { return (sender, args) => { ((OleMenuCommand)sender).Visible = false; ((OleMenuCommand)sender).Supported = false; }; } } public override int CommandId { get { return (int)PkgCmdIDList.cmdidSendToRepl; } } class InteractiveInputs { private readonly LinkedList<string> _pendingInputs = new LinkedList<string>(); private readonly IServiceProvider _serviceProvider; private readonly IInteractiveWindow _window; private readonly bool _submitAtEnd; public InteractiveInputs(IInteractiveWindow window, IServiceProvider serviceProvider, bool submitAtEnd) { _window = window; _serviceProvider = serviceProvider; _window.ReadyForInput += () => ProcessQueuedInputAsync().DoNotWait(); _submitAtEnd = submitAtEnd; } public async Task EnqueueAsync(string input) { _pendingInputs.AddLast(input); if (!_window.IsRunning) { await ProcessQueuedInputAsync(); } } /// <summary> /// Pends the next input line to the current input buffer, optionally executing it /// if it forms a complete statement. /// </summary> private async Task ProcessQueuedInputAsync() { var textView = _window.TextView; var eval = _window.GetPythonEvaluator(); bool supportsMultipleStatements = false; if (eval != null) { supportsMultipleStatements = await eval.GetSupportsMultipleStatementsAsync(); } // Process all of our pending inputs until we get a complete statement while (_pendingInputs.First != null) { string current = _pendingInputs.First.Value; _pendingInputs.RemoveFirst(); MoveCaretToEndOfCurrentInput(); var statements = RecombineInput( current, _window.CurrentLanguageBuffer?.CurrentSnapshot.GetText(), supportsMultipleStatements, textView.GetLanguageVersion(_serviceProvider), textView.Options.GetNewLineCharacter() ); if (statements.Count > 0) { // If there was more than one statement then save those for execution later... var input = statements[0]; for (int i = statements.Count - 1; i > 0; i--) { _pendingInputs.AddFirst(statements[i]); } _window.InsertCode(input); string fullCode = _window.CurrentLanguageBuffer.CurrentSnapshot.GetText(); if (_window.Evaluator.CanExecuteCode(fullCode)) { // the code is complete, execute it now _window.Operations.ExecuteInput(); return; } _window.InsertCode(textView.Options.GetNewLineCharacter()); if (_submitAtEnd && _pendingInputs.First == null) { _window.Operations.ExecuteInput(); } } } } /// <summary> /// Takes the new input and appends it to any existing input that's been entered so far. The combined /// input is then split into multiple top-level statements that will be executed one-by-one. /// /// Also handles any dedents necessary to make the input a valid input, which usually would only /// apply if we have no input so far. /// </summary> private static List<string> RecombineInput( string input, string pendingInput, bool supportsMultipleStatements, PythonLanguageVersion version, string newLineCharacter ) { // Combine the current input text with the newly submitted text. This will prevent us // from dedenting code when doing line-by-line submissions of things like: // if True: // x = 1 // // So that we don't dedent "x = 1" when we submit it by its self. var combinedText = (pendingInput ?? string.Empty) + input; var oldLineCount = string.IsNullOrEmpty(pendingInput) ? 0 : pendingInput.Split(_newLineChars, StringSplitOptions.None).Length - 1; // The split and join will not alter the number of lines that are fed in and returned but // may change the text by dedenting it if we hadn't submitted the "if True:" in the // code above. var split = ReplEditFilter.SplitAndDedent(combinedText); IEnumerable<string> joinedLines; if (!supportsMultipleStatements) { joinedLines = ReplEditFilter.JoinToCompleteStatements(split, version, false); } else { joinedLines = new[] { string.Join(newLineCharacter, split) }; } // Remove any of the lines that were previously inputted into the buffer and also // remove any extra newlines in the submission. List<string> res = new List<string>(); foreach (var inputLine in joinedLines) { var actualLines = inputLine.Split(_newLineChars, StringSplitOptions.None); var newLine = ReplEditFilter.FixEndingNewLine( string.Join(newLineCharacter, actualLines.Skip(oldLineCount)) ); res.Add(newLine); oldLineCount -= actualLines.Count(); if (oldLineCount < 0) { oldLineCount = 0; } } return res; } private void MoveCaretToEndOfCurrentInput() { var textView = _window.TextView; var curLangBuffer = _window.CurrentLanguageBuffer; // Sending to the interactive window is like appending the input to the end, we don't // respect the current caret position or selection. We use InsertCode which uses the // current caret position, so first we need to ensure the caret is in the input buffer, // otherwise inserting code does nothing. SnapshotPoint? viewPoint = textView.BufferGraph.MapUpToBuffer( new SnapshotPoint(curLangBuffer.CurrentSnapshot, curLangBuffer.CurrentSnapshot.Length), PointTrackingMode.Positive, PositionAffinity.Successor, textView.TextBuffer ); if (!viewPoint.HasValue) { // Unable to map language buffer to view. // Try moving caret to the end of the view then. viewPoint = new SnapshotPoint( textView.TextBuffer.CurrentSnapshot, textView.TextBuffer.CurrentSnapshot.Length ); } textView.Caret.MoveTo(viewPoint.Value); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using log4net; using Microsoft.Isam.Esent.Interop; using Rhino.Queues.Model; using Rhino.Queues.Protocol; namespace Rhino.Queues.Storage { public class SenderActions : AbstractActions { private readonly ILog logger = LogManager.GetLogger(typeof (SenderActions)); public SenderActions(JET_INSTANCE instance, ColumnsInformation columnsInformation, string database, Guid instanceId) : base(instance, columnsInformation, database, instanceId) { } public IList<PersistentMessage> GetMessagesToSendAndMarkThemAsInFlight(int maxNumberOfMessage, int maxSizeOfMessagesInTotal, out Endpoint endPoint) { Api.MoveBeforeFirst(session, outgoing); endPoint = null; string queue = null; var messages = new List<PersistentMessage>(); while (Api.TryMoveNext(session, outgoing)) { var msgId = new Guid(Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"])); var value = (OutgoingMessageStatus)Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"]).Value; var timeAsDate = Api.RetrieveColumnAsDouble(session, outgoing, ColumnsInformation.OutgoingColumns["time_to_send"]).Value; var time = DateTime.FromOADate(timeAsDate); logger.DebugFormat("Scanning message {0} with status {1} to be sent at {2}", msgId, value, time); if (value != OutgoingMessageStatus.Ready) continue; if (time > DateTime.Now) continue; var rowEndpoint = new Endpoint( Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["address"]), Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["port"]).Value ); if (endPoint == null) endPoint = rowEndpoint; if (endPoint.Equals(rowEndpoint) == false) continue; var rowQueue = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["queue"], Encoding.Unicode); if (queue == null) queue = rowQueue; if(queue != rowQueue) continue; logger.DebugFormat("Adding message {0} to returned messages", msgId); var bookmark = new MessageBookmark(); Api.JetGetBookmark(session, outgoing, bookmark.Bookmark, bookmark.Size, out bookmark.Size); var headerAsQueryString = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["headers"],Encoding.Unicode); messages.Add(new PersistentMessage { Id = new MessageId { SourceInstanceId = instanceId, MessageIdentifier = msgId }, Headers = HttpUtility.ParseQueryString(headerAsQueryString), Queue = rowQueue, SubQueue = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["subqueue"], Encoding.Unicode), SentAt = DateTime.FromOADate(Api.RetrieveColumnAsDouble(session, outgoing, ColumnsInformation.OutgoingColumns["sent_at"]).Value), Data = Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["data"]), Bookmark = bookmark }); using (var update = new Update(session, outgoing, JET_prep.Replace)) { Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.InFlight); update.Save(); } logger.DebugFormat("Marking output message {0} as InFlight", msgId); if (maxNumberOfMessage < messages.Count) break; if (maxSizeOfMessagesInTotal < messages.Sum(x => x.Data.Length)) break; } return messages; } public void MarkOutgoingMessageAsFailedTransmission(MessageBookmark bookmark, bool queueDoesNotExistsInDestination) { Api.JetGotoBookmark(session, outgoing, bookmark.Bookmark, bookmark.Size); var numOfRetries = Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["number_of_retries"]).Value; var msgId = Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"]).Value; if (numOfRetries < 100 && queueDoesNotExistsInDestination == false) { using (var update = new Update(session, outgoing, JET_prep.Replace)) { var timeToSend = DateTime.Now.AddSeconds(numOfRetries * numOfRetries); Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.Ready); Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["time_to_send"], timeToSend.ToOADate()); Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["number_of_retries"], numOfRetries + 1); logger.DebugFormat("Marking outgoing message {0} as failed with retries: {1}", msgId, numOfRetries); update.Save(); } } else { using (var update = new Update(session, outgoingHistory, JET_prep.Insert)) { foreach (var column in ColumnsInformation.OutgoingColumns.Keys) { Api.SetColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns[column], Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns[column]) ); } Api.SetColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["send_status"], (int)OutgoingMessageStatus.Failed); logger.DebugFormat("Marking outgoing message {0} as permenantly failed after {1} retries", msgId, numOfRetries); update.Save(); } Api.JetDelete(session, outgoing); } } public MessageBookmark MarkOutgoingMessageAsSuccessfullySent(MessageBookmark bookmark) { Api.JetGotoBookmark(session, outgoing, bookmark.Bookmark, bookmark.Size); var newBookmark = new MessageBookmark(); using (var update = new Update(session, outgoingHistory, JET_prep.Insert)) { foreach (var column in ColumnsInformation.OutgoingColumns.Keys) { var bytes = Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns[column]); Api.SetColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns[column], bytes); } Api.SetColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["send_status"], (int)OutgoingMessageStatus.Sent); update.Save(newBookmark.Bookmark, newBookmark.Size, out newBookmark.Size); } var msgId = Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"]).Value; Api.JetDelete(session, outgoing); logger.DebugFormat("Successfully sent output message {0}", msgId); return newBookmark; } public bool HasMessagesToSend() { Api.MoveBeforeFirst(session, outgoing); return Api.TryMoveNext(session, outgoing); } public IEnumerable<PersistentMessageToSend> GetMessagesToSend() { Api.MoveBeforeFirst(session, outgoing); while (Api.TryMoveNext(session, outgoing)) { var address = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["address"]); var port = Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["port"]).Value; var bookmark = new MessageBookmark(); Api.JetGetBookmark(session, outgoing, bookmark.Bookmark, bookmark.Size, out bookmark.Size); yield return new PersistentMessageToSend { Id = new MessageId { SourceInstanceId = instanceId, MessageIdentifier = new Guid(Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"])) }, OutgoingStatus = (OutgoingMessageStatus)Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"]).Value, Endpoint = new Endpoint(address, port), Queue = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["queue"], Encoding.Unicode), SubQueue = Api.RetrieveColumnAsString(session, outgoing, ColumnsInformation.OutgoingColumns["subqueue"], Encoding.Unicode), SentAt = DateTime.FromOADate(Api.RetrieveColumnAsDouble(session, outgoing, ColumnsInformation.OutgoingColumns["sent_at"]).Value), Data = Api.RetrieveColumn(session, outgoing, ColumnsInformation.OutgoingColumns["data"]), Bookmark = bookmark }; } } public void RevertBackToSend(MessageBookmark[] bookmarks) { foreach (var bookmark in bookmarks) { Api.JetGotoBookmark(session, outgoingHistory, bookmark.Bookmark, bookmark.Size); var msgId = Api.RetrieveColumnAsInt32(session, outgoing, ColumnsInformation.OutgoingColumns["msg_id"]).Value; using(var update = new Update(session, outgoing, JET_prep.Insert)) { foreach (var column in ColumnsInformation.OutgoingColumns.Keys) { Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns[column], Api.RetrieveColumn(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns[column]) ); } Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["send_status"], (int)OutgoingMessageStatus.Ready); Api.SetColumn(session, outgoing, ColumnsInformation.OutgoingColumns["number_of_retries"], Api.RetrieveColumnAsInt32(session, outgoingHistory, ColumnsInformation.OutgoingHistoryColumns["number_of_retries"]).Value + 1 ); logger.DebugFormat("Reverting output message {0} back to Ready mode", msgId); update.Save(); } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Net.NetworkInformation; using System.Threading; using System.Text; namespace WifiLib { /// <summary> /// Represents a client to the Zeroconf (Native Wifi) service. /// </summary> /// <remarks> /// This class is the entrypoint to Native Wifi management. To manage WiFi settings, create an instance /// of this class. /// </remarks> public class WlanClient : IDisposable { /// <summary> /// Represents a Wifi network interface. /// </summary> public class WlanInterface { private readonly WlanClient client; private Wlan.WlanInterfaceInfo info; #region Events /// <summary> /// Represents a method that will handle <see cref="WlanNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> public delegate void WlanNotificationEventHandler(Wlan.WlanNotificationData notifyData); /// <summary> /// Represents a method that will handle <see cref="WlanConnectionNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="connNotifyData">The notification data.</param> public delegate void WlanConnectionNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData); /// <summary> /// Represents a method that will handle <see cref="WlanReasonNotification"/> events. /// </summary> /// <param name="notifyData">The notification data.</param> /// <param name="reasonCode">The reason code.</param> public delegate void WlanReasonNotificationEventHandler(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode); /// <summary> /// Occurs when an event of any kind occurs on a WLAN interface. /// </summary> public event WlanNotificationEventHandler WlanNotification; /// <summary> /// Occurs when a WLAN interface changes connection state. /// </summary> public event WlanConnectionNotificationEventHandler WlanConnectionNotification; /// <summary> /// Occurs when a WLAN operation fails due to some reason. /// </summary> public event WlanReasonNotificationEventHandler WlanReasonNotification; #endregion #region Event queue private bool queueEvents; private readonly AutoResetEvent eventQueueFilled = new AutoResetEvent(false); private readonly Queue<object> eventQueue = new Queue<object>(); private struct WlanConnectionNotificationEventData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanConnectionNotificationData connNotifyData; } private struct WlanReasonNotificationData { public Wlan.WlanNotificationData notifyData; public Wlan.WlanReasonCode reasonCode; } #endregion internal WlanInterface(WlanClient client, Wlan.WlanInterfaceInfo info) { this.client = client; this.info = info; } /// <summary> /// Sets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <param name="value">The value to set.</param> private void SetInterfaceInt(Wlan.WlanIntfOpcode opCode, int value) { IntPtr valuePtr = Marshal.AllocHGlobal(sizeof(int)); Marshal.WriteInt32(valuePtr, value); try { Wlan.ThrowIfError( Wlan.WlanSetInterface(client.clientHandle, info.interfaceGuid, opCode, sizeof(int), valuePtr, IntPtr.Zero)); } finally { Marshal.FreeHGlobal(valuePtr); } } /// <summary> /// Gets a parameter of the interface whose data type is <see cref="int"/>. /// </summary> /// <param name="opCode">The opcode of the parameter.</param> /// <returns>The integer value.</returns> private int GetInterfaceInt(Wlan.WlanIntfOpcode opCode) { IntPtr valuePtr; int valueSize; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, opCode, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return Marshal.ReadInt32(valuePtr); } finally { Wlan.WlanFreeMemory(valuePtr); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="WlanInterface"/> is automatically configured. /// </summary> /// <value><c>true</c> if "autoconf" is enabled; otherwise, <c>false</c>.</value> public bool Autoconf { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled) != 0; } set { SetInterfaceInt(Wlan.WlanIntfOpcode.AutoconfEnabled, value ? 1 : 0); } } /// <summary> /// Gets or sets the BSS type for the indicated interface. /// </summary> /// <value>The type of the BSS.</value> public Wlan.Dot11BssType BssType { get { return (Wlan.Dot11BssType) GetInterfaceInt(Wlan.WlanIntfOpcode.BssType); } set { SetInterfaceInt(Wlan.WlanIntfOpcode.BssType, (int)value); } } /// <summary> /// Gets the state of the interface. /// </summary> /// <value>The state of the interface.</value> public Wlan.WlanInterfaceState InterfaceState { get { return (Wlan.WlanInterfaceState)GetInterfaceInt(Wlan.WlanIntfOpcode.InterfaceState); } } /// <summary> /// Gets the channel. /// </summary> /// <value>The channel.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int Channel { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.ChannelNumber); } } /// <summary> /// Gets the RSSI. /// </summary> /// <value>The RSSI.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public int RSSI { get { return GetInterfaceInt(Wlan.WlanIntfOpcode.RSSI); } } /// <summary> /// Gets the radio state. /// </summary> /// <value>The radio state.</value> /// <remarks>Not supported on Windows XP.</remarks> public Wlan.WlanRadioState RadioState { get { int valueSize; IntPtr valuePtr; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.RadioState, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return (Wlan.WlanRadioState)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanRadioState)); } finally { Wlan.WlanFreeMemory(valuePtr); } } } /// <summary> /// Gets the current operation mode. /// </summary> /// <value>The current operation mode.</value> /// <remarks>Not supported on Windows XP SP2.</remarks> public Wlan.Dot11OperationMode CurrentOperationMode { get { return (Wlan.Dot11OperationMode) GetInterfaceInt(Wlan.WlanIntfOpcode.CurrentOperationMode); } } /// <summary> /// Gets the attributes of the current connection. /// </summary> /// <value>The current connection attributes.</value> /// <exception cref="Win32Exception">An exception with code 0x0000139F (The group or resource is not in the correct state to perform the requested operation.) will be thrown if the interface is not connected to a network.</exception> public Wlan.WlanConnectionAttributes CurrentConnection { get { int valueSize; IntPtr valuePtr; Wlan.WlanOpcodeValueType opcodeValueType; Wlan.ThrowIfError( Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType)); try { return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes)); } finally { Wlan.WlanFreeMemory(valuePtr); } } } /// <summary> /// Requests a scan for available networks. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Scan() { Wlan.ThrowIfError( Wlan.WlanScan(client.clientHandle, info.interfaceGuid, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)); } /// <summary> /// Converts a pointer to a available networks list (header + entries) to an array of available network entries. /// </summary> /// <param name="availNetListPtr">A pointer to an available networks list's header.</param> /// <returns>An array of available network entries.</returns> private static Wlan.WlanAvailableNetwork[] ConvertAvailableNetworkListPtr(IntPtr availNetListPtr) { Wlan.WlanAvailableNetworkListHeader availNetListHeader = (Wlan.WlanAvailableNetworkListHeader)Marshal.PtrToStructure(availNetListPtr, typeof(Wlan.WlanAvailableNetworkListHeader)); long availNetListIt = availNetListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanAvailableNetworkListHeader)); Wlan.WlanAvailableNetwork[] availNets = new Wlan.WlanAvailableNetwork[availNetListHeader.numberOfItems]; for (int i = 0; i < availNetListHeader.numberOfItems; ++i) { availNets[i] = (Wlan.WlanAvailableNetwork)Marshal.PtrToStructure(new IntPtr(availNetListIt), typeof(Wlan.WlanAvailableNetwork)); availNetListIt += Marshal.SizeOf(typeof(Wlan.WlanAvailableNetwork)); } return availNets; } /// <summary> /// Retrieves the list of available networks. /// </summary> /// <param name="flags">Controls the type of networks returned.</param> /// <returns>A list of the available networks.</returns> public Wlan.WlanAvailableNetwork[] GetAvailableNetworkList(Wlan.WlanGetAvailableNetworkFlags flags) { IntPtr availNetListPtr; Wlan.ThrowIfError( Wlan.WlanGetAvailableNetworkList(client.clientHandle, info.interfaceGuid, flags, IntPtr.Zero, out availNetListPtr)); try { return ConvertAvailableNetworkListPtr(availNetListPtr); } finally { Wlan.WlanFreeMemory(availNetListPtr); } } /// <summary> /// Converts a pointer to a BSS list (header + entries) to an array of BSS entries. /// </summary> /// <param name="bssListPtr">A pointer to a BSS list's header.</param> /// <returns>An array of BSS entries.</returns> private static Wlan.WlanBssEntry[] ConvertBssListPtr(IntPtr bssListPtr) { Wlan.WlanBssListHeader bssListHeader = (Wlan.WlanBssListHeader)Marshal.PtrToStructure(bssListPtr, typeof(Wlan.WlanBssListHeader)); long bssListIt = bssListPtr.ToInt64() + Marshal.SizeOf(typeof(Wlan.WlanBssListHeader)); Wlan.WlanBssEntry[] bssEntries = new Wlan.WlanBssEntry[bssListHeader.numberOfItems]; for (int i=0; i<bssListHeader.numberOfItems; ++i) { bssEntries[i] = (Wlan.WlanBssEntry)Marshal.PtrToStructure(new IntPtr(bssListIt), typeof(Wlan.WlanBssEntry)); bssListIt += Marshal.SizeOf(typeof(Wlan.WlanBssEntry)); } return bssEntries; } /// <summary> /// Retrieves the basic service sets (BSS) list of all available networks. /// </summary> public Wlan.WlanBssEntry[] GetNetworkBssList() { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, Wlan.Dot11BssType.Any, false, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } /// <summary> /// Retrieves the basic service sets (BSS) list of the specified network. /// </summary> /// <param name="ssid">Specifies the SSID of the network from which the BSS list is requested.</param> /// <param name="bssType">Indicates the BSS type of the network.</param> /// <param name="securityEnabled">Indicates whether security is enabled on the network.</param> public Wlan.WlanBssEntry[] GetNetworkBssList(Wlan.Dot11Ssid ssid, Wlan.Dot11BssType bssType, bool securityEnabled) { IntPtr ssidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, ssidPtr, false); try { IntPtr bssListPtr; Wlan.ThrowIfError( Wlan.WlanGetNetworkBssList(client.clientHandle, info.interfaceGuid, ssidPtr, bssType, securityEnabled, IntPtr.Zero, out bssListPtr)); try { return ConvertBssListPtr(bssListPtr); } finally { Wlan.WlanFreeMemory(bssListPtr); } } finally { Marshal.FreeHGlobal(ssidPtr); } } /// <summary> /// Connects to a network defined by a connection parameters structure. /// </summary> /// <param name="connectionParams">The connection paramters.</param> protected void Connect(Wlan.WlanConnectionParameters connectionParams) { Wlan.ThrowIfError( Wlan.WlanConnect(client.clientHandle, info.interfaceGuid, ref connectionParams, IntPtr.Zero)); } /// <summary> /// Requests a connection (association) to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.profile = profile; connectionParams.dot11BssType = bssType; connectionParams.flags = 0; Connect(connectionParams); } /// <summary> /// Connects (associates) to the specified wireless network, returning either on a success to connect /// or a failure. /// </summary> /// <param name="connectionMode"></param> /// <param name="bssType"></param> /// <param name="profile"></param> /// <param name="connectTimeout"></param> /// <returns></returns> public bool ConnectSynchronously(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, string profile, int connectTimeout) { queueEvents = true; try { Connect(connectionMode, bssType, profile); while (queueEvents && eventQueueFilled.WaitOne(connectTimeout, true)) { lock (eventQueue) { while (eventQueue.Count != 0) { object e = eventQueue.Dequeue(); if (e is WlanConnectionNotificationEventData) { WlanConnectionNotificationEventData wlanConnectionData = (WlanConnectionNotificationEventData)e; // Check if the conditions are good to indicate either success or failure. if (wlanConnectionData.notifyData.notificationSource == Wlan.WlanNotificationSource.ACM) { switch ((Wlan.WlanNotificationCodeAcm)wlanConnectionData.notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionComplete: if (wlanConnectionData.connNotifyData.profileName == profile) return true; break; } } break; } } } } } finally { queueEvents = false; eventQueue.Clear(); } return false; // timeout expired and no "connection complete" } /// <summary> /// Connects to the specified wireless network. /// </summary> /// <remarks> /// The method returns immediately. Progress is reported through the <see cref="WlanNotification"/> event. /// </remarks> public void Connect(Wlan.WlanConnectionMode connectionMode, Wlan.Dot11BssType bssType, Wlan.Dot11Ssid ssid, Wlan.WlanConnectionFlags flags) { Wlan.WlanConnectionParameters connectionParams = new Wlan.WlanConnectionParameters(); connectionParams.wlanConnectionMode = connectionMode; connectionParams.dot11SsidPtr = Marshal.AllocHGlobal(Marshal.SizeOf(ssid)); Marshal.StructureToPtr(ssid, connectionParams.dot11SsidPtr, false); connectionParams.dot11BssType = bssType; connectionParams.flags = flags; Connect(connectionParams); Marshal.DestroyStructure(connectionParams.dot11SsidPtr, ssid.GetType()); Marshal.FreeHGlobal(connectionParams.dot11SsidPtr); } /// <summary> /// Deletes a profile. /// </summary> /// <param name="profileName"> /// The name of the profile to be deleted. Profile names are case-sensitive. /// On Windows XP SP2, the supplied name must match the profile name derived automatically from the SSID of the network. For an infrastructure network profile, the SSID must be supplied for the profile name. For an ad hoc network profile, the supplied name must be the SSID of the ad hoc network followed by <c>-adhoc</c>. /// </param> public void DeleteProfile(string profileName) { Wlan.ThrowIfError( Wlan.WlanDeleteProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero)); } /// <summary> /// Sets the profile. /// </summary> /// <param name="flags">The flags to set on the profile.</param> /// <param name="profileXml">The XML representation of the profile. On Windows XP SP 2, special care should be taken to adhere to its limitations.</param> /// <param name="overwrite">If a profile by the given name already exists, then specifies whether to overwrite it (if <c>true</c>) or return an error (if <c>false</c>).</param> /// <returns>The resulting code indicating a success or the reason why the profile wasn't valid.</returns> public Wlan.WlanReasonCode SetProfile(Wlan.WlanProfileFlags flags, string profileXml, bool overwrite) { Wlan.WlanReasonCode reasonCode; Wlan.ThrowIfError( Wlan.WlanSetProfile(client.clientHandle, info.interfaceGuid, flags, profileXml, null, overwrite, IntPtr.Zero, out reasonCode)); return reasonCode; } /// <summary> /// Gets the profile's XML specification. /// </summary> /// <param name="profileName">The name of the profile.</param> /// <returns>The XML document.</returns> public string GetProfileXml(string profileName) { IntPtr profileXmlPtr; Wlan.WlanProfileFlags flags; Wlan.WlanAccess access; Wlan.ThrowIfError( Wlan.WlanGetProfile(client.clientHandle, info.interfaceGuid, profileName, IntPtr.Zero, out profileXmlPtr, out flags, out access)); try { return Marshal.PtrToStringUni(profileXmlPtr); } finally { Wlan.WlanFreeMemory(profileXmlPtr); } } /// <summary> /// Gets the information of all profiles on this interface. /// </summary> /// <returns>The profiles information.</returns> public Wlan.WlanProfileInfo[] GetProfiles() { IntPtr profileListPtr; Wlan.ThrowIfError( Wlan.WlanGetProfileList(client.clientHandle, info.interfaceGuid, IntPtr.Zero, out profileListPtr)); try { Wlan.WlanProfileInfoListHeader header = (Wlan.WlanProfileInfoListHeader) Marshal.PtrToStructure(profileListPtr, typeof(Wlan.WlanProfileInfoListHeader)); Wlan.WlanProfileInfo[] profileInfos = new Wlan.WlanProfileInfo[header.numberOfItems]; long profileListIterator = profileListPtr.ToInt64() + Marshal.SizeOf(header); for (int i=0; i<header.numberOfItems; ++i) { Wlan.WlanProfileInfo profileInfo = (Wlan.WlanProfileInfo) Marshal.PtrToStructure(new IntPtr(profileListIterator), typeof(Wlan.WlanProfileInfo)); profileInfos[i] = profileInfo; profileListIterator += Marshal.SizeOf(profileInfo); } return profileInfos; } finally { Wlan.WlanFreeMemory(profileListPtr); } } internal void OnWlanConnection(Wlan.WlanNotificationData notifyData, Wlan.WlanConnectionNotificationData connNotifyData) { if (WlanConnectionNotification != null) WlanConnectionNotification(notifyData, connNotifyData); if (queueEvents) { WlanConnectionNotificationEventData queuedEvent = new WlanConnectionNotificationEventData(); queuedEvent.notifyData = notifyData; queuedEvent.connNotifyData = connNotifyData; EnqueueEvent(queuedEvent); } } internal void OnWlanReason(Wlan.WlanNotificationData notifyData, Wlan.WlanReasonCode reasonCode) { if (WlanReasonNotification != null) WlanReasonNotification(notifyData, reasonCode); if (queueEvents) { WlanReasonNotificationData queuedEvent = new WlanReasonNotificationData(); queuedEvent.notifyData = notifyData; queuedEvent.reasonCode = reasonCode; EnqueueEvent(queuedEvent); } } internal void OnWlanNotification(Wlan.WlanNotificationData notifyData) { if (WlanNotification != null) WlanNotification(notifyData); } /// <summary> /// Enqueues a notification event to be processed serially. /// </summary> private void EnqueueEvent(object queuedEvent) { lock (eventQueue) eventQueue.Enqueue(queuedEvent); eventQueueFilled.Set(); } /// <summary> /// Gets the network interface of this wireless interface. /// </summary> /// <remarks> /// The network interface allows querying of generic network properties such as the interface's IP address. /// </remarks> public NetworkInterface NetworkInterface { get { // Do not cache the NetworkInterface; We need it fresh // each time cause otherwise it caches the IP information. foreach (NetworkInterface netIface in NetworkInterface.GetAllNetworkInterfaces()) { Guid netIfaceGuid = new Guid(netIface.Id); if (netIfaceGuid.Equals(info.interfaceGuid)) { return netIface; } } return null; } } /// <summary> /// The GUID of the interface (same content as the <see cref="System.Net.NetworkInformation.NetworkInterface.Id"/> value). /// </summary> public Guid InterfaceGuid { get { return info.interfaceGuid; } } /// <summary> /// The description of the interface. /// This is a user-immutable string containing the vendor and model name of the adapter. /// </summary> public string InterfaceDescription { get { return info.interfaceDescription; } } /// <summary> /// The friendly name given to the interface by the user (e.g. "Local Area Network Connection"). /// </summary> public string InterfaceName { get { return NetworkInterface.Name; } } } private IntPtr clientHandle; private uint negotiatedVersion; private readonly Wlan.WlanNotificationCallbackDelegate wlanNotificationCallback; private readonly Dictionary<Guid,WlanInterface> ifaces = new Dictionary<Guid,WlanInterface>(); /// <summary> /// Creates a new instance of a Native Wifi service client. /// </summary> public WlanClient() { Wlan.ThrowIfError( Wlan.WlanOpenHandle(Wlan.WLAN_CLIENT_VERSION_XP_SP2, IntPtr.Zero, out negotiatedVersion, out clientHandle)); try { Wlan.WlanNotificationSource prevSrc; wlanNotificationCallback = OnWlanNotification; Wlan.ThrowIfError( Wlan.WlanRegisterNotification(clientHandle, Wlan.WlanNotificationSource.All, false, wlanNotificationCallback, IntPtr.Zero, IntPtr.Zero, out prevSrc)); } catch { Close(); throw; } } void IDisposable.Dispose() { GC.SuppressFinalize(this); Close(); } ~WlanClient() { Close(); } /// <summary> /// Closes the handle. /// </summary> private void Close() { if (clientHandle != IntPtr.Zero) { Wlan.WlanCloseHandle(clientHandle, IntPtr.Zero); clientHandle = IntPtr.Zero; } } private static Wlan.WlanConnectionNotificationData? ParseWlanConnectionNotification(ref Wlan.WlanNotificationData notifyData) { int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanConnectionNotificationData)); if (notifyData.dataSize < expectedSize) return null; Wlan.WlanConnectionNotificationData connNotifyData = (Wlan.WlanConnectionNotificationData) Marshal.PtrToStructure(notifyData.dataPtr, typeof(Wlan.WlanConnectionNotificationData)); if (connNotifyData.wlanReasonCode == Wlan.WlanReasonCode.Success) { IntPtr profileXmlPtr = new IntPtr( notifyData.dataPtr.ToInt64() + Marshal.OffsetOf(typeof(Wlan.WlanConnectionNotificationData), "profileXml").ToInt64()); connNotifyData.profileXml = Marshal.PtrToStringUni(profileXmlPtr); } return connNotifyData; } private void OnWlanNotification(ref Wlan.WlanNotificationData notifyData, IntPtr context) { WlanInterface wlanIface; ifaces.TryGetValue(notifyData.interfaceGuid, out wlanIface); switch(notifyData.notificationSource) { case Wlan.WlanNotificationSource.ACM: switch((Wlan.WlanNotificationCodeAcm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeAcm.ConnectionStart: case Wlan.WlanNotificationCodeAcm.ConnectionComplete: case Wlan.WlanNotificationCodeAcm.ConnectionAttemptFail: case Wlan.WlanNotificationCodeAcm.Disconnecting: case Wlan.WlanNotificationCodeAcm.Disconnected: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; case Wlan.WlanNotificationCodeAcm.ScanFail: { int expectedSize = Marshal.SizeOf(typeof (int)); if (notifyData.dataSize >= expectedSize) { // parse reason code if we can Wlan.WlanReasonCode reasonCode = Wlan.WlanReasonCode.UNKNOWN; int reasonData = Marshal.ReadInt32(notifyData.dataPtr); if (Enum.IsDefined(typeof(Wlan.WlanReasonCode), reasonData)) reasonCode = (Wlan.WlanReasonCode)reasonData; if (wlanIface != null) wlanIface.OnWlanReason(notifyData, reasonCode); } } break; } break; case Wlan.WlanNotificationSource.MSM: if (Enum.IsDefined(typeof(Wlan.WlanNotificationCodeMsm), notifyData.notificationCode)) { switch ((Wlan.WlanNotificationCodeMsm)notifyData.notificationCode) { case Wlan.WlanNotificationCodeMsm.Associating: case Wlan.WlanNotificationCodeMsm.Associated: case Wlan.WlanNotificationCodeMsm.Authenticating: case Wlan.WlanNotificationCodeMsm.Connected: case Wlan.WlanNotificationCodeMsm.RoamingStart: case Wlan.WlanNotificationCodeMsm.RoamingEnd: case Wlan.WlanNotificationCodeMsm.Disassociating: case Wlan.WlanNotificationCodeMsm.Disconnected: case Wlan.WlanNotificationCodeMsm.PeerJoin: case Wlan.WlanNotificationCodeMsm.PeerLeave: case Wlan.WlanNotificationCodeMsm.AdapterRemoval: Wlan.WlanConnectionNotificationData? connNotifyData = ParseWlanConnectionNotification(ref notifyData); if (connNotifyData.HasValue) if (wlanIface != null) wlanIface.OnWlanConnection(notifyData, connNotifyData.Value); break; } } break; } if (wlanIface != null) wlanIface.OnWlanNotification(notifyData); } /// <summary> /// Gets the WLAN interfaces. /// </summary> /// <value>The WLAN interfaces.</value> public WlanInterface[] Interfaces { get { IntPtr ifaceList; Wlan.ThrowIfError( Wlan.WlanEnumInterfaces(clientHandle, IntPtr.Zero, out ifaceList)); try { Wlan.WlanInterfaceInfoListHeader header = (Wlan.WlanInterfaceInfoListHeader) Marshal.PtrToStructure(ifaceList, typeof (Wlan.WlanInterfaceInfoListHeader)); Int64 listIterator = ifaceList.ToInt64() + Marshal.SizeOf(header); WlanInterface[] interfaces = new WlanInterface[header.numberOfItems]; List<Guid> currentIfaceGuids = new List<Guid>(); for (int i = 0; i < header.numberOfItems; ++i) { Wlan.WlanInterfaceInfo info = (Wlan.WlanInterfaceInfo) Marshal.PtrToStructure(new IntPtr(listIterator), typeof (Wlan.WlanInterfaceInfo)); listIterator += Marshal.SizeOf(info); currentIfaceGuids.Add(info.interfaceGuid); WlanInterface wlanIface; if (!ifaces.TryGetValue(info.interfaceGuid, out wlanIface)) { wlanIface = new WlanInterface(this, info); ifaces[info.interfaceGuid] = wlanIface; } interfaces[i] = wlanIface; } // Remove stale interfaces Queue<Guid> deadIfacesGuids = new Queue<Guid>(); foreach (Guid ifaceGuid in ifaces.Keys) { if (!currentIfaceGuids.Contains(ifaceGuid)) deadIfacesGuids.Enqueue(ifaceGuid); } while(deadIfacesGuids.Count != 0) { Guid deadIfaceGuid = deadIfacesGuids.Dequeue(); ifaces.Remove(deadIfaceGuid); } return interfaces; } finally { Wlan.WlanFreeMemory(ifaceList); } } } /// <summary> /// Gets a string that describes a specified reason code. /// </summary> /// <param name="reasonCode">The reason code.</param> /// <returns>The string.</returns> public string GetStringForReasonCode(Wlan.WlanReasonCode reasonCode) { StringBuilder sb = new StringBuilder(1024); // the 1024 size here is arbitrary; the WlanReasonCodeToString docs fail to specify a recommended size Wlan.ThrowIfError( Wlan.WlanReasonCodeToString(reasonCode, sb.Capacity, sb, IntPtr.Zero)); return sb.ToString(); } } }
using System; using System.Collections.Generic; using NUnit.Framework; using System.Threading; using OpenQA.Selenium.Environment; using System.IO; namespace OpenQA.Selenium.Firefox { [TestFixture] public class FirefoxDriverTest : DriverTestFixture { //[Test] public void ShouldContinueToWorkIfUnableToFindElementById() { driver.Url = formsPage; try { driver.FindElement(By.Id("notThere")); Assert.Fail("Should not be able to select element by id here"); } catch (NoSuchElementException) { // This is expected } // Is this works, then we're golden driver.Url = xhtmlTestPage; } //[Test] public void ShouldWaitUntilBrowserHasClosedProperly() { driver.Url = simpleTestPage; driver.Close(); CreateFreshDriver(); driver.Url = formsPage; IWebElement textarea = driver.FindElement(By.Id("withText")); string expectedText = "I like cheese" + System.Environment.NewLine + System.Environment.NewLine + "It's really nice"; textarea.Clear(); textarea.SendKeys(expectedText); string seenText = textarea.GetAttribute("value"); Assert.AreEqual(expectedText, seenText); } //[Test] public void ShouldBeAbleToStartMoreThanOneInstanceOfTheFirefoxDriverSimultaneously() { IWebDriver secondDriver = new FirefoxDriver(); driver.Url = xhtmlTestPage; secondDriver.Url = formsPage; Assert.AreEqual("XHTML Test Page", driver.Title); Assert.AreEqual("We Leave From Here", secondDriver.Title); // We only need to quit the second driver if the test passes secondDriver.Quit(); } //[Test] public void ShouldBeAbleToStartANamedProfile() { FirefoxProfile profile = new FirefoxProfileManager().GetProfile("default"); if (profile != null) { FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; IWebDriver firefox = new FirefoxDriver(options); firefox.Quit(); } else { Assert.Ignore("Skipping test: No profile named \"default\" found."); } } //[Test] public void ShouldRemoveProfileAfterExit() { FirefoxProfile profile = new FirefoxProfile(); FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; IWebDriver firefox = new FirefoxDriver(options); string profileLocation = profile.ProfileDirectory; firefox.Quit(); Assert.IsFalse(Directory.Exists(profileLocation)); } //[Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void FocusRemainsInOriginalWindowWhenOpeningNewWindow() { if (PlatformHasNativeEvents() == false) { return; } // Scenario: Open a new window, make sure the current window still gets // native events (keyboard events in this case). driver.Url = xhtmlTestPage; driver.FindElement(By.Name("windowOne")).Click(); SleepBecauseWindowsTakeTimeToOpen(); driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("ABC DEF"); Assert.AreEqual("ABC DEF", keyReporter.GetAttribute("value")); } //[Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void SwitchingWindowShouldSwitchFocus() { if (PlatformHasNativeEvents() == false) { return; } // Scenario: Open a new window, switch to it, make sure it gets native events. // Then switch back to the original window, make sure it gets native events. driver.Url = xhtmlTestPage; string originalWinHandle = driver.CurrentWindowHandle; driver.FindElement(By.Name("windowOne")).Click(); SleepBecauseWindowsTakeTimeToOpen(); List<string> allWindowHandles = new List<string>(driver.WindowHandles); // There should be two windows. We should also see each of the window titles at least once. Assert.AreEqual(2, allWindowHandles.Count); allWindowHandles.Remove(originalWinHandle); string newWinHandle = (string)allWindowHandles[0]; // Key events in new window. driver.SwitchTo().Window(newWinHandle); SleepBecauseWindowsTakeTimeToOpen(); driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("ABC DEF"); Assert.AreEqual("ABC DEF", keyReporter.GetAttribute("value")); // Key events in original window. driver.SwitchTo().Window(originalWinHandle); SleepBecauseWindowsTakeTimeToOpen(); driver.Url = javascriptPage; IWebElement keyReporter2 = driver.FindElement(By.Id("keyReporter")); keyReporter2.SendKeys("QWERTY"); Assert.AreEqual("QWERTY", keyReporter2.GetAttribute("value")); } //[Test] [NeedsFreshDriver(IsCreatedBeforeTest = true, IsCreatedAfterTest = true)] public void ClosingWindowAndSwitchingToOriginalSwitchesFocus() { if (PlatformHasNativeEvents() == false) { return; } // Scenario: Open a new window, switch to it, close it, switch back to the // original window - make sure it gets native events. driver.Url = xhtmlTestPage; string originalWinHandle = driver.CurrentWindowHandle; driver.FindElement(By.Name("windowOne")).Click(); SleepBecauseWindowsTakeTimeToOpen(); List<string> allWindowHandles = new List<string>(driver.WindowHandles); // There should be two windows. We should also see each of the window titles at least once. Assert.AreEqual(2, allWindowHandles.Count); allWindowHandles.Remove(originalWinHandle); string newWinHandle = (string)allWindowHandles[0]; // Switch to the new window. driver.SwitchTo().Window(newWinHandle); SleepBecauseWindowsTakeTimeToOpen(); // Close new window. driver.Close(); // Switch back to old window. driver.SwitchTo().Window(originalWinHandle); SleepBecauseWindowsTakeTimeToOpen(); // Send events to the new window. driver.Url = javascriptPage; IWebElement keyReporter = driver.FindElement(By.Id("keyReporter")); keyReporter.SendKeys("ABC DEF"); Assert.AreEqual("ABC DEF", keyReporter.GetAttribute("value")); } //[Test] public void CanBlockInvalidSslCertificates() { FirefoxProfile profile = new FirefoxProfile(); string url = EnvironmentManager.Instance.UrlBuilder.WhereIsSecure("simpleTest.html"); IWebDriver secondDriver = null; try { FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; secondDriver = new FirefoxDriver(options); secondDriver.Url = url; string gotTitle = secondDriver.Title; Assert.AreNotEqual("Hello IWebDriver", gotTitle); } catch (Exception) { Assert.Fail("Creating driver with untrusted certificates set to false failed."); } finally { if (secondDriver != null) { secondDriver.Quit(); } } } //[Test] public void ShouldAllowUserToSuccessfullyOverrideTheHomePage() { FirefoxProfile profile = new FirefoxProfile(); profile.SetPreference("browser.startup.page", "1"); profile.SetPreference("browser.startup.homepage", javascriptPage); FirefoxOptions options = new FirefoxOptions(); options.Profile = profile; IWebDriver driver2 = new FirefoxDriver(options); try { Assert.AreEqual(javascriptPage, driver2.Url); } finally { driver2.Quit(); } } private static bool PlatformHasNativeEvents() { return true; } private void SleepBecauseWindowsTakeTimeToOpen() { try { Thread.Sleep(1000); } catch (ThreadInterruptedException) { Assert.Fail("Interrupted"); } } } }
using ESRI.ArcGIS.Client; using ESRI.ArcGIS.Client.Tasks; using FieldWorker.Common; using FieldWorker.Schema; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Windows.Data; using System.Windows.Input; namespace FieldWorker.ViewModels { public abstract class BaseItemsViewModel : BaseViewModel { protected FeatureLayerHelper _featureLayerHelper = null; private String _filterString; private bool _bDefaultsApplied = false; protected ObservableCollection<Item> _items; protected List<Item> _filteredItems; protected List<GroupColumnViewModel> _groupByColumnViewModels = null; protected ItemSchema _schema = null; public ItemSchema Schema { get { return _schema; } } public ICommand GroupByDelegatingCommand { get; protected set; } public BaseItemsViewModel ViewModel { get; protected set; } private Object _selectedItem = null; public Object SelectedItem { get { return _selectedItem; } set { _selectedItem = value; OnPropertyChanged(() => ViewModel); } } public bool ConvertToLocalTimeZone { get; set; } public Dictionary<string, string> Properties { get; set; } public string GetPropValue(string name) { if (!Properties.ContainsKey(name)) return null; return Properties[name]; } private bool _bSkipUdates = false; public bool SkipUpdates { get { return _bSkipUdates; } set { _bSkipUdates = value; } } public ObservableCollection<Schema.Item> Items { get { return _items; } protected set { _items = value; } } protected CollectionViewGroup FindCollectionViewGroup(String groupName) { ICollectionView cv = CollectionViewSource.GetDefaultView(Items); if (cv == null || cv.Groups == null) return null; foreach (CollectionViewGroup group in cv.Groups) { if (group.Name.ToString() == groupName) return group; } return null; } //hk - REVIEW ... public String TrackIdFieldName { get; set; } public String GroupByFieldName { get; set; } public String SortByFieldName1 { get; set; } public String SortByFieldName2 { get; set; } public ListSortDirection SortByFieldOrder1 { get; set; } public ListSortDirection SortByFieldOrder2 { get; set; } public BaseItemsViewModel(FeatureLayerHelper featureLayerHelper) { Init(); SetFeatureLayer(featureLayerHelper); ViewModel = this; Properties = new Dictionary<string, string>(); ConvertToLocalTimeZone = true; // init commands GroupByDelegatingCommand = new DelegatingCommand(OnGroupByAction); //hk Update(featureLayer); } private void Init() { _items = new ObservableCollection<Item>(); _filteredItems = new List<Item>(); } virtual protected Item CreateItem() { return new Item(this); } public void GetProperties(Dictionary<string, string> properties) { // update the Widget's data members from the VM so that they will get persisted with the widget if (properties == null) return; foreach (KeyValuePair<string, string> entry in Properties) properties[entry.Key] = entry.Value; } public void SetProperties(Dictionary<string, string> properties) { // update the VM from the View's data members if (properties == null) return; foreach (KeyValuePair<string, string> entry in properties) Properties[entry.Key] = entry.Value; } public Item GetSelectedItem() { return SelectedItem as Item; } public void SetFeatureLayer(FeatureLayerHelper featureLayerHelper) { if (featureLayerHelper == null || featureLayerHelper.FeatureLayer == null) return; if (_featureLayerHelper == null || _featureLayerHelper.FeatureLayer != featureLayerHelper.FeatureLayer) { // this will cause the schema to get recreated _schema = null; // clear the grouping _groupByColumnViewModels = null; } _featureLayerHelper = featureLayerHelper; } public void Update(FeatureLayerHelper featureLayerHelper, string where) { if (SkipUpdates) return; if (featureLayerHelper == null || featureLayerHelper.FeatureLayer == null) return; if (featureLayerHelper.FeatureLayer.HasEdits) return; if (String.IsNullOrEmpty(where)) where = "1=1"; QueryTask queryTask = new QueryTask(featureLayerHelper.FeatureLayer.Url); Query query = new Query(); query.Where = where; query.ReturnGeometry = true; query.OutFields.AddRange(new string[] { "*" }); queryTask.Execute(query); try { SetFeatureLayer(featureLayerHelper); Update(queryTask.LastResult); } catch (Exception ex) { Log.TraceException("Updating " + featureLayerHelper.FeatureLayer.DisplayName, ex); } } protected void Update(FeatureSet featureSet) { Update(featureSet.Features, featureSet.Fields); } private void Update(IList<Graphic> graphics, List<Field> fields) { if (SkipUpdates) return; // Delete removed items IList<Item> itemsToRemove = GetItemsToRemove(Items, graphics); foreach (Item item in itemsToRemove) { Items.Remove(item); Log.Trace("Update - removed " + itemsToRemove.Count + " items."); } itemsToRemove.Clear(); itemsToRemove = GetItemsToRemove(_filteredItems, graphics); foreach (Item item in itemsToRemove) _filteredItems.Remove(item); // Update existing items and add new ones foreach (Graphic graphic in graphics) { string trackId = graphic.Attributes[TrackIdFieldName].ToString(); if (trackId == null) continue; Item itemFound = null; // look for the item in Items itemFound = FindTrackIdInItems(trackId, Items); if (itemFound != null) { // item found in Items, update the item UpdateItem(itemFound, graphic); //Log.Trace("Update - updated item " + itemFound.Graphic.Attributes[TrackIdFieldName] + "."); if (!IsItemIncludedForFilter(itemFound)) { // move the item to the _filteredItems Items.Remove(itemFound); Log.Trace("Update - removed item " + itemFound.Graphic.Attributes[TrackIdFieldName] + "."); _filteredItems.Add(itemFound); } } else { // item was not found in Items, look for it in _filteredItems itemFound = FindTrackIdInItems(trackId, _filteredItems); if (itemFound != null) { // item found in _filteredItems, update the item UpdateItem(itemFound, graphic); if (IsItemIncludedForFilter(itemFound)) { // move the item to the Items _filteredItems.Remove(itemFound); Items.Add(itemFound); Log.Trace("Update - added item " + itemFound.Graphic.Attributes[TrackIdFieldName] + "."); } } } if (itemFound == null) { // item was not found, add it as a new item Item newItem = CreateNewItem(graphic, fields); if (newItem == null) continue; if (IsItemIncludedForFilter(newItem)) { Items.Add(newItem); Log.Trace("Update - added item " + newItem.Graphic.Attributes[TrackIdFieldName] + "."); } else { _filteredItems.Add(newItem); } } } InitDefaults(); } private IList<Item> GetItemsToRemove(IList<Item> items, IList<Graphic> graphics) { List<Item> itemsToRemove = new List<Item>(); foreach (Item item in items) { object trackIdObj = item.GetPropertyValue(TrackIdFieldName); if (trackIdObj != null) { string trackId = trackIdObj.ToString(); Graphic graphicFound = FindTrackIdInGraphics(trackId, graphics, TrackIdFieldName); if (graphicFound == null) itemsToRemove.Add(item); } } return itemsToRemove; } protected Graphic FindTrackIdInGraphics(string trackId, IList<Graphic> graphics, string key) { if (trackId == null) return null; foreach (Graphic graphic in graphics) { if (graphic.Attributes == null) continue; if (!graphic.Attributes.ContainsKey(key)) continue; object graphicTrackIdObj = graphic.Attributes[key]; if (graphicTrackIdObj == null) continue; string graphicTrackId = graphicTrackIdObj.ToString(); if (graphicTrackId == null) continue; if (graphicTrackId.ToUpper() == trackId.ToUpper()) return graphic; } return null; } private Item FindTrackIdInItems(string trackId, IList<Item> items) { if (trackId == null) return null; foreach (Item item in items) { string itemTrackId = item.GetPropertyValue(TrackIdFieldName).ToString(); if (itemTrackId == null) continue; if (itemTrackId.ToUpper() == trackId.ToUpper()) return item; } return null; } protected bool UpdateItem(Item item, Graphic graphic) { // update the item's properties foreach (KeyValuePair<string, object> pair in graphic.Attributes) { object value = pair.Value; if (ConvertToLocalTimeZone && pair.Value is DateTime) { // convert the DateTime attribute to local time zone DateTime localTime = ((DateTime)value).ToLocalTime(); value = localTime as object; } item.SetPropertyValue(pair.Key, value); } // update the item's graphic //hk graphic.Geometry = Helper.ProjectGeometryToMap(graphic.Geometry, _map); item.Graphic = graphic; return true; } protected Item CreateNewItem(Graphic graphic, List<Field> fields) { // make sure the schema is up to date if (_schema == null) { if (fields == null) return null; _schema = new ItemSchema(); Field oidField = null; foreach (Field field in fields) { if (field.Type == Field.FieldType.OID) // (field.Name.ToUpper() != "OBJECTID") oidField = field; else _schema.AddProperty(field); } // add the OID field at the end if (oidField != null) _schema.AddProperty(oidField); } // create a new item Item item = CreateItem(); // set item attributes if (!UpdateItem(item, graphic)) return null; return item; } public IEnumerable<GroupColumnViewModel> GroupByColumnViewModels { get { if (_groupByColumnViewModels == null) { if (_schema == null) return null; PropertyInfo[] propInfos = _schema.GetProperties(); if (propInfos == null) return null; if (propInfos.Count() == 0) return null; // create a new ViewModel collection _groupByColumnViewModels = new List<GroupColumnViewModel>(); // add a ViewModel for "None" _groupByColumnViewModels.Add(new GroupColumnViewModel("None", GroupByDelegatingCommand) { IsChecked = true }); // add ViewModels for each of the properties foreach (PropertyInfo pi in propInfos) _groupByColumnViewModels.Add(new GroupColumnViewModel(pi.Name, GroupByDelegatingCommand)); } return _groupByColumnViewModels; } } private void InitDefaults() { if (!_bDefaultsApplied) { _bDefaultsApplied = ApplySettings(); // temp workaround to make sure to apply changes _bDefaultsApplied = false; } } public bool ApplySettings() { if (_schema == null) return false; // if null or empty group by string - keep default group name as "None" String groupByFieldName = GroupByFieldName == null ? null : _schema.NameToAlias(GroupByFieldName); if (!String.IsNullOrEmpty(groupByFieldName)) ApplyGroupBy(groupByFieldName); ApplySortBy(SortByFieldName1, SortByFieldOrder1, SortByFieldName2, SortByFieldOrder2); return true; } private bool ApplySortBy(String fieldName1, ListSortDirection sortDirection1, String fieldName2, ListSortDirection sortDirection2) { if (_schema == null) return false; ICollectionView cv = CollectionViewSource.GetDefaultView(_items); ICollectionViewLiveShaping cvls = cv as ICollectionViewLiveShaping; if (!cv.CanSort) return false; cvls.IsLiveSorting = true; cv.SortDescriptions.Clear(); //cvls.LiveSortingProperties.Clear(); if (!String.IsNullOrEmpty(fieldName1)) { cv.SortDescriptions.Add(new SortDescription(fieldName1, sortDirection1)); //cvls.LiveSortingProperties.Add(fieldName1); } if (!String.IsNullOrEmpty(fieldName2)) { cv.SortDescriptions.Add(new SortDescription(fieldName2, sortDirection2)); //cvls.LiveSortingProperties.Add(fieldName2); } return true; } private bool ApplyGroupBy(String groupByName) { if (_schema == null) return false; ICollectionView cv = CollectionViewSource.GetDefaultView(_items); ICollectionViewLiveShaping cvls = cv as ICollectionViewLiveShaping; if (!cv.CanGroup) return false; foreach (var viewModel in GroupByColumnViewModels) viewModel.IsChecked = (viewModel.PropertyName == groupByName); cvls.IsLiveGrouping = true; cvls.IsLiveFiltering = true; cvls.IsLiveSorting = true; // clear the group cv.GroupDescriptions.Clear(); cvls.LiveGroupingProperties.Clear(); // if groupByName not in schema - set the group to "None" if (!_schema.ContainsPropertyAlias(groupByName)) return false; // set the group if (groupByName != "None") { cv.GroupDescriptions.Add(new PropertyGroupDescription(groupByName)); cvls.LiveGroupingProperties.Add(groupByName); } // refresh the live properties cvls.LiveFilteringProperties.Clear(); cvls.LiveSortingProperties.Clear(); PropertyInfo[] propInfos = _schema.GetProperties(); foreach (var propInfo in propInfos) { cvls.LiveFilteringProperties.Add(propInfo.Name); cvls.LiveSortingProperties.Add(propInfo.Name); //cvls.LiveFilteringProperties.Add(propInfo.Name); } return true; } private void OnGroupByAction(object vm) { GroupColumnViewModel groupColumnViewModel = vm as GroupColumnViewModel; string groupByName = groupColumnViewModel != null ? groupColumnViewModel.PropertyName : "None"; ICollectionView cv = CollectionViewSource.GetDefaultView(_items); if (cv.CanGroup) ApplyGroupBy(groupByName); } private void ApplyFilter(Boolean enableFilter) { //ApplyWpfFilter(enableFilter); ApplyManualFilter(enableFilter); } private void ApplyManualFilter(Boolean enableFilter) { if (!enableFilter) { foreach (Item item in _filteredItems) Items.Add(item); _filteredItems.Clear(); return; } // backup filtered items to prevFilteredItems List<Item> prevFilteredItems = _filteredItems; _filteredItems = new List<Item>(); // add items to the Items list foreach (Item item in prevFilteredItems) { if (IsItemIncludedForFilter(item)) Items.Add(item); else _filteredItems.Add(item); } // mark new filtered items (store them in a new temp list) to br removed from the items list List<Item> itemsToRemove = new List<Item>(); foreach (Item item in Items) { if (!IsItemIncludedForFilter(item)) itemsToRemove.Add(item); } // move filtered items from Items to _filteredItems foreach (Item item in itemsToRemove) { _filteredItems.Add(item); Items.Remove(item); } } private void ApplyWpfFilter(Boolean enableFilter) { ICollectionView cv = CollectionViewSource.GetDefaultView(_items); ICollectionViewLiveShaping cvls = cv as ICollectionViewLiveShaping; if (!enableFilter) { cv.Filter = null; return; } if (cv != null && cv.CanFilter) { if (cvls != null && cvls.CanChangeLiveFiltering) { if (_schema != null) { PropertyInfo[] propInfos = _schema.GetProperties(); cvls.LiveFilteringProperties.Clear(); foreach (var propInfo in propInfos) cvls.LiveFilteringProperties.Add(propInfo.Name); } cvls.IsLiveFiltering = true; cv.Filter = IsItemIncludedForFilter; } } } public bool IsItemIncludedForFilter(object item) { if (String.IsNullOrEmpty(_filterString)) return true; string filterString = _filterString.ToLower(); Item dynamicItem = (Item)item; PropertyInfo[] propInfos = dynamicItem.GetProperties(); foreach (var propInfo in propInfos) { var prop = dynamicItem.GetPropertyValue(propInfo.Name); if (prop == null) continue; if (prop.ToString().ToLower().Contains(filterString)) return true; } return false; } public void SetFilterString(string filterString) { SkipUpdates = true; _filterString = filterString; ApplyFilter(true); SkipUpdates = false; } public int GetItemsCount() { return Items.Count(); } } }
using System; using System.IO; using System.Text; using NUnit.Framework; using Raksha.Bcpg; using Raksha.Bcpg.OpenPgp; using Raksha.Security; using Raksha.Utilities; using Raksha.Utilities.Encoders; using Raksha.Utilities.IO; using Raksha.Tests.Utilities; namespace Raksha.Tests.Bcpg.OpenPgp { [TestFixture] public class PgpPbeTest : SimpleTest { private static readonly DateTime TestDateTime = new DateTime(2003, 8, 29, 23, 35, 11, 0); private static readonly byte[] enc1 = Base64.Decode( "jA0EAwMC5M5wWBP2HBZgySvUwWFAmMRLn7dWiZN6AkQMvpE3b6qwN3SSun7zInw2" + "hxxdgFzVGfbjuB8w"); // private static readonly byte[] enc1crc = Base64.Decode("H66L"); private static readonly char[] pass = "hello world".ToCharArray(); /** * Message with both PBE and symmetric */ private static readonly byte[] testPBEAsym = Base64.Decode( "hQIOA/ZlQEFWB5vuEAf/covEUaBve7NlWWdiO5NZubdtTHGElEXzG9hyBycp9At8" + "nZGi27xOZtEGFQo7pfz4JySRc3O0s6w7PpjJSonFJyNSxuze2LuqRwFWBYYcbS8/" + "7YcjB6PqutrT939OWsozfNqivI9/QyZCjBvFU89pp7dtUngiZ6MVv81ds2I+vcvk" + "GlIFcxcE1XoCIB3EvbqWNaoOotgEPT60unnB2BeDV1KD3lDRouMIYHfZ3SzBwOOI" + "6aK39sWnY5sAK7JjFvnDAMBdueOiI0Fy+gxbFD/zFDt4cWAVSAGTC4w371iqppmT" + "25TM7zAtCgpiq5IsELPlUZZnXKmnYQ7OCeysF0eeVwf+OFB9fyvCEv/zVQocJCg8" + "fWxfCBlIVFNeNQpeGygn/ZmRaILvB7IXDWP0oOw7/F2Ym66IdYYIp2HeEZv+jFwa" + "l41w5W4BH/gtbwGjFQ6CvF/m+lfUv6ZZdzsMIeEOwhP5g7rXBxrbcnGBaU+PXbho" + "gjDqaYzAWGlrmAd6aPSj51AGeYXkb2T1T/yoJ++M3GvhH4C4hvitamDkksh/qRnM" + "M/s8Nku6z1+RXO3M6p5QC1nlAVqieU8esT43945eSoC77K8WyujDNbysDyUCUTzt" + "p/aoQwe/HgkeOTJNelKR9y2W3xinZLFzep0SqpNI/e468yB/2/LGsykIyQa7JX6r" + "BYwuBAIDAkOKfv5rK8v0YDfnN+eFqwhTcrfBj5rDH7hER6nW3lNWcMataUiHEaMg" + "o6Q0OO1vptIGxW8jClTD4N1sCNwNu9vKny8dKYDDHbCjE06DNTv7XYVW3+JqTL5E" + "BnidvGgOmA=="); /** * decrypt the passed in message stream */ private byte[] DecryptMessage( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime); } Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bytes; } private byte[] DecryptMessageBuffered( byte[] message) { PgpObjectFactory pgpF = new PgpObjectFactory(message); PgpEncryptedDataList enc = (PgpEncryptedDataList) pgpF.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[0]; Stream clear = pbe.GetDataStream(pass); PgpObjectFactory pgpFact = new PgpObjectFactory(clear); PgpCompressedData cData = (PgpCompressedData) pgpFact.NextPgpObject(); pgpFact = new PgpObjectFactory(cData.GetDataStream()); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); MemoryStream bOut = new MemoryStream(); if (!ld.FileName.Equals("test.txt") && !ld.FileName.Equals("_CONSOLE")) { Fail("wrong filename in packet"); } if (!ld.ModificationTime.Equals(TestDateTime)) { Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks); } Stream unc = ld.GetInputStream(); byte[] buf = new byte[1024]; int len; while ((len = unc.Read(buf, 0, buf.Length)) > 0) { bOut.Write(buf, 0, len); } if (pbe.IsIntegrityProtected() && !pbe.Verify()) { Fail("integrity check failed"); } return bOut.ToArray(); } public override void PerformTest() { byte[] data = DecryptMessage(enc1); if (data[0] != 'h' || data[1] != 'e' || data[2] != 'l') { Fail("wrong plain text in packet"); } // // create a PBE encrypted message and read it back. // byte[] text = Encoding.ASCII.GetBytes("hello world!\n"); // // encryption step - convert to literal data, compress, encode. // MemoryStream bOut = new UncloseableMemoryStream(); PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator(); Stream comOut = comData.Open(new UncloseableStream(bOut)); Stream ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, text.Length, TestDateTime); ldOut.Write(text, 0, text.Length); ldOut.Close(); comOut.Close(); // // encrypt - with stream close // MemoryStream cbOut = new UncloseableMemoryStream(); PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass); byte[] bOutData = bOut.ToArray(); Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - with generator close // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, new SecureRandom()); cPk.AddMethod(pass); bOutData = bOut.ToArray(); cOut = cPk.Open(new UncloseableStream(cbOut), bOutData.Length); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, text)) { Fail("wrong plain text in generated packet"); } // // encrypt - partial packet style. // SecureRandom rand = new SecureRandom(); byte[] test = new byte[1233]; rand.NextBytes(test); bOut = new UncloseableMemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); comOut = comData.Open(new UncloseableStream(bOut)); lData = new PgpLiteralDataGenerator(); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, TestDateTime, new byte[16]); ldOut.Write(test, 0, test.Length); lData.Close(); comData.Close(); cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); { byte[] tmp = bOut.ToArray(); cOut.Write(tmp, 0, tmp.Length); } cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // with integrity packet // cbOut = new UncloseableMemoryStream(); cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); bOutData = bOut.ToArray(); cOut.Write(bOutData, 0, bOutData.Length); cPk.Close(); data = DecryptMessage(cbOut.ToArray()); if (!Arrays.AreEqual(data, test)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, test)) { Fail("wrong plain text in buffer generated packet"); } // // sample message // PgpObjectFactory pgpFact = new PgpObjectFactory(testPBEAsym); PgpEncryptedDataList enc = (PgpEncryptedDataList)pgpFact.NextPgpObject(); PgpPbeEncryptedData pbe = (PgpPbeEncryptedData) enc[1]; Stream clear = pbe.GetDataStream("password".ToCharArray()); pgpFact = new PgpObjectFactory(clear); PgpLiteralData ld = (PgpLiteralData) pgpFact.NextPgpObject(); Stream unc = ld.GetInputStream(); byte[] bytes = Streams.ReadAll(unc); if (!AreEqual(bytes, Hex.Decode("5361742031302e30322e30370d0a"))) { Fail("data mismatch on combined PBE"); } // // with integrity packet - one byte message // byte[] msg = new byte[1]; bOut = new MemoryStream(); comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip); lData = new PgpLiteralDataGenerator(); comOut = comData.Open(new UncloseableStream(bOut)); ldOut = lData.Open( new UncloseableStream(comOut), PgpLiteralData.Binary, PgpLiteralData.Console, msg.Length, TestDateTime); ldOut.Write(msg, 0, msg.Length); ldOut.Close(); comOut.Close(); cbOut = new MemoryStream(); cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, true, rand); cPk.AddMethod(pass); cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]); data = bOut.ToArray(); cOut.Write(data, 0, data.Length); cOut.Close(); data = DecryptMessage(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in generated packet"); } // // decrypt with buffering // data = DecryptMessageBuffered(cbOut.ToArray()); if (!AreEqual(data, msg)) { Fail("wrong plain text in buffer generated packet"); } } private class UncloseableMemoryStream : MemoryStream { public override void Close() { throw new Exception("Close() called on underlying stream"); } } public override string Name { get { return "PGPPBETest"; } } public static void Main( string[] args) { RunTest(new PgpPbeTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
using System; using WindowsAzure.Messaging; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Plugin.AzurePushNotifications; namespace Gcm.Client { [Preserve(AllMembers = true)] public abstract class GcmServiceBase : IntentService { private const string WakelockKey = "GCM_LIB"; private const int MaxBackoffMs = 3600000; //1 hour private const string ExtraToken = "token"; private static PowerManager.WakeLock sWakeLock; private static readonly object Lock = new object(); private static int serviceId = 1; protected static NotificationHub Hub; private readonly Random sRandom = new Random(); private readonly string token = ""; /// <summary> /// The GCM Sender Ids to use. Set by the constructor taking parameters but not by the one that doesn't. Be very /// careful changing this value, preferably only set it in your constructor and only once. /// </summary> protected string[] SenderIds; protected GcmServiceBase() { SenderIds = new[] {PushNotificationCredentials.GoogleApiSenderId}; } public GcmServiceBase(params string[] senderIds) : base("GCMIntentService-" + serviceId++) { SenderIds = senderIds; } protected virtual void OnMessage(Context context, Intent intent) { } protected virtual void OnDeletedMessages(Context context, int total) { } protected virtual bool OnRecoverableError(Context context, string errorId) { return true; } protected virtual void OnError(Context context, string errorId) { } protected virtual void OnRegistered(Context context, string registrationId) { Hub = new NotificationHub(PushNotificationCredentials.AzureNotificationHubName, PushNotificationCredentials.AzureListenConnectionString, context); try { Hub.UnregisterAll(registrationId); } catch(Exception ex) { //Log.Error(PushNotificationsBroadcastReceiver.Tag, ex.Message); } try { var hubRegistration = Hub.Register(registrationId, PushNotificationCredentials.Tags); } catch(Exception ex) { //Log.Error(PushNotificationsBroadcastReceiver.Tag, ex.Message); } } protected virtual void OnUnRegistered(Context context, string registrationId) { Hub?.Unregister(); } protected override void OnHandleIntent(Intent intent) { try { var context = ApplicationContext; var action = intent.Action; if(action.Equals(Constants.IntentFromGcmRegistrationCallback)) { HandleRegistration(context, intent); } else if(action.Equals(Constants.IntentFromGcmMessage)) { // checks for special messages var messageType = intent.GetStringExtra(Constants.ExtraSpecialMessage); if(messageType != null) { if(messageType.Equals(Constants.ValueDeletedMessages)) { var sTotal = intent.GetStringExtra(Constants.ExtraTotalDeleted); if(!string.IsNullOrEmpty(sTotal)) { var nTotal = 0; if(int.TryParse(sTotal, out nTotal)) { //Logger.Debug("Received deleted messages notification: " + nTotal); OnDeletedMessages(context, nTotal); } } } } else { OnMessage(context, intent); } } else if(action.Equals(Constants.IntentFromGcmLibraryRetry)) { var token = intent.GetStringExtra(ExtraToken); if(!string.IsNullOrEmpty(token) && !this.token.Equals(token)) { // make sure intent was generated by this class, not by a // malicious app. //Logger.Debug("Received invalid token: " + token); return; } // retry last call if(GcmClient.IsRegistered(context)) { GcmClient.InternalUnRegister(context); } else { GcmClient.InternalRegister(context, SenderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If OnMessage() needs to spawn a thread or do something else, // it should use its own lock. lock(Lock) { //Sanity check for null as this is a public method if(sWakeLock != null) { //Logger.Debug("Releasing Wakelock"); sWakeLock.Release(); } } } } internal static void RunIntentInService(Context context, Intent intent, Type classType) { lock(Lock) { if(sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. var pm = PowerManager.FromContext(context); sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, WakelockKey); } } //Logger.Debug("Acquiring wakelock"); sWakeLock.Acquire(); //intent.SetClassName(context, className); intent.SetClass(context, classType); context.StartService(intent); } private void HandleRegistration(Context context, Intent intent) { var registrationId = intent.GetStringExtra(Constants.ExtraRegistrationId); var error = intent.GetStringExtra(Constants.ExtraError); var unregistered = intent.GetStringExtra(Constants.ExtraUnregistered); //Logger.Debug("handleRegistration: registrationId = " + registrationId + ", error = " + error + ", unregistered = " + unregistered); // registration succeeded if(registrationId != null) { GcmClient.ResetBackoff(context); GcmClient.SetRegistrationId(context, registrationId); OnRegistered(context, registrationId); return; } // unregistration succeeded if(unregistered != null) { // Remember we are unregistered GcmClient.ResetBackoff(context); var oldRegistrationId = GcmClient.ClearRegistrationId(context); OnUnRegistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; //Logger.Debug("Registration error: " + error); // Registration failed if(Constants.ErrorServiceNotAvailable.Equals(error)) { var retry = OnRecoverableError(context, error); if(retry) { var backoffTimeMs = GcmClient.GetBackoff(context); var nextAttempt = backoffTimeMs/2 + sRandom.Next(backoffTimeMs); //Logger.Debug("Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")"); var retryIntent = new Intent(Constants.IntentFromGcmLibraryRetry); retryIntent.PutExtra(ExtraToken, token); var retryPendingIntent = PendingIntent.GetBroadcast(context, 0, retryIntent, PendingIntentFlags.OneShot); var am = AlarmManager.FromContext(context); am.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if(backoffTimeMs < MaxBackoffMs) { GcmClient.SetBackoff(context, backoffTimeMs*2); } } } else { // Unrecoverable error, notify app OnError(context, error); } } } }
// Copyright (c) Lex Li. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace JexusManager.Features { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using JexusManager.Services; using Microsoft.Web.Administration; using Microsoft.Web.Management.Client.Win32; using Module = Microsoft.Web.Management.Client.Module; public abstract class FeatureBase<T> where T : class, IItem<T> { protected FeatureBase(Module module) { this.Module = module; Items = new List<T>(); } public List<T> Items { get; set; } public T SelectedItem { get; set; } public virtual bool IsFeatureEnabled { get { return true; } } public Module Module { get; } public bool CanMoveUp { get { return this.SelectedItem != null && this.Items.IndexOf(this.SelectedItem) > 0 && this.Items.All(item => item.Element.IsLocked == "false" && item.Element.LockAttributes.Count == 0); } } public bool CanMoveDown { get { return this.SelectedItem != null && this.Items.IndexOf(this.SelectedItem) < this.Items.Count - 1 && this.Items.All(item => item.Element.IsLocked == "false" && item.Element.LockAttributes.Count == 0); } } protected abstract ConfigurationElementCollection GetCollection(IConfigurationService service); protected object GetService(Type type) { return (this.Module as IServiceProvider).GetService(type); } protected void DisplayErrorMessage(Exception ex, ResourceManager resourceManager) { var service = (IManagementUIService)this.GetService(typeof(IManagementUIService)); service.ShowError(ex, resourceManager?.GetString("General"), "", false); } protected abstract void OnSettingsSaved(); public virtual void LoadItems() { this.Items.Clear(); var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); ConfigurationElementCollection collection = this.GetCollection(service); foreach (ConfigurationElement addElement in collection) { var type = typeof(T); var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var constructorInfo = constructors[0]; var item = (T) constructorInfo.Invoke( constructorInfo.GetParameters().Length == 1 ? new object[] { addElement } : new object[] { addElement, true }); this.Items.Add(item); } var secondary = GetSecondaryCollection(service); if (secondary != null) { foreach (ConfigurationElement addElement in secondary) { var type = typeof(T); var constructors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var constructorInfo = constructors[0]; var item = (T) constructorInfo.Invoke( constructorInfo.GetParameters().Length == 1 ? new object[] { addElement } : new object[] { addElement, false }); this.Items.Add(item); } } this.OnSettingsSaved(); } public virtual void AddItem(T item) { this.Items.Add(item); this.SelectedItem = item; var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); var collection = this.GetCollection(service, item); item.AppendTo(collection); service.ServerManager.CommitChanges(); this.OnSettingsSaved(); } private ConfigurationElementCollection GetCollection(IConfigurationService service, T item) { var duo = item as IDuoItem<T>; if (duo == null || duo.Allowed) { return GetCollection(service); } return GetSecondaryCollection(service); } public virtual void InsertItem(int index, T item) { this.Items.Insert(index, item); this.SelectedItem = item; var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); var collection = this.GetCollection(service); item.Element = collection.CreateElement(); item.Apply(); collection.AddAt(index, item.Element); service.ServerManager.CommitChanges(); this.OnSettingsSaved(); } public virtual void EditItem(T newItem) { var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); if (newItem.Flag != "Local") { ConfigurationElementCollection collection = this.GetCollection(service); collection.Remove(newItem.Element); newItem.AppendTo(collection); newItem.Flag = "Local"; } else { newItem.Apply(); } service.ServerManager.CommitChanges(); this.OnSettingsSaved(); } public virtual void RemoveItem() { this.Items.Remove(this.SelectedItem); var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); ConfigurationElementCollection collection = GetCollection(service, SelectedItem); try { collection.Remove(this.SelectedItem.Element); } catch (FileLoadException ex) { DisplayErrorMessage(ex, null); return; } service.ServerManager.CommitChanges(); this.SelectedItem = default(T); this.OnSettingsSaved(); } public virtual void MoveUpItem() { int index = this.Items.IndexOf(this.SelectedItem); this.Items.Remove(this.SelectedItem); this.Items.Insert(index - 1, this.SelectedItem); var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); var collection = GetCollection(service); var element = collection[index]; collection.Remove(element); collection.AddAt(index - 1, element); service.ServerManager.CommitChanges(); this.OnSettingsSaved(); } public virtual void MoveDownItem() { int index = this.Items.IndexOf(this.SelectedItem); this.Items.Remove(this.SelectedItem); this.Items.Insert(index + 1, this.SelectedItem); var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); var collection = GetCollection(service); var element = collection[index]; collection.Remove(element); collection.AddAt(index + 1, element); service.ServerManager.CommitChanges(); this.OnSettingsSaved(); } public virtual void RevertItems() { var service = (IConfigurationService)this.GetService(typeof(IConfigurationService)); var collection = GetCollection(service); collection.Revert(); service.ServerManager.CommitChanges(); this.SelectedItem = null; LoadItems(); } protected virtual ConfigurationElementCollection GetSecondaryCollection(IConfigurationService service) { return null; } } }
//--------------------------------------------------------------------------- // <copyright file="FixedHighlight.cs" company="Microsoft"> // Copyright (C) 2003 by Microsoft Corporation. All rights reserved. // </copyright> // // Description: // Implements FixedHighlight // // History: // 1/11/2004 - Zhenbin Xu (ZhenbinX) - Created. // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal.Documents; using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Media; // Brush using System.Windows.Media.TextFormatting; // CharacterHit using System.Windows.Shapes; // Glyphs using System.Windows.Controls; // Image //===================================================================== /// <summary> /// FixedHighlight represents partial glyph run that is highlighted on a fixed document. /// </summary> internal sealed class FixedHighlight { //-------------------------------------------------------------------- // // Connstructors // //--------------------------------------------------------------------- #region Constructors /// <summary> /// Create a new FixedHighlight for a Glyphs with character offset of /// beginOffset to endOffset, to be rendered with a given brush. /// </summary> internal FixedHighlight(UIElement element, int beginOffset, int endOffset, FixedHighlightType t, Brush foreground, Brush background) { Debug.Assert(element != null && beginOffset >= 0 && endOffset >= 0); _element = element; _gBeginOffset = beginOffset; _gEndOffset = endOffset; _type = t; _foregroundBrush = foreground; _backgroundBrush = background; } #endregion Constructors //-------------------------------------------------------------------- // // Public Methods // //--------------------------------------------------------------------- #region Public Methods /// <summary> /// Compares 2 FixedHighlight /// </summary> /// <param name="oCompare">the FixedHighlight to compare with</param> /// <returns>true if this FixedHighlight is on the same element with the same offset, and brush</returns> override public bool Equals(object oCompare) { FixedHighlight fh = oCompare as FixedHighlight; if (fh == null) { return false; } return (fh._element == _element) && (fh._gBeginOffset == _gBeginOffset) && (fh._gEndOffset == _gEndOffset) && (fh._type == _type); } /// <summary> /// Overloaded method from object /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { return _element == null ? 0 : _element.GetHashCode() + _gBeginOffset + _gEndOffset + (int)_type; } #endregion Public Methods //-------------------------------------------------------------------- // // Public Properties // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Public Events // //--------------------------------------------------------------------- //-------------------------------------------------------------------- // // Internal Methods // //--------------------------------------------------------------------- #region Internal Methods // Compute the rectangle that covers this highlight internal Rect ComputeDesignRect() { Glyphs g = _element as Glyphs; if (g == null) { Image im = _element as Image; if (im != null && im.Source != null) { return new Rect(0, 0, im.Width, im.Height); } else { Path p = _element as Path; if (p != null) { return p.Data.Bounds; } } return Rect.Empty; } GlyphRun run = g.MeasurementGlyphRun; // g.ToGlyphRun(); if (run == null || _gBeginOffset >= _gEndOffset) { return Rect.Empty; } Rect designRect = run.ComputeAlignmentBox(); designRect.Offset(g.OriginX, g.OriginY); int chrct = (run.Characters == null ? 0 : run.Characters.Count); Debug.Assert(_gBeginOffset >= 0); Debug.Assert(_gEndOffset <= chrct); double x1, x2, width; x1 = run.GetDistanceFromCaretCharacterHit(new CharacterHit(_gBeginOffset, 0)); if (_gEndOffset == chrct) { x2 = run.GetDistanceFromCaretCharacterHit(new CharacterHit(chrct - 1, 1)); } else { x2 = run.GetDistanceFromCaretCharacterHit(new CharacterHit(_gEndOffset, 0)); } if (x2 < x1) { double temp = x1; x1 = x2; x2 = temp; } width = x2 - x1; if ((run.BidiLevel & 1) != 0) { // right to left designRect.X = g.OriginX - x2; } else { designRect.X = g.OriginX + x1; } designRect.Width = width; #if DEBUG DocumentsTrace.FixedTextOM.Highlight.Trace(string.Format("DesignBound {0}", designRect)); #endif return designRect; } #endregion Internal Methods //-------------------------------------------------------------------- // // Internal Properties // //--------------------------------------------------------------------- #region Internal Properties internal FixedHighlightType HighlightType { get { return _type; } } internal Glyphs Glyphs { get { return _element as Glyphs; } } internal UIElement Element { get { return _element; } } internal Brush ForegroundBrush { get { return _foregroundBrush; } } internal Brush BackgroundBrush { get { return _backgroundBrush; } } #endregion Internal Properties //-------------------------------------------------------------------- // // Private Fields // //--------------------------------------------------------------------- #region Private Fields private readonly UIElement _element; // the Glyphs element, or possibly an image private readonly int _gBeginOffset; // Begin character offset with Glyphs private readonly int _gEndOffset; // End character offset with Glyphs private readonly FixedHighlightType _type; // Type of highlight private readonly Brush _backgroundBrush; // highlight background brush private readonly Brush _foregroundBrush; // highlight foreground brush #endregion Private Fields } /// <summary> /// Flags determine type of highlight /// </summary> internal enum FixedHighlightType { None = 0, TextSelection = 1, AnnotationHighlight = 2 } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; namespace EduHub.Data.Entities { /// <summary> /// Tax Scales /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PX : EduHubEntity { #region Foreign Navigation Properties private IReadOnlyList<PE> Cache_PXKEY_PE_TAXCODE; #endregion /// <inheritdoc /> public override DateTime? EntityLastModified { get { return LW_DATE; } } #region Field Properties /// <summary> /// Tax scale number /// </summary> public short PXKEY { get; internal set; } /// <summary> /// Description /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION01 { get; internal set; } /// <summary> /// Description /// [Alphanumeric (30)] /// </summary> public string DESCRIPTION02 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME01 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME02 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME03 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME04 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME05 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME06 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME07 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME08 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME09 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME10 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME11 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME12 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME13 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME14 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME15 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME16 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME17 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME18 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME19 { get; internal set; } /// <summary> /// End incomes for 8 brackets /// </summary> public decimal? ENDINCOME20 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA01 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA02 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA03 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA04 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA05 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA06 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA07 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA08 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA09 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA10 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA11 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA12 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA13 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA14 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA15 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA16 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA17 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA18 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA19 { get; internal set; } /// <summary> /// Coefficient A /// </summary> public double? COEFA20 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB01 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB02 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB03 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB04 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB05 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB06 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB07 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB08 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB09 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB10 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB11 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB12 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB13 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB14 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB15 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB16 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB17 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB18 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB19 { get; internal set; } /// <summary> /// Coefficient B /// </summary> public double? COEFB20 { get; internal set; } /// <summary> /// &lt;No documentation available&gt; /// </summary> public DateTime? TRANSDATE { get; internal set; } /// <summary> /// Includes HECS Y/N /// [Uppercase Alphanumeric (1)] /// </summary> public string HECS { get; internal set; } /// <summary> /// Last write date /// </summary> public DateTime? LW_DATE { get; internal set; } /// <summary> /// Last write time /// </summary> public short? LW_TIME { get; internal set; } /// <summary> /// Last operator /// [Uppercase Alphanumeric (128)] /// </summary> public string LW_USER { get; internal set; } #endregion #region Foreign Navigation Properties /// <summary> /// PE (Employees) related entities by [PX.PXKEY]-&gt;[PE.TAXCODE] /// Tax scale number /// </summary> public IReadOnlyList<PE> PXKEY_PE_TAXCODE { get { if (Cache_PXKEY_PE_TAXCODE == null && !Context.PE.TryFindByTAXCODE(PXKEY, out Cache_PXKEY_PE_TAXCODE)) { Cache_PXKEY_PE_TAXCODE = new List<PE>().AsReadOnly(); } return Cache_PXKEY_PE_TAXCODE; } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using CustomerPortal.Areas.HelpPage.ModelDescriptions; using CustomerPortal.Areas.HelpPage.Models; namespace CustomerPortal.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }